diff options
386 files changed, 10444 insertions, 3568 deletions
@@ -25,7 +25,7 @@ sudo apt-get install repo git-core gnupg flex bison gperf build-essential \ libgl1-mesa-dev libxml2-utils xsltproc unzip liblz4-tool libssl-dev \ libc++-dev libevent-dev \ flatbuffers-compiler libflatbuffers1 openssl \ - libflatbuffers-dev libtinyxml2-dev \ + libflatbuffers-dev libfmt-dev libtinyxml2-dev \ libglib2.0-dev libevent-dev libnss3-dev libdbus-1-dev \ libprotobuf-dev ninja-build generate-ninja protobuf-compiler \ libre2-9 debmake \ diff --git a/android/app/Android.bp b/android/app/Android.bp index 365851ceab..e97384e248 100644 --- a/android/app/Android.bp +++ b/android/app/Android.bp @@ -110,6 +110,7 @@ cc_library_shared { "libbluetooth_core_rs_bridge", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-audio-asrc", "libbt-audio-hal-interface", "libbt-bta", diff --git a/android/app/AndroidManifest.xml b/android/app/AndroidManifest.xml index 17490a6c2d..c87c771bca 100644 --- a/android/app/AndroidManifest.xml +++ b/android/app/AndroidManifest.xml @@ -104,12 +104,12 @@ </service> <service android:process="@string/process" - android:name="com.android.bluetooth.airplane.NotificationHelperService" - android:label="Airplane Notification Helper" + android:name="com.android.bluetooth.notification.NotificationHelperService" + android:label="Notification Helper" android:exported="true" android:permission="android.permission.BLUETOOTH_PRIVILEGED"> <intent-filter> - <action android:name="android.bluetooth.airplane.action.SEND_NOTIFICATION"/> + <action android:name="android.bluetooth.notification.action.SEND_TOGGLE_NOTIFICATION"/> </intent-filter> </service> diff --git a/android/app/aidl/android/bluetooth/IBluetooth.aidl b/android/app/aidl/android/bluetooth/IBluetooth.aidl index 277999a5b6..b937d99d97 100644 --- a/android/app/aidl/android/bluetooth/IBluetooth.aidl +++ b/android/app/aidl/android/bluetooth/IBluetooth.aidl @@ -313,4 +313,10 @@ interface IBluetooth @JavaPassthrough(annotation="@android.annotation.RequiresNoPermission") oneway void getProfile(int profile, in SynchronousResultReceiver receiver); + + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + oneway void setActiveAudioDevicePolicy(in BluetoothDevice device, int activeAudioDevicePolicy, in AttributionSource source, in SynchronousResultReceiver receiver); + + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + oneway void getActiveAudioDevicePolicy(in BluetoothDevice device, in AttributionSource source, in SynchronousResultReceiver receiver); } diff --git a/android/app/aidl/android/bluetooth/IBluetoothHidHost.aidl b/android/app/aidl/android/bluetooth/IBluetoothHidHost.aidl index 421e1ada88..1753700b6b 100644 --- a/android/app/aidl/android/bluetooth/IBluetoothHidHost.aidl +++ b/android/app/aidl/android/bluetooth/IBluetoothHidHost.aidl @@ -42,6 +42,10 @@ oneway interface IBluetoothHidHost { void setConnectionPolicy(in BluetoothDevice device, int connectionPolicy, in AttributionSource attributionSource, in SynchronousResultReceiver receiver); @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") void getConnectionPolicy(in BluetoothDevice device, in AttributionSource attributionSource, in SynchronousResultReceiver receiver); + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + void setPreferredTransport(in BluetoothDevice device, int transport, in AttributionSource attributionSource, in SynchronousResultReceiver receiver); + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + void getPreferredTransport(in BluetoothDevice device, in AttributionSource attributionSource, in SynchronousResultReceiver receiver); @JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)") void getProtocolMode(in BluetoothDevice device, in AttributionSource attributionSource, in SynchronousResultReceiver receiver); @JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)") diff --git a/android/app/aidl/android/bluetooth/IBluetoothLeAudio.aidl b/android/app/aidl/android/bluetooth/IBluetoothLeAudio.aidl index ef51fa4fe3..9c6f87e7c5 100644 --- a/android/app/aidl/android/bluetooth/IBluetoothLeAudio.aidl +++ b/android/app/aidl/android/bluetooth/IBluetoothLeAudio.aidl @@ -81,6 +81,9 @@ oneway interface IBluetoothLeAudio { const int GROUP_NODE_ADDED = 1; const int GROUP_NODE_REMOVED = 2; + const int GROUP_STREAM_STATUS_IDLE = 0; + const int GROUP_STREAM_STATUS_STREAMING = 1; + /** * Get device group id. Devices with same group id belong to same group (i.e left and right * earbud) diff --git a/android/app/jni/com_android_bluetooth_gatt.cpp b/android/app/jni/com_android_bluetooth_gatt.cpp index 82751504f8..752dd56503 100644 --- a/android/app/jni/com_android_bluetooth_gatt.cpp +++ b/android/app/jni/com_android_bluetooth_gatt.cpp @@ -1551,8 +1551,8 @@ static void gattSetScanParametersNative(JNIEnv* /* env */, jobject /* object */, jint scan_window_unit) { if (!sGattIf) return; sGattIf->scanner->SetScanParameters( - client_if, scan_interval_unit, scan_window_unit, - base::Bind(&set_scan_params_cmpl_cb, client_if)); + client_if, /* use active scan */ 0x01, scan_interval_unit, + scan_window_unit, base::Bind(&set_scan_params_cmpl_cb, client_if)); } void scan_filter_param_cb(uint8_t client_if, uint8_t avbl_space, uint8_t action, diff --git a/android/app/res/drawable/bt_incomming_file_notification.xml b/android/app/res/drawable/ic_bluetooth_file_transfer_notification.xml index ed45b3bce3..ed45b3bce3 100644 --- a/android/app/res/drawable/bt_incomming_file_notification.xml +++ b/android/app/res/drawable/ic_bluetooth_file_transfer_notification.xml diff --git a/android/app/src/com/android/bluetooth/a2dp/A2dpService.java b/android/app/src/com/android/bluetooth/a2dp/A2dpService.java index 2cb65a374b..a8be371b5f 100644 --- a/android/app/src/com/android/bluetooth/a2dp/A2dpService.java +++ b/android/app/src/com/android/bluetooth/a2dp/A2dpService.java @@ -148,7 +148,7 @@ public class A2dpService extends ProfileService { } @Override - protected void start() { + public void start() { Log.i(TAG, "start()"); if (sA2dpService != null) { throw new IllegalStateException("start() called twice"); @@ -205,7 +205,7 @@ public class A2dpService extends ProfileService { } @Override - protected void stop() { + public void stop() { Log.i(TAG, "stop()"); if (sA2dpService == null) { Log.w(TAG, "stop() called before start()"); @@ -259,7 +259,7 @@ public class A2dpService extends ProfileService { } @Override - protected void cleanup() { + public void cleanup() { Log.i(TAG, "cleanup()"); } diff --git a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java index 465efda0f0..c823b7676f 100644 --- a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java +++ b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java @@ -92,7 +92,7 @@ public class A2dpSinkService extends ProfileService { } @Override - protected void start() { + public void start() { mAdapterService = requireNonNull( AdapterService.getAdapterService(), @@ -113,7 +113,7 @@ public class A2dpSinkService extends ProfileService { } @Override - protected void stop() { + public void stop() { setA2dpSinkService(null); mNativeInterface.cleanup(); for (A2dpSinkStateMachine stateMachine : mDeviceStateMap.values()) { @@ -636,6 +636,13 @@ public class A2dpSinkService extends ProfileService { return; } A2dpSinkStateMachine stateMachine = getStateMachineForDevice(device); + if (stateMachine == null) { + Log.w( + TAG, + "Received audio config changed event for an unconnected device, device=" + + device); + return; + } stateMachine.onStackEvent(event); } diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java index b71db82853..0e33c42d89 100644 --- a/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java +++ b/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java @@ -188,7 +188,7 @@ public class AvrcpTargetService extends ProfileService { } @Override - protected void start() { + public void start() { if (sInstance != null) { throw new IllegalStateException("start() called twice"); } @@ -244,7 +244,7 @@ public class AvrcpTargetService extends ProfileService { } @Override - protected void stop() { + public void stop() { Log.i(TAG, "Stopping the AVRCP Target Service"); if (sInstance == null) { diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java index 48b1d545ba..fc9248cb6f 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java @@ -150,7 +150,7 @@ public class AvrcpControllerService extends ProfileService { } @Override - protected synchronized void start() { + public synchronized void start() { mNativeInterface.init(this); setComponentAvailable(ON_ERROR_SETTINGS_ACTIVITY, true); mAdapterService = AdapterService.getAdapterService(); @@ -169,7 +169,7 @@ public class AvrcpControllerService extends ProfileService { } @Override - protected synchronized void stop() { + public synchronized void stop() { setActiveDevice(null); Intent stopIntent = new Intent(this, BluetoothMediaBrowserService.class); stopService(stopIntent); diff --git a/android/app/src/com/android/bluetooth/bas/BatteryService.java b/android/app/src/com/android/bluetooth/bas/BatteryService.java index 862bfdba98..e52220dd9d 100644 --- a/android/app/src/com/android/bluetooth/bas/BatteryService.java +++ b/android/app/src/com/android/bluetooth/bas/BatteryService.java @@ -80,7 +80,7 @@ public class BatteryService extends ProfileService { } @Override - protected void start() { + public void start() { if (DBG) { Log.d(TAG, "start()"); } @@ -102,7 +102,7 @@ public class BatteryService extends ProfileService { } @Override - protected void stop() { + public void stop() { if (DBG) { Log.d(TAG, "stop()"); } @@ -143,7 +143,7 @@ public class BatteryService extends ProfileService { } @Override - protected void cleanup() { + public void cleanup() { if (DBG) { Log.d(TAG, "cleanup()"); } 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 c5c4eae13d..ba068604fb 100644 --- a/android/app/src/com/android/bluetooth/bass_client/BassClientService.java +++ b/android/app/src/com/android/bluetooth/bass_client/BassClientService.java @@ -374,7 +374,7 @@ public class BassClientService extends ProfileService { } @Override - protected void start() { + public void start() { if (DBG) { Log.d(TAG, "start()"); } @@ -408,7 +408,7 @@ public class BassClientService extends ProfileService { } @Override - protected void stop() { + public void stop() { if (DBG) { Log.d(TAG, "stop()"); } 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 11fdbf05c1..595021214a 100644 --- a/android/app/src/com/android/bluetooth/bass_client/BassClientStateMachine.java +++ b/android/app/src/com/android/bluetooth/bass_client/BassClientStateMachine.java @@ -1499,10 +1499,12 @@ public class BassClientStateMachine extends StateMachine { stream.write((metaData.getBroadcastId() & 0x0000000000FF0000) >>> 16); // PA_Sync - if (!mDefNoPAS) { - stream.write(0x01); + if (mDefNoPAS) { + // Synchronize to PA – PAST not available + stream.write(0x02); } else { - stream.write(0x00); + // Synchronize to PA – PAST available + stream.write(0x01); } // PA_Interval diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterService.java b/android/app/src/com/android/bluetooth/btservice/AdapterService.java index 3ff04d1e04..4313fee7c4 100644 --- a/android/app/src/com/android/bluetooth/btservice/AdapterService.java +++ b/android/app/src/com/android/bluetooth/btservice/AdapterService.java @@ -128,7 +128,6 @@ import com.android.bluetooth.csip.CsipSetCoordinatorService; import com.android.bluetooth.flags.FeatureFlagsImpl; import com.android.bluetooth.flags.Flags; import com.android.bluetooth.gatt.GattService; -import com.android.bluetooth.le_scan.ScanManager; import com.android.bluetooth.hap.HapClientService; import com.android.bluetooth.hearingaid.HearingAidService; import com.android.bluetooth.hfp.HeadsetService; @@ -136,6 +135,7 @@ import com.android.bluetooth.hfpclient.HeadsetClientService; import com.android.bluetooth.hid.HidDeviceService; import com.android.bluetooth.hid.HidHostService; import com.android.bluetooth.le_audio.LeAudioService; +import com.android.bluetooth.le_scan.ScanManager; import com.android.bluetooth.map.BluetoothMapService; import com.android.bluetooth.mapclient.MapClientService; import com.android.bluetooth.mcp.McpService; @@ -1049,8 +1049,10 @@ public class AdapterService extends Service { mGattService = new GattService(this); mStartedProfiles.put(BluetoothProfile.GATT, mGattService); - - ((ProfileService) mGattService).doStart(); + addProfile(mGattService); + mGattService.start(); + mGattService.setAvailable(true); + onProfileServiceStateChanged(mGattService, BluetoothAdapter.STATE_ON); } private void stopGattProfileService() { @@ -1062,7 +1064,12 @@ public class AdapterService extends Service { mStartedProfiles.remove(BluetoothProfile.GATT); if (mGattService != null) { - ((ProfileService) mGattService).doStop(); + mGattService.setAvailable(false); + onProfileServiceStateChanged(mGattService, BluetoothAdapter.STATE_OFF); + mGattService.stop(); + removeProfile(mGattService); + mGattService.cleanup(); + mGattService.getBinder().cleanup(); mGattService = null; } } @@ -1462,7 +1469,10 @@ public class AdapterService extends Service { if (!mStartedProfiles.containsKey(profileId)) { ProfileService profileService = PROFILE_CONSTRUCTORS.get(profileId).apply(this); mStartedProfiles.put(profileId, profileService); - profileService.doStart(); + addProfile(profileService); + profileService.start(); + profileService.setAvailable(true); + onProfileServiceStateChanged(profileService, BluetoothAdapter.STATE_ON); } else { Log.e( TAG, @@ -1473,7 +1483,12 @@ public class AdapterService extends Service { } else if (state == BluetoothAdapter.STATE_OFF) { ProfileService profileService = mStartedProfiles.remove(profileId); if (profileService != null) { - profileService.doStop(); + profileService.setAvailable(false); + onProfileServiceStateChanged(profileService, BluetoothAdapter.STATE_OFF); + profileService.stop(); + removeProfile(profileService); + profileService.cleanup(); + profileService.getBinder().cleanup(); } else { Log.e( TAG, @@ -5389,6 +5404,82 @@ public class AdapterService extends Service { return service.getProfile(profileId); } + + @Override + public void setActiveAudioDevicePolicy( + BluetoothDevice device, + int activeAudioDevicePolicy, + AttributionSource source, + SynchronousResultReceiver receiver) { + try { + receiver.send(setActiveAudioDevicePolicy(device, activeAudioDevicePolicy, source)); + } catch (RuntimeException e) { + receiver.propagateException(e); + } + } + + @RequiresPermission( + allOf = { + android.Manifest.permission.BLUETOOTH_CONNECT, + android.Manifest.permission.BLUETOOTH_PRIVILEGED, + }) + private int setActiveAudioDevicePolicy( + BluetoothDevice device, int activeAudioDevicePolicy, AttributionSource source) { + AdapterService service = getService(); + if (service == null) { + return BluetoothStatusCodes.ERROR_BLUETOOTH_NOT_ENABLED; + } + if (!callerIsSystemOrActiveOrManagedUser(service, TAG, "setActiveAudioDevicePolicy")) { + return BluetoothStatusCodes.ERROR_BLUETOOTH_NOT_ALLOWED; + } + if (!BluetoothAdapter.checkBluetoothAddress(device.getAddress())) { + throw new IllegalArgumentException("device cannot have an invalid address"); + } + if (!Utils.checkConnectPermissionForDataDelivery(service, source, TAG)) { + return BluetoothStatusCodes.ERROR_MISSING_BLUETOOTH_CONNECT_PERMISSION; + } + + enforceBluetoothPrivilegedPermission(service); + return service.mDatabaseManager.setActiveAudioDevicePolicy( + device, activeAudioDevicePolicy); + } + + @Override + public void getActiveAudioDevicePolicy( + BluetoothDevice device, + AttributionSource source, + SynchronousResultReceiver receiver) { + try { + receiver.send(getActiveAudioDevicePolicy(device, source)); + } catch (RuntimeException e) { + receiver.propagateException(e); + } + } + + @RequiresPermission( + allOf = { + android.Manifest.permission.BLUETOOTH_CONNECT, + android.Manifest.permission.BLUETOOTH_PRIVILEGED, + }) + private int getActiveAudioDevicePolicy(BluetoothDevice device, AttributionSource source) { + AdapterService service = getService(); + if (service == null) { + return BluetoothDevice.ACTIVE_AUDIO_DEVICE_POLICY_DEFAULT; + } + if (!callerIsSystemOrActiveOrManagedUser(service, TAG, "getActiveAudioDevicePolicy")) { + 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, TAG)) { + return BluetoothDevice.ACTIVE_AUDIO_DEVICE_POLICY_DEFAULT; + } + + enforceBluetoothPrivilegedPermission(service); + return service.mDatabaseManager.getActiveAudioDevicePolicy(device); + } } /** diff --git a/android/app/src/com/android/bluetooth/btservice/AudioRoutingManager.java b/android/app/src/com/android/bluetooth/btservice/AudioRoutingManager.java index fe6caf4185..6b0865e4ac 100644 --- a/android/app/src/com/android/bluetooth/btservice/AudioRoutingManager.java +++ b/android/app/src/com/android/bluetooth/btservice/AudioRoutingManager.java @@ -51,10 +51,13 @@ import com.android.internal.annotations.VisibleForTesting; import com.android.modules.utils.SynchronousResultReceiver; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; +import java.util.NoSuchElementException; import java.util.Objects; +import java.util.Optional; import java.util.Set; public class AudioRoutingManager extends ActiveDeviceManager { @@ -309,8 +312,8 @@ public class AudioRoutingManager extends ActiveDeviceManager { List<BluetoothDevice> activeDevices = mActiveDevices.get(profile); if (activeDevices != null && activeDevices.contains(device)) { activeDevices.remove(device); - if (activeDevices.size() == 0) { - if (!setFallbackDeviceActive()) { + if (activeDevices.isEmpty()) { + if (!setFallbackDeviceActive(profile)) { removeActiveDevice(profile, false); } } @@ -329,53 +332,69 @@ public class AudioRoutingManager extends ActiveDeviceManager { + device); } - private boolean setFallbackDeviceActive() { + private Optional<BluetoothDevice> getFallbackDevice( + Collection<AudioRoutingDevice> candidates) { + List<BluetoothDevice> activatableDevices = new ArrayList<>(); + for (AudioRoutingDevice d : candidates) { + if (d.isA2dpOnly() || d.isHfpOnly()) continue; + boolean canActivate = true; + for (int p : d.connectedProfiles) { + if (!d.canActivateNow(p)) { + canActivate = false; + break; + } else if (p != BluetoothProfile.A2DP && p != BluetoothProfile.HEADSET) { + break; + } + } + if (canActivate) { + activatableDevices.add(d.device); + } + } + return Optional.ofNullable( + mDbManager.getMostRecentlyConnectedDevicesInList(activatableDevices)); + } + + private boolean setFallbackDeviceActive(int profile) { if (DBG) { - Log.d(TAG, "setFallbackDeviceActive"); - } - List<BluetoothDevice> candidates = new ArrayList<>(); - int audioMode = mAudioManager.getMode(); - for (AudioRoutingDevice routingDevice : mConnectedDevices.values()) { - for (int profile : routingDevice.connectedProfiles) { - if (audioMode == AudioManager.MODE_NORMAL) { - if (profile != BluetoothProfile.HEADSET) { - candidates.add(routingDevice.device); - break; - } + Log.d(TAG, "setFallbackDeviceActive: " + BluetoothProfile.getProfileName(profile)); + } + // 1. Activate the lastly activated device among currently activated devices. + Set<AudioRoutingDevice> candidates = new HashSet<>(); + for (int i = 0; i < mActiveDevices.size(); ++i) { + for (BluetoothDevice d : mActiveDevices.valueAt(i)) { + candidates.add(getAudioRoutingDevice(d)); + } + } + try { + // 2. Activate the lastly activated device for the profile + Optional<BluetoothDevice> fallbackDevice = + getFallbackDevice(candidates) + .or(() -> getFallbackDevice(mConnectedDevices.values())); + AudioRoutingDevice fallbackRoutingDevice = + getAudioRoutingDevice(fallbackDevice.get()); + int profileToActivate = profile; + if (!fallbackRoutingDevice.canActivateNow(profile)) { + // if it can't activate the given profile, try LE_AUDIO + if (fallbackRoutingDevice.canActivateNow(BluetoothProfile.LE_AUDIO)) { + profileToActivate = BluetoothProfile.LE_AUDIO; } else { - if (profile != BluetoothProfile.A2DP) { - candidates.add(routingDevice.device); - break; + // if it can't activate both the given profile and LE_AUDIO, select any + for (int p : fallbackRoutingDevice.connectedProfiles) { + if (fallbackRoutingDevice.canActivateNow(p)) { + profileToActivate = p; + break; + } } } } - } - AudioRoutingDevice deviceToActivate = null; - BluetoothDevice device = mDbManager.getMostRecentlyConnectedDevicesInList(candidates); - if (device != null) { - deviceToActivate = getAudioRoutingDevice(device); - } - if (deviceToActivate != null) { + return activateDeviceProfile(fallbackRoutingDevice, profileToActivate); + } catch (NoSuchElementException e) { + // Thrown when no available fallback devices found if (DBG) { - Log.d(TAG, "activateDevice: device=" + deviceToActivate.device); + Log.d(TAG, "Found no available BT fallback devices."); } - // Try to activate hearing aid and LE audio first - if (deviceToActivate.connectedProfiles.contains(BluetoothProfile.HEARING_AID)) { - return activateDeviceProfile(deviceToActivate, BluetoothProfile.HEARING_AID); - } else if (deviceToActivate.connectedProfiles.contains(BluetoothProfile.LE_AUDIO)) { - return activateDeviceProfile(deviceToActivate, BluetoothProfile.LE_AUDIO); - } else if (deviceToActivate.connectedProfiles.contains(BluetoothProfile.A2DP)) { - return activateDeviceProfile(deviceToActivate, BluetoothProfile.A2DP); - } else if (deviceToActivate.connectedProfiles.contains(BluetoothProfile.HEADSET)) { - return activateDeviceProfile(deviceToActivate, BluetoothProfile.HEADSET); - } - Log.w( - TAG, - "Fail to activate the device: " - + deviceToActivate.device - + ", no connected audio profiles"); + return false; } - return false; } // TODO: handle the connection policy change events. @@ -660,7 +679,7 @@ public class AudioRoutingManager extends ActiveDeviceManager { for (int p : connectedDevice.supportedProfiles) { if (!getActiveDevices(p).isEmpty()) { BluetoothMethodProxy mp = BluetoothMethodProxy.getInstance(); - if (mp.mediaSessionManagerGetActiveSessions(mSessionManager).size() > 0 + if (!mp.mediaSessionManagerGetActiveSessions(mSessionManager).isEmpty() || mAudioManager.getMode() == AudioManager.MODE_IN_CALL) { Log.i( TAG, @@ -733,7 +752,6 @@ public class AudioRoutingManager extends ActiveDeviceManager { public boolean canActivateNow(int profile) { if (!connectedProfiles.contains(profile)) return false; - // TODO: Return false if there are another active remote streaming an audio. return switch (profile) { case BluetoothProfile.HEADSET -> !supportedProfiles.contains( BluetoothProfile.A2DP) diff --git a/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java b/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java index ea4c1fd102..10c9afb9df 100644 --- a/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java +++ b/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java @@ -158,7 +158,7 @@ public class PhonePolicy implements AdapterService.BluetoothStateCallback { ; // Policy API functions for lifecycle management (protected) - protected void start() { + public void start() { mAdapterService.registerBluetoothStateCallback((command) -> mHandler.post(command), this); IntentFilter filter = new IntentFilter(); @@ -166,7 +166,7 @@ public class PhonePolicy implements AdapterService.BluetoothStateCallback { filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); } - protected void cleanup() { + public void cleanup() { mAdapterService.unregisterBluetoothStateCallback(this); resetStates(); } diff --git a/android/app/src/com/android/bluetooth/btservice/ProfileService.java b/android/app/src/com/android/bluetooth/btservice/ProfileService.java index 3a9226d007..3190463e71 100644 --- a/android/app/src/com/android/bluetooth/btservice/ProfileService.java +++ b/android/app/src/com/android/bluetooth/btservice/ProfileService.java @@ -21,17 +21,14 @@ import static java.util.Objects.requireNonNull; import android.annotation.RequiresPermission; import android.annotation.SuppressLint; -import android.bluetooth.BluetoothAdapter; import android.content.ComponentName; import android.content.Context; import android.content.ContextWrapper; -import android.content.Intent; import android.content.pm.PackageManager; import android.os.IBinder; import android.util.Log; import com.android.bluetooth.BluetoothMetricsProto; -import com.android.internal.annotations.VisibleForTesting; /** Base class for a background service that runs a Bluetooth profile */ public abstract class ProfileService extends ContextWrapper { @@ -43,16 +40,13 @@ public abstract class ProfileService extends ContextWrapper { android.Manifest.permission.BLUETOOTH_PRIVILEGED; public interface IProfileServiceBinder extends IBinder { - /** - * Called in {@link #onDestroy()} - */ void cleanup(); } private final IProfileServiceBinder mBinder; private final String mName; private AdapterService mAdapterService; - private boolean mProfileStarted = false; + private boolean mAvailable = false; private volatile boolean mTestModeEnabled = false; public String getName() { @@ -60,7 +54,11 @@ public abstract class ProfileService extends ContextWrapper { } public boolean isAvailable() { - return mProfileStarted; + return mAvailable; + } + + public void setAvailable(boolean available) { + mAvailable = available; } protected boolean isTestModeEnabled() { @@ -74,20 +72,14 @@ public abstract class ProfileService extends ContextWrapper { */ protected abstract IProfileServiceBinder initBinder(); - /** - * Called in {@link #onStartCommand(Intent, int, int)} when the service is started by intent - */ - protected abstract void start(); + /** Start service */ + public abstract void start(); - /** - * Called in {@link #onStartCommand(Intent, int, int)} when the service is stopped by intent - */ - protected abstract void stop(); + /** Stop service */ + public abstract void stop(); - /** - * Called in {@link #onDestroy()} when this object is completely discarded - */ - protected void cleanup() {} + /** Called when this object is completely discarded */ + public void cleanup() {} /** * @param testModeEnabled if the profile should enter or exit a testing mode @@ -106,7 +98,7 @@ public abstract class ProfileService extends ContextWrapper { } /** return the binder of the profile */ - public IBinder getBinder() { + public IProfileServiceBinder getBinder() { return mBinder; } @@ -195,50 +187,4 @@ public abstract class ProfileService extends ContextWrapper { sb.append(s); sb.append("\n"); } - - /** start the profile and inform AdapterService */ - @RequiresPermission( - anyOf = { - android.Manifest.permission.MANAGE_USERS, - android.Manifest.permission.INTERACT_ACROSS_USERS - }) - @VisibleForTesting - public void doStart() { - Log.v(mName, "doStart"); - mAdapterService = AdapterService.getAdapterService(); - if (mAdapterService == null) { - Log.w(mName, "Could not add this profile because AdapterService is null."); - return; - } - mAdapterService.addProfile(this); - - start(); - mProfileStarted = true; - - mAdapterService.onProfileServiceStateChanged(this, BluetoothAdapter.STATE_ON); - } - - /** stop the profile and inform AdapterService */ - @VisibleForTesting - public void doStop() { - Log.v(mName, "doStop"); - if (mAdapterService == null) { - Log.w(mName, "Unexpectedly do Stop, don't stop."); - return; - } - if (!mProfileStarted) { - Log.w(mName, "doStop() called, but the profile is not running."); - return; - } - mProfileStarted = false; - if (mAdapterService != null) { - mAdapterService.onProfileServiceStateChanged(this, BluetoothAdapter.STATE_OFF); - } - stop(); - if (mAdapterService != null) { - mAdapterService.removeProfile(this); - } - cleanup(); - mBinder.cleanup(); - } } diff --git a/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java b/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java index b42180d754..5e3971264b 100644 --- a/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java +++ b/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java @@ -236,6 +236,10 @@ public class RemoteDevices { } DeviceProperties getDeviceProperties(BluetoothDevice device) { + if (device == null) { + return null; + } + synchronized (mDevices) { String address = mDualDevicesMap.get(device.getAddress()); // If the device is not in the dual map, use its original address 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 7c9f1d8823..f9db3f7fb3 100644 --- a/android/app/src/com/android/bluetooth/btservice/storage/DatabaseManager.java +++ b/android/app/src/com/android/bluetooth/btservice/storage/DatabaseManager.java @@ -1015,6 +1015,60 @@ public class DatabaseManager { } /** + * Set the device active audio policy. See {@link + * BluetoothDevice#setActiveAudioDevicePolicy(activeAudioDevicePolicy)} for more details. + * + * @param device is the remote device for which we are setting the active audio device policy. + * @param activeAudioDevicePolicy active audio device policy. + * @return whether the policy was set properly + */ + public int setActiveAudioDevicePolicy(BluetoothDevice device, int activeAudioDevicePolicy) { + synchronized (mMetadataCache) { + String address = device.getAddress(); + + if (!mMetadataCache.containsKey(address)) { + Log.e(TAG, "device is not bonded"); + return BluetoothStatusCodes.ERROR_DEVICE_NOT_BONDED; + } + + Metadata metadata = mMetadataCache.get(address); + Log.i( + TAG, + "Updating active_audio_device_policy setting for " + + "device " + + device + + " to: " + + activeAudioDevicePolicy); + metadata.active_audio_device_policy = activeAudioDevicePolicy; + + updateDatabase(metadata); + } + return BluetoothStatusCodes.SUCCESS; + } + + /** + * Get the active audio device policy for this device. See {@link + * BluetoothDevice#getActiveAudioDevicePolicy()} for more details. + * + * @param device is the device for which we want to get the policy + * @return active audio device policy for this device + */ + public int getActiveAudioDevicePolicy(BluetoothDevice device) { + synchronized (mMetadataCache) { + String address = device.getAddress(); + + if (!mMetadataCache.containsKey(address)) { + Log.e(TAG, "device is not bonded"); + return BluetoothDevice.ACTIVE_AUDIO_DEVICE_POLICY_DEFAULT; + } + + Metadata metadata = mMetadataCache.get(address); + + return metadata.active_audio_device_policy; + } + } + + /** * Get the {@link Looper} for the handler thread. This is used in testing and helper * objects * 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 c3032ec89b..6dcf5546c0 100644 --- a/android/app/src/com/android/bluetooth/btservice/storage/Metadata.java +++ b/android/app/src/com/android/bluetooth/btservice/storage/Metadata.java @@ -79,6 +79,9 @@ public class Metadata { */ public int preferred_duplex_profile; + /** This is used to indicate whether device's active audio policy */ + public int active_audio_device_policy; + Metadata(String address) { this(address, false, false); } @@ -96,6 +99,7 @@ public class Metadata { audioPolicyMetadata = new AudioPolicyEntity(); preferred_output_only_profile = 0; preferred_duplex_profile = 0; + active_audio_device_policy = BluetoothDevice.ACTIVE_AUDIO_DEVICE_POLICY_DEFAULT; } static final class Builder { 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 f151c08c1d..fd580b00fc 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 = 119) + version = 120) public abstract class MetadataDatabase extends RoomDatabase { /** The metadata database file name */ public static final String DATABASE_NAME = "bluetooth_db"; @@ -69,6 +69,7 @@ public abstract class MetadataDatabase extends RoomDatabase { .addMigrations(MIGRATION_116_117) .addMigrations(MIGRATION_117_118) .addMigrations(MIGRATION_118_119) + .addMigrations(MIGRATION_119_120) .allowMainThreadQueries() .build(); } @@ -649,4 +650,25 @@ public abstract class MetadataDatabase extends RoomDatabase { } } }; + + @VisibleForTesting + static final Migration MIGRATION_119_120 = + new Migration(119, 120) { + @Override + public void migrate(SupportSQLiteDatabase database) { + try { + database.execSQL( + "ALTER TABLE metadata ADD COLUMN" + + " `active_audio_device_policy` 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("active_audio_device_policy") == -1) { + throw ex; + } + } + } + }; } diff --git a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java index ff234d9270..9494b10faa 100644 --- a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java +++ b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java @@ -123,7 +123,7 @@ public class CsipSetCoordinatorService extends ProfileService { } @Override - protected void start() { + public void start() { if (DBG) { Log.d(TAG, "start()"); } @@ -166,7 +166,7 @@ public class CsipSetCoordinatorService extends ProfileService { } @Override - protected void stop() { + public void stop() { if (DBG) { Log.d(TAG, "stop()"); } @@ -222,7 +222,7 @@ public class CsipSetCoordinatorService extends ProfileService { } @Override - protected void cleanup() { + public void cleanup() { if (DBG) { Log.d(TAG, "cleanup()"); } diff --git a/android/app/src/com/android/bluetooth/gatt/ContextMap.java b/android/app/src/com/android/bluetooth/gatt/ContextMap.java index 5d12569d12..f8f7ca822b 100644 --- a/android/app/src/com/android/bluetooth/gatt/ContextMap.java +++ b/android/app/src/com/android/bluetooth/gatt/ContextMap.java @@ -211,7 +211,7 @@ public class ContextMap<C, T> { private final Object mConnectionsLock = new Object(); /** Add an entry to the application context list. */ - App add( + protected App add( UUID uuid, WorkSource workSource, C callback, @@ -292,7 +292,7 @@ public class ContextMap<C, T> { /** * Remove the context for a given application ID. */ - void remove(int id) { + protected void remove(int id) { boolean find = false; synchronized (mAppsLock) { Iterator<App> i = mApps.iterator(); @@ -312,7 +312,7 @@ public class ContextMap<C, T> { } } - List<Integer> getAllAppsIds() { + protected List<Integer> getAllAppsIds() { List<Integer> appIds = new ArrayList(); synchronized (mAppsLock) { Iterator<App> i = mApps.iterator(); @@ -370,7 +370,7 @@ public class ContextMap<C, T> { /** * Get an application context by ID. */ - App getById(int id) { + protected App getById(int id) { synchronized (mAppsLock) { Iterator<App> i = mApps.iterator(); while (i.hasNext()) { @@ -387,7 +387,7 @@ public class ContextMap<C, T> { /** * Get an application context by UUID. */ - App getByUuid(UUID uuid) { + protected App getByUuid(UUID uuid) { synchronized (mAppsLock) { Iterator<App> i = mApps.iterator(); while (i.hasNext()) { @@ -421,7 +421,7 @@ public class ContextMap<C, T> { /** * Get an application context by the context info object. */ - App getByContextInfo(T contextInfo) { + protected App getByContextInfo(T contextInfo) { synchronized (mAppsLock) { Iterator<App> i = mApps.iterator(); while (i.hasNext()) { @@ -438,7 +438,7 @@ public class ContextMap<C, T> { /** * Get Logging info by ID */ - AppScanStats getAppScanStatsById(int id) { + protected AppScanStats getAppScanStatsById(int id) { App temp = getById(id); if (temp != null) { return temp.appScanStats; @@ -674,7 +674,7 @@ public class ContextMap<C, T> { /** * Erases all application context entries. */ - void clear() { + protected void clear() { synchronized (mAppsLock) { Iterator<App> i = mApps.iterator(); while (i.hasNext()) { @@ -713,7 +713,7 @@ public class ContextMap<C, T> { /** * Logs debug information. */ - void dump(StringBuilder sb) { + protected void dump(StringBuilder sb) { sb.append(" Entries: " + mAppScanStats.size() + "\n\n"); Iterator<Map.Entry<Integer, AppScanStats>> it = mAppScanStats.entrySet().iterator(); diff --git a/android/app/src/com/android/bluetooth/gatt/GattService.java b/android/app/src/com/android/bluetooth/gatt/GattService.java index a03be06580..c6d98fe984 100644 --- a/android/app/src/com/android/bluetooth/gatt/GattService.java +++ b/android/app/src/com/android/bluetooth/gatt/GattService.java @@ -100,6 +100,7 @@ import com.android.bluetooth.le_scan.AppScanStats; import com.android.bluetooth.le_scan.PeriodicScanManager; import com.android.bluetooth.le_scan.ScanClient; import com.android.bluetooth.le_scan.ScanManager; +import com.android.bluetooth.le_scan.TransitionalScanHelper; import com.android.bluetooth.util.NumberUtils; import com.android.internal.annotations.VisibleForTesting; import com.android.modules.utils.SynchronousResultReceiver; @@ -213,7 +214,7 @@ public class GattService extends ProfileService { /** * Keep the arguments passed in for the PendingIntent. */ - class PendingIntentInfo { + public static class PendingIntentInfo { public PendingIntent intent; public ScanSettings settings; public List<ScanFilter> filters; @@ -237,12 +238,7 @@ public class GattService extends ProfileService { } }; - /** - * List of our registered scanners. - */ - public static class ScannerMap extends ContextMap<IScannerCallback, PendingIntentInfo> {} - - public ScannerMap mScannerMap = new ScannerMap(); + public final TransitionalScanHelper mTransitionalScanHelper = new TransitionalScanHelper(); /** * List of our registered advertisers. @@ -284,7 +280,7 @@ public class GattService extends ProfileService { /** * Set of restricted (which require a BLUETOOTH_PRIVILEGED permission) handles per connectionId. */ - private final Map<Integer, Set<Integer>> mRestrictedHandles = new HashMap<>(); + @VisibleForTesting final Map<Integer, Set<Integer>> mRestrictedHandles = new HashMap<>(); /** * HashMap used to synchronize writeCharacteristic calls mapping remote device address to @@ -346,7 +342,7 @@ public class GattService extends ProfileService { } @Override - protected void start() { + public void start() { if (DBG) { Log.d(TAG, "start()"); } @@ -390,13 +386,16 @@ public class GattService extends ProfileService { } @Override - protected void stop() { + public void stop() { if (DBG) { Log.d(TAG, "stop()"); } - mScannerMap.clear(); + mTransitionalScanHelper.getScannerMap().clear(); mAdvertiserMap.clear(); mClientMap.clear(); + if (Flags.gattCleanupRestrictedHandles()) { + mRestrictedHandles.clear(); + } mServerMap.clear(); mHandleMap.clear(); mReliableQueue.clear(); @@ -404,7 +403,7 @@ public class GattService extends ProfileService { } @Override - protected void cleanup() { + public void cleanup() { if (DBG) { Log.d(TAG, "cleanup()"); } @@ -2017,7 +2016,8 @@ public class GattService extends ProfileService { byte[] legacyAdvData = Arrays.copyOfRange(advData, 0, 62); for (ScanClient client : mScanManager.getRegularScanQueue()) { - ScannerMap.App app = mScannerMap.getById(client.scannerId); + TransitionalScanHelper.ScannerMap.App app = + mTransitionalScanHelper.getScannerMap().getById(client.scannerId); if (app == null) { if (VDBG) { Log.d(TAG, "App is null; skip."); @@ -2109,7 +2109,7 @@ public class GattService extends ProfileService { if (Flags.leScanFixRemoteException()) { handleDeadScanClient(client); } else { - mScannerMap.remove(client.scannerId); + mTransitionalScanHelper.getScannerMap().remove(client.scannerId); mScanManager.stopScan(client.scannerId); } } @@ -2158,7 +2158,8 @@ public class GattService extends ProfileService { } // First check the callback map - ScannerMap.App cbApp = mScannerMap.getByUuid(uuid); + TransitionalScanHelper.ScannerMap.App cbApp = + mTransitionalScanHelper.getScannerMap().getByUuid(uuid); if (cbApp != null) { if (status == 0) { cbApp.id = scannerId; @@ -2170,7 +2171,7 @@ public class GattService extends ProfileService { continuePiStartScan(scannerId, cbApp); } } else { - mScannerMap.remove(scannerId); + mTransitionalScanHelper.getScannerMap().remove(scannerId); } if (cbApp.callback != null) { cbApp.callback.onScannerRegistered(status, scannerId); @@ -2281,6 +2282,10 @@ public class GattService extends ProfileService { mClientMap.removeConnection(clientIf, connId); ClientMap.App app = mClientMap.getById(clientIf); + if (Flags.gattCleanupRestrictedHandles()) { + mRestrictedHandles.remove(connId); + } + // Remove AtomicBoolean representing permit if no other connections rely on this remote device. if (!mClientMap.getConnectedDevices().contains(address)) { synchronized (mPermits) { @@ -2795,7 +2800,8 @@ public class GattService extends ProfileService { Set<ScanResult> results = parseBatchScanResults(numRecords, reportType, recordData); if (reportType == ScanManager.SCAN_RESULT_TYPE_TRUNCATED) { // We only support single client for truncated mode. - ScannerMap.App app = mScannerMap.getById(scannerId); + TransitionalScanHelper.ScannerMap.App app = + mTransitionalScanHelper.getScannerMap().getById(scannerId); if (app == null) { return; } @@ -2846,7 +2852,7 @@ public class GattService extends ProfileService { mScanManager.callbackDone(scannerId, status); } - private void sendBatchScanResults(ScannerMap.App app, ScanClient client, + private void sendBatchScanResults(TransitionalScanHelper.ScannerMap.App app, ScanClient client, ArrayList<ScanResult> results) { try { if (app.callback != null) { @@ -2873,7 +2879,7 @@ public class GattService extends ProfileService { if (Flags.leScanFixRemoteException()) { handleDeadScanClient(client); } else { - mScannerMap.remove(client.scannerId); + mTransitionalScanHelper.getScannerMap().remove(client.scannerId); mScanManager.stopScan(client.scannerId); } } @@ -2882,7 +2888,8 @@ public class GattService extends ProfileService { // Check and deliver scan results for different scan clients. private void deliverBatchScan(ScanClient client, Set<ScanResult> allResults) throws RemoteException { - ScannerMap.App app = mScannerMap.getById(client.scannerId); + TransitionalScanHelper.ScannerMap.App app = + mTransitionalScanHelper.getScannerMap().getById(client.scannerId); if (app == null) { return; } @@ -3043,7 +3050,8 @@ public class GattService extends ProfileService { + trackingInfo.getAdvState()); } - ScannerMap.App app = mScannerMap.getById(trackingInfo.getClientIf()); + TransitionalScanHelper.ScannerMap.App app = + mTransitionalScanHelper.getScannerMap().getById(trackingInfo.getClientIf()); if (app == null || (app.callback == null && app.info == null)) { Log.e(TAG, "app or callback is null"); return; @@ -3089,7 +3097,8 @@ public class GattService extends ProfileService { } void onScanParamSetupCompleted(int status, int scannerId) throws RemoteException { - ScannerMap.App app = mScannerMap.getById(scannerId); + TransitionalScanHelper.ScannerMap.App app = + mTransitionalScanHelper.getScannerMap().getById(scannerId); if (app == null || app.callback == null) { Log.e(TAG, "Advertise app or callback is null"); return; @@ -3101,7 +3110,8 @@ public class GattService extends ProfileService { // callback from ScanManager for dispatch of errors apps. public void onScanManagerErrorCallback(int scannerId, int errorCode) throws RemoteException { - ScannerMap.App app = mScannerMap.getById(scannerId); + TransitionalScanHelper.ScannerMap.App app = + mTransitionalScanHelper.getScannerMap().getById(scannerId); if (app == null || (app.callback == null && app.info == null)) { Log.e(TAG, "App or callback is null"); return; @@ -3218,7 +3228,8 @@ public class GattService extends ProfileService { enforceImpersonatationPermissionIfNeeded(workSource); - AppScanStats app = mScannerMap.getAppScanStatsByUid(Binder.getCallingUid()); + AppScanStats app = mTransitionalScanHelper.getScannerMap() + .getAppScanStatsByUid(Binder.getCallingUid()); if (app != null && app.isScanningTooFrequently() && !Utils.checkCallerHasPrivilegedPermission(this)) { Log.e(TAG, "App '" + app.appName + "' is scanning too frequently"); @@ -3226,7 +3237,8 @@ public class GattService extends ProfileService { return; } - mScannerMap.add(uuid, workSource, callback, null, this); + mTransitionalScanHelper + .getScannerMap().add(uuid, workSource, callback, null, this); mScanManager.registerScanner(uuid); } @@ -3240,7 +3252,7 @@ public class GattService extends ProfileService { if (DBG) { Log.d(TAG, "unregisterScanner() - scannerId=" + scannerId); } - mScannerMap.remove(scannerId); + mTransitionalScanHelper.getScannerMap().remove(scannerId); mScanManager.unregisterScanner(scannerId); } @@ -3312,8 +3324,9 @@ public class GattService extends ProfileService { Utils.checkCallerHasScanWithoutLocationPermission(this); scanClient.associatedDevices = getAssociatedDevices(callingPackage); - AppScanStats app = mScannerMap.getAppScanStatsById(scannerId); - ScannerMap.App cbApp = mScannerMap.getById(scannerId); + AppScanStats app = mTransitionalScanHelper.getScannerMap().getAppScanStatsById(scannerId); + TransitionalScanHelper.ScannerMap.App cbApp = + mTransitionalScanHelper.getScannerMap().getById(scannerId); if (app != null) { scanClient.stats = app; boolean isFilteredScan = (filters != null) && !filters.isEmpty(); @@ -3360,12 +3373,13 @@ public class GattService extends ProfileService { } // Don't start scan if the Pi scan already in mScannerMap. - if (mScannerMap.getByContextInfo(piInfo) != null) { + if (mTransitionalScanHelper.getScannerMap().getByContextInfo(piInfo) != null) { Log.d(TAG, "Don't startScan(PI) since the same Pi scan already in mScannerMap."); return; } - ScannerMap.App app = mScannerMap.add(uuid, null, null, piInfo, this); + TransitionalScanHelper.ScannerMap.App app = + mTransitionalScanHelper.getScannerMap().add(uuid, null, null, piInfo, this); app.mUserHandle = UserHandle.getUserHandleForUid(Binder.getCallingUid()); mAppOps.checkPackage(Binder.getCallingUid(), callingPackage); @@ -3405,7 +3419,7 @@ public class GattService extends ProfileService { } } - void continuePiStartScan(int scannerId, ScannerMap.App app) { + void continuePiStartScan(int scannerId, TransitionalScanHelper.ScannerMap.App app) { final PendingIntentInfo piInfo = app.info; final ScanClient scanClient = new ScanClient(scannerId, piInfo.settings, piInfo.filters, piInfo.callingUid); @@ -3420,7 +3434,8 @@ public class GattService extends ProfileService { scanClient.associatedDevices = app.mAssociatedDevices; scanClient.hasDisavowedLocation = app.mHasDisavowedLocation; - AppScanStats scanStats = mScannerMap.getAppScanStatsById(scannerId); + AppScanStats scanStats = + mTransitionalScanHelper.getScannerMap().getAppScanStatsById(scannerId); if (scanStats != null) { scanClient.stats = scanStats; boolean isFilteredScan = (piInfo.filters != null) && !piInfo.filters.isEmpty(); @@ -3456,7 +3471,7 @@ public class GattService extends ProfileService { } AppScanStats app = null; - app = mScannerMap.getAppScanStatsById(scannerId); + app = mTransitionalScanHelper.getScannerMap().getAppScanStatsById(scannerId); if (app != null) { app.recordScanStop(scannerId); } @@ -3472,7 +3487,8 @@ public class GattService extends ProfileService { } PendingIntentInfo pii = new PendingIntentInfo(); pii.intent = intent; - ScannerMap.App app = mScannerMap.getByContextInfo(pii); + TransitionalScanHelper.ScannerMap.App app = + mTransitionalScanHelper.getScannerMap().getByContextInfo(pii); if (VDBG) { Log.d(TAG, "stopScan(PendingIntent): app found = " + app); } @@ -5095,8 +5111,9 @@ public class GattService extends ProfileService { void dumpRegisterId(StringBuilder sb) { sb.append(" Scanner:\n"); - for (Integer appId : mScannerMap.getAllAppsIds()) { - println(sb, " app_if: " + appId + ", appName: " + mScannerMap.getById(appId).name); + for (Integer appId : mTransitionalScanHelper.getScannerMap().getAllAppsIds()) { + println(sb, " app_if: " + appId + ", appName: " + + mTransitionalScanHelper.getScannerMap().getById(appId).name); } sb.append(" Client:\n"); for (Integer appId : mClientMap.getAllAppsIds()) { @@ -5123,7 +5140,7 @@ public class GattService extends ProfileService { dumpRegisterId(sb); sb.append("GATT Scanner Map\n"); - mScannerMap.dump(sb); + mTransitionalScanHelper.getScannerMap().dump(sb); sb.append("GATT Advertiser Map\n"); mAdvertiserMap.dumpAdvertiser(sb); diff --git a/android/app/src/com/android/bluetooth/hap/HapClientService.java b/android/app/src/com/android/bluetooth/hap/HapClientService.java index b4fabb8794..5de342cca3 100644 --- a/android/app/src/com/android/bluetooth/hap/HapClientService.java +++ b/android/app/src/com/android/bluetooth/hap/HapClientService.java @@ -133,7 +133,7 @@ public class HapClientService extends ProfileService { } @Override - protected void cleanup() { + public void cleanup() { if (DBG) { Log.d(TAG, "cleanup()"); } @@ -145,7 +145,7 @@ public class HapClientService extends ProfileService { } @Override - protected void start() { + public void start() { if (DBG) { Log.d(TAG, "start()"); } @@ -180,7 +180,7 @@ public class HapClientService extends ProfileService { } @Override - protected void stop() { + public void stop() { if (DBG) { Log.d(TAG, "stop()"); } diff --git a/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java b/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java index 0da9e1986e..1c4185fe6f 100644 --- a/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java +++ b/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java @@ -119,7 +119,7 @@ public class HearingAidService extends ProfileService { } @Override - protected void start() { + public void start() { if (DBG) { Log.d(TAG, "start()"); } @@ -155,7 +155,7 @@ public class HearingAidService extends ProfileService { } @Override - protected void stop() { + public void stop() { if (DBG) { Log.d(TAG, "stop()"); } @@ -209,7 +209,7 @@ public class HearingAidService extends ProfileService { } @Override - protected void cleanup() { + public void cleanup() { if (DBG) { Log.d(TAG, "cleanup()"); } diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetService.java b/android/app/src/com/android/bluetooth/hfp/HeadsetService.java index ef989ead5b..be803e46ad 100644 --- a/android/app/src/com/android/bluetooth/hfp/HeadsetService.java +++ b/android/app/src/com/android/bluetooth/hfp/HeadsetService.java @@ -170,7 +170,7 @@ public class HeadsetService extends ProfileService { } @Override - protected void start() { + public void start() { Log.i(TAG, "start()"); if (mStarted) { throw new IllegalStateException("start() called twice"); @@ -213,7 +213,7 @@ public class HeadsetService extends ProfileService { } @Override - protected void stop() { + public void stop() { Log.i(TAG, "stop()"); if (!mStarted) { Log.w(TAG, "stop() called before start()"); @@ -283,7 +283,7 @@ public class HeadsetService extends ProfileService { } @Override - protected void cleanup() { + public void cleanup() { Log.i(TAG, "cleanup"); } diff --git a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java index cccdbd512d..0de2e0980f 100644 --- a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java +++ b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java @@ -101,7 +101,7 @@ public class HeadsetClientService extends ProfileService { } @Override - protected void start() { + public void start() { synchronized (mStartStopLock) { if (DBG) { Log.d(TAG, "start()"); @@ -155,7 +155,7 @@ public class HeadsetClientService extends ProfileService { } @Override - protected void stop() { + public void stop() { synchronized (mStartStopLock) { synchronized (HeadsetClientService.class) { if (sHeadsetClientService == null) { diff --git a/android/app/src/com/android/bluetooth/hid/HidDeviceService.java b/android/app/src/com/android/bluetooth/hid/HidDeviceService.java index d54f92b46a..99f2beb005 100644 --- a/android/app/src/com/android/bluetooth/hid/HidDeviceService.java +++ b/android/app/src/com/android/bluetooth/hid/HidDeviceService.java @@ -773,7 +773,7 @@ public class HidDeviceService extends ProfileService { } @Override - protected void start() { + public void start() { if (DBG) { Log.d(TAG, "start()"); } @@ -792,7 +792,7 @@ public class HidDeviceService extends ProfileService { } @Override - protected void stop() { + public void stop() { if (DBG) { Log.d(TAG, "stop()"); } diff --git a/android/app/src/com/android/bluetooth/hid/HidHostService.java b/android/app/src/com/android/bluetooth/hid/HidHostService.java index a2f9446873..7da8367b2c 100644 --- a/android/app/src/com/android/bluetooth/hid/HidHostService.java +++ b/android/app/src/com/android/bluetooth/hid/HidHostService.java @@ -103,7 +103,7 @@ public class HidHostService extends ProfileService { } @Override - protected void start() { + public void start() { mDatabaseManager = requireNonNull( AdapterService.getAdapterService().getDatabase(), @@ -120,14 +120,14 @@ public class HidHostService extends ProfileService { } @Override - protected void stop() { + public void stop() { if (DBG) { Log.d(TAG, "Stopping Bluetooth HidHostService"); } } @Override - protected void cleanup() { + public void cleanup() { if (DBG) Log.d(TAG, "Stopping Bluetooth HidHostService"); if (mNativeAvailable) { mNativeInterface.cleanup(); @@ -478,6 +478,43 @@ public class HidHostService extends ProfileService { } } + @Override + public void setPreferredTransport( + BluetoothDevice device, + int transport, + AttributionSource source, + SynchronousResultReceiver receiver) { + try { + HidHostService service = getService(source); + boolean defaultValue = false; + if (service != null) { + enforceBluetoothPrivilegedPermission(service); + defaultValue = service.setPreferredTransport(device, transport); + } + receiver.send(defaultValue); + } catch (RuntimeException e) { + receiver.propagateException(e); + } + } + + @Override + public void getPreferredTransport( + BluetoothDevice device, + AttributionSource source, + SynchronousResultReceiver receiver) { + try { + HidHostService service = getService(source); + int defaultValue = BluetoothDevice.TRANSPORT_AUTO; + if (service != null) { + enforceBluetoothPrivilegedPermission(service); + defaultValue = service.getPreferredTransport(device); + } + receiver.send(defaultValue); + } catch (RuntimeException e) { + receiver.propagateException(e); + } + } + /* The following APIs regarding test app for compliance */ @Override public void getProtocolMode(BluetoothDevice device, AttributionSource source, @@ -708,6 +745,37 @@ public class HidHostService extends ProfileService { } /** + * @see BluetoothHidHost#setPreferredTransport + */ + boolean setPreferredTransport(BluetoothDevice device, int transport) { + if (DBG) { + Log.i(TAG, "setPreferredTransport: " + device + " transport: " + transport); + } + + if (device.getBondState() != BluetoothDevice.BOND_BONDED) { + Log.w(TAG, "Device not bonded" + device); + return false; + } + + boolean hidSupported = Utils.arrayContains(device.getUuids(), BluetoothUuid.HID); + boolean hogpSupported = Utils.arrayContains(device.getUuids(), BluetoothUuid.HOGP); + if (transport == BluetoothDevice.TRANSPORT_BREDR && !hidSupported) { + Log.w(TAG, "HID not supported: " + device); + return false; + } else if (transport == BluetoothDevice.TRANSPORT_LE && !hogpSupported) { + Log.w(TAG, "HOGP not supported: " + device); + return false; + } + + /* TODO: b/324094542 - Implement setPreferredTransport API + * Save transport preference in the persistent storage + * If connection policy allows connection, ensure that the preferred transport is + * connected and not the other one. + */ + return false; + } + + /** * Get the connection policy of the profile. * * <p> The connection policy can be any of: @@ -727,6 +795,18 @@ public class HidHostService extends ProfileService { .getProfileConnectionPolicy(device, BluetoothProfile.HID_HOST); } + /** + * @see BluetoothHidHost#getPreferredTransport + */ + int getPreferredTransport(BluetoothDevice device) { + if (DBG) { + Log.d(TAG, "getPreferredTransport: " + device); + } + + // TODO: b/324094542 - Implement getPreferredTransport API + return BluetoothDevice.TRANSPORT_AUTO; + } + /* The following APIs regarding test app for compliance */ boolean getProtocolMode(BluetoothDevice device) { if (DBG) { @@ -924,6 +1004,9 @@ public class HidHostService extends ProfileService { intent.putExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, prevState); intent.putExtra(BluetoothProfile.EXTRA_STATE, newState); intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device); + /* TODO: b/324094542 - Set correct transport as EXTRA_TRANSPORT + * intent.putExtra(BluetoothDevice.EXTRA_TRANSPORT, BluetoothDevice.TRANSPORT_AUTO); + */ intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_CONNECT, Utils.getTempAllowlistBroadcastOptions()); 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 805d4e9023..5b8fb2dd03 100644 --- a/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java +++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java @@ -313,7 +313,7 @@ public class LeAudioService extends ProfileService { } @Override - protected void start() { + public void start() { Log.i(TAG, "start()"); if (sLeAudioService != null) { throw new IllegalStateException("start() called twice"); @@ -372,8 +372,7 @@ public class LeAudioService extends ProfileService { mAudioManager.registerAudioDeviceCallback(mAudioManagerAudioDeviceCallback, mHandler); - // clear mUnicastGroupIdDeactivatedForBroadcastTransition to default - updateFallbackUnicastGroupIdForBroadcast(LE_AUDIO_GROUP_ID_INVALID); + // Mark service as started setLeAudioService(this); @@ -404,7 +403,7 @@ public class LeAudioService extends ProfileService { } @Override - protected void stop() { + public void stop() { Log.i(TAG, "stop()"); if (sLeAudioService == null) { Log.w(TAG, "stop() called before start()"); @@ -500,8 +499,7 @@ public class LeAudioService extends ProfileService { } mAudioManager.unregisterAudioDeviceCallback(mAudioManagerAudioDeviceCallback); - // clear mUnicastGroupIdDeactivatedForBroadcastTransition to default - updateFallbackUnicastGroupIdForBroadcast(LE_AUDIO_GROUP_ID_INVALID); + mAdapterService = null; mAudioManager = null; mMcpService = null; @@ -512,7 +510,7 @@ public class LeAudioService extends ProfileService { } @Override - protected void cleanup() { + public void cleanup() { Log.i(TAG, "cleanup()"); } @@ -2875,6 +2873,7 @@ public class LeAudioService extends ProfileService { return; } removeStateMachine(device); + removeAuthorizationInfoForRelatedProfiles(device); } } @@ -2950,25 +2949,26 @@ public class LeAudioService extends ProfileService { * Process a change for disconnection of a device. */ public synchronized void deviceDisconnected(BluetoothDevice device, boolean hasFallbackDevice) { - LeAudioDeviceDescriptor deviceDescriptor = getDeviceDescriptor(device); - if (deviceDescriptor == null) { - Log.e(TAG, "deviceDisconnected: No valid descriptor for device: " + device); - return; - } + synchronized (mGroupLock) { + LeAudioDeviceDescriptor deviceDescriptor = getDeviceDescriptor(device); + if (deviceDescriptor == null) { + Log.e(TAG, "deviceDisconnected: No valid descriptor for device: " + device); + return; + } - int bondState = mAdapterService.getBondState(device); - if (bondState == BluetoothDevice.BOND_NONE) { - if (DBG) { - Log.d(TAG, device + " is unbond. Remove state machine"); + int bondState = mAdapterService.getBondState(device); + if (bondState == BluetoothDevice.BOND_NONE) { + if (DBG) { + Log.d(TAG, device + " is unbond. Remove state machine"); + } + removeStateMachine(device); + removeAuthorizationInfoForRelatedProfiles(device); } - removeStateMachine(device); - } - if (!isScannerNeeded()) { - stopAudioServersBackgroundScan(); - } + if (!isScannerNeeded()) { + stopAudioServersBackgroundScan(); + } - synchronized (mGroupLock) { LeAudioGroupDescriptor descriptor = getGroupDescriptor(deviceDescriptor.mGroupId); if (descriptor == null) { Log.e(TAG, "deviceDisconnected: no descriptors for group: " @@ -3341,6 +3341,23 @@ public class LeAudioService extends ProfileService { } } + void removeAuthorizationInfoForRelatedProfiles(BluetoothDevice device) { + if (!mFeatureFlags.leaudioMcsTbsAuthorizationRebondFix()) { + Log.i(TAG, "leaudio_mcs_tbs_authorization_rebond_fix is disabled"); + return; + } + + McpService mcpService = getMcpService(); + if (mcpService != null) { + mcpService.removeDeviceAuthorizationInfo(device); + } + + TbsService tbsService = getTbsService(); + if (tbsService != null) { + tbsService.removeDeviceAuthorizationInfo(device); + } + } + /** * This function is called when the framework registers a callback with the service for this * first time. This is used as an indication that Bluetooth has been enabled. @@ -3499,6 +3516,7 @@ public class LeAudioService extends ProfileService { } setAuthorizationForRelatedProfiles(device, false); + removeAuthorizationInfoForRelatedProfiles(device); } private void notifyGroupNodeRemoved(BluetoothDevice device, int groupId) { 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 662e0fa3bc..c50f484228 100644 --- a/android/app/src/com/android/bluetooth/le_scan/ScanManager.java +++ b/android/app/src/com/android/bluetooth/le_scan/ScanManager.java @@ -1922,7 +1922,8 @@ public class ScanManager { new ActivityManager.OnUidImportanceListener() { @Override public void onUidImportance(final int uid, final int importance) { - if (mService.mScannerMap.getAppScanStatsByUid(uid) != null) { + if (mService.mTransitionalScanHelper.getScannerMap().getAppScanStatsByUid(uid) + != null) { Message message = new Message(); message.what = MSG_IMPORTANCE_CHANGE; message.obj = new UidImportance(uid, importance); diff --git a/android/app/src/com/android/bluetooth/le_scan/TransitionalScanHelper.java b/android/app/src/com/android/bluetooth/le_scan/TransitionalScanHelper.java new file mode 100644 index 0000000000..913cc40478 --- /dev/null +++ b/android/app/src/com/android/bluetooth/le_scan/TransitionalScanHelper.java @@ -0,0 +1,49 @@ +/* + * Copyright (C) 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. + */ + +package com.android.bluetooth.le_scan; + +import android.bluetooth.le.IScannerCallback; + +import com.android.bluetooth.gatt.ContextMap; +import com.android.bluetooth.gatt.GattService; +import com.android.internal.annotations.VisibleForTesting; + +/** + * A helper class which contains all scan related functions extracted from {@link + * com.android.bluetooth.gatt.GattService}. The purpose of this class is to preserve scan + * functionality within GattService and provide the same functionality in a new scan dedicated + * {@link com.android.bluetooth.btservice.ProfileService} when introduced. + * + * @hide + */ +public class TransitionalScanHelper { + + /** List of our registered scanners. */ + public static class ScannerMap + extends ContextMap<IScannerCallback, GattService.PendingIntentInfo> {} + + private ScannerMap mScannerMap = new ScannerMap(); + + public ScannerMap getScannerMap() { + return mScannerMap; + } + + @VisibleForTesting + public void setScannerMap(ScannerMap scannerMap) { + mScannerMap = scannerMap; + } +} diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapService.java b/android/app/src/com/android/bluetooth/map/BluetoothMapService.java index 2e0ebf39d1..f1499c61c8 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapService.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapService.java @@ -717,7 +717,7 @@ public class BluetoothMapService extends ProfileService { } @Override - protected void start() { + public void start() { if (DEBUG) { Log.d(TAG, "start()"); } @@ -945,7 +945,7 @@ public class BluetoothMapService extends ProfileService { } @Override - protected void stop() { + public void stop() { if (DEBUG) { Log.d(TAG, "stop()"); } diff --git a/android/app/src/com/android/bluetooth/mapclient/MapClientContent.java b/android/app/src/com/android/bluetooth/mapclient/MapClientContent.java index c552a1e0c6..4034afd060 100644 --- a/android/app/src/com/android/bluetooth/mapclient/MapClientContent.java +++ b/android/app/src/com/android/bluetooth/mapclient/MapClientContent.java @@ -24,6 +24,7 @@ import android.content.Context; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; +import android.provider.BaseColumns; import android.provider.Telephony; import android.provider.Telephony.Mms; import android.provider.Telephony.MmsSms; @@ -45,7 +46,12 @@ import com.android.vcard.VCardProperty; import com.google.android.mms.pdu.PduHeaders; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Set; @@ -58,6 +64,20 @@ class MapClientContent { private static final int ORIGINATOR_ADDRESS_TYPE = 137; private static final int RECIPIENT_ADDRESS_TYPE = 151; + private static final int NUM_RECENT_MSGS_TO_DUMP = 5; + + private enum Type { + UNKNOWN, + SMS, + MMS + } + + private enum Folder { + UNKNOWN, + INBOX, + SENT + } + final BluetoothDevice mDevice; private final Context mContext; private final Callbacks mCallbacks; @@ -81,18 +101,16 @@ class MapClientContent { /** * MapClientContent manages all interactions between Bluetooth and the messaging provider. * - * Changes to the database are mirrored between the remote and local providers, specifically new - * messages, changes to read status, and removal of messages. + * <p>Changes to the database are mirrored between the remote and local providers, specifically + * new messages, changes to read status, and removal of messages. * - * Object is invalid after cleanUp() is called. + * <p>Object is invalid after cleanUp() is called. * - * context: the context that all content provider interactions are conducted - * MceStateMachine: the interface to send outbound updates such as when a message is read - * locally - * device: the associated Bluetooth device used for associating messages with a subscription + * <p>context: the context that all content provider interactions are conducted MceStateMachine: + * the interface to send outbound updates such as when a message is read locally device: the + * associated Bluetooth device used for associating messages with a subscription */ - MapClientContent(Context context, Callbacks callbacks, - BluetoothDevice device) { + MapClientContent(Context context, Callbacks callbacks, BluetoothDevice device) { mContext = context; mDevice = device; mCallbacks = callbacks; @@ -187,9 +205,20 @@ class MapClientContent { * The handle is used to associate the local message with the remote message. */ void storeMessage(Bmessage message, String handle, Long timestamp, boolean seen) { - logI("storeMessage(device=" + Utils.getLoggableAddress(mDevice) + ", time=" + timestamp - + ", handle=" + handle + ", type=" + message.getType() - + ", folder=" + message.getFolder()); + logI( + "storeMessage(device=" + + Utils.getLoggableAddress(mDevice) + + ", time=" + + timestamp + + "[" + + toDatetimeString(timestamp) + + "]" + + ", handle=" + + handle + + ", type=" + + message.getType() + + ", folder=" + + message.getFolder()); switch (message.getType()) { case MMS: @@ -609,6 +638,146 @@ class MapClientContent { return count; } + private List<MessageDumpElement> getRecentMessagesFromFolder(Folder folder) { + Uri smsUri = null; + Uri mmsUri = null; + if (folder == Folder.INBOX) { + smsUri = Sms.Inbox.CONTENT_URI; + mmsUri = Mms.Inbox.CONTENT_URI; + } else if (folder == Folder.SENT) { + smsUri = Sms.Sent.CONTENT_URI; + mmsUri = Mms.Sent.CONTENT_URI; + } else { + Log.w(TAG, "getRecentMessagesFromFolder: Failed, unsupported folder=" + folder); + return null; + } + + ArrayList<MessageDumpElement> messages = new ArrayList<MessageDumpElement>(); + for (Uri uri : new Uri[] {smsUri, mmsUri}) { + messages.addAll(getMessagesFromUri(uri)); + } + logV( + "getRecentMessagesFromFolder: " + + folder + + ", " + + messages.size() + + " messages found."); + + Collections.sort(messages); + if (messages.size() > NUM_RECENT_MSGS_TO_DUMP) { + return messages.subList(0, NUM_RECENT_MSGS_TO_DUMP); + } + return messages; + } + + private List<MessageDumpElement> getMessagesFromUri(Uri uri) { + logD("getMessagesFromUri: uri=" + uri); + ArrayList<MessageDumpElement> messages = new ArrayList<MessageDumpElement>(); + + if (mSubscriptionId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) { + Log.w(TAG, "getMessagesFromUri: Failed, no subscription ID"); + return messages; + } + + Type type = getMessageTypeFromUri(uri); + if (type == Type.UNKNOWN) { + Log.w(TAG, "getMessagesFromUri: unknown message type"); + return messages; + } + + String[] selectionArgs = new String[] {Integer.toString(mSubscriptionId)}; + String limit = " LIMIT " + NUM_RECENT_MSGS_TO_DUMP; + String[] projection = null; + String selectionClause = null; + String threadIdColumnName = null; + String timestampColumnName = null; + + if (type == Type.SMS) { + projection = new String[] {BaseColumns._ID, Sms.THREAD_ID, Sms.DATE}; + selectionClause = Sms.SUBSCRIPTION_ID + " =? "; + threadIdColumnName = Sms.THREAD_ID; + timestampColumnName = Sms.DATE; + } else if (type == Type.MMS) { + projection = new String[] {BaseColumns._ID, Mms.THREAD_ID, Mms.DATE}; + selectionClause = Mms.SUBSCRIPTION_ID + " =? "; + threadIdColumnName = Mms.THREAD_ID; + timestampColumnName = Mms.DATE; + } + + Cursor cursor = + mResolver.query( + uri, + projection, + selectionClause, + selectionArgs, + timestampColumnName + " DESC" + limit); + + try { + if (cursor == null) { + Log.w(TAG, "getMessagesFromUri: null cursor for uri=" + uri); + return messages; + } + logV("Number of rows in cursor = " + cursor.getCount() + ", for uri=" + uri); + + cursor.moveToPosition(-1); + while (cursor.moveToNext()) { + // Even though {@link storeSms} and {@link storeMms} use Uris that contain the + // folder name (e.g., {@code Sms.Inbox.CONTENT_URI}), the Uri returned by + // {@link ContentResolver#insert} does not (e.g., {@code Sms.CONTENT_URI}). + // Therefore, the Uris in the keyset of {@code mUriToHandleMap} do not contain + // the folder name, but unfortunately, the Uri passed in to query the database + // does contains the folder name, so we can't simply append messageId to the + // passed-in Uri. + String messageId = cursor.getString(cursor.getColumnIndex(BaseColumns._ID)); + Uri messageUri = + Uri.withAppendedPath( + type == Type.SMS ? Sms.CONTENT_URI : Mms.CONTENT_URI, messageId); + + MessageStatus handleAndStatus = mUriToHandleMap.get(messageUri); + String messageHandle = "<unknown>"; + if (handleAndStatus == null) { + Log.w(TAG, "getMessagesFromUri: no entry for message uri=" + messageUri); + } else { + messageHandle = handleAndStatus.mHandle; + } + + long timestamp = cursor.getLong(cursor.getColumnIndex(timestampColumnName)); + // TODO: why does `storeMms` truncate down to the seconds instead of keeping it + // millisec, like `storeSms`? + if (type == Type.MMS) { + timestamp *= 1000L; + } + + messages.add( + new MessageDumpElement( + messageHandle, + messageUri, + timestamp, + cursor.getLong(cursor.getColumnIndex(threadIdColumnName)), + type)); + } + } catch (Exception e) { + Log.w(TAG, "Exception when querying db for dumpsys", e); + } finally { + cursor.close(); + } + return messages; + } + + private Type getMessageTypeFromUri(Uri uri) { + if (Sms.CONTENT_URI.equals(uri) + || Sms.Inbox.CONTENT_URI.equals(uri) + || Sms.Sent.CONTENT_URI.equals(uri)) { + return Type.SMS; + } else if (Mms.CONTENT_URI.equals(uri) + || Mms.Inbox.CONTENT_URI.equals(uri) + || Mms.Sent.CONTENT_URI.equals(uri)) { + return Type.MMS; + } else { + return Type.UNKNOWN; + } + } + public void dump(StringBuilder sb) { sb.append(" Device Message DB:"); sb.append("\n Subscription ID: " + mSubscriptionId); @@ -624,6 +793,17 @@ class MapClientContent { + " / " + getStoredMessagesCount(Mms.CONTENT_URI)); sb.append("\n Threads: " + getStoredMessagesCount(Threads.CONTENT_URI)); + + sb.append("\n Most recent 'Sent' messages:"); + sb.append("\n " + MessageDumpElement.getFormattedColumnNames()); + for (MessageDumpElement e : getRecentMessagesFromFolder(Folder.SENT)) { + sb.append("\n " + e); + } + sb.append("\n Most recent 'Inbox' messages:"); + sb.append("\n " + MessageDumpElement.getFormattedColumnNames()); + for (MessageDumpElement e : getRecentMessagesFromFolder(Folder.INBOX)) { + sb.append("\n " + e); + } } sb.append("\n"); } @@ -650,4 +830,53 @@ class MapClientContent { .equals(mHandle)); } } + + @SuppressWarnings("GoodTime") // Use system time zone to render times for logging + private static String toDatetimeString(long epochMillis) { + return DateTimeFormatter.ofPattern("MM-dd HH:mm:ss.SSS") + .format( + Instant.ofEpochMilli(epochMillis) + .atZone(ZoneId.systemDefault()) + .toLocalDateTime()); + } + + private static class MessageDumpElement implements Comparable<MessageDumpElement> { + private String mMessageHandle; + private long mTimestamp; + private Type mType; + private long mThreadId; + private Uri mUri; + + MessageDumpElement(String handle, Uri uri, long timestamp, long threadId, Type type) { + mMessageHandle = handle; + mTimestamp = timestamp; + mUri = uri; + mThreadId = threadId; + mType = type; + } + + public static String getFormattedColumnNames() { + return String.format( + "%-19s %s %-16s %s %s", "Timestamp", "ThreadId", "Handle", "Type", "Uri"); + } + + @Override + public String toString() { + return String.format( + "%-19s %8d %-16s %-4s %s", + toDatetimeString(mTimestamp), mThreadId, mMessageHandle, mType, mUri); + } + + @Override + public int compareTo(MessageDumpElement e) { + // we want reverse chronological. + if (this.mTimestamp < e.mTimestamp) { + return 1; + } else if (this.mTimestamp > e.mTimestamp) { + return -1; + } else { + return 0; + } + } + } } diff --git a/android/app/src/com/android/bluetooth/mapclient/MapClientService.java b/android/app/src/com/android/bluetooth/mapclient/MapClientService.java index 2a31ea4777..cc259099f4 100644 --- a/android/app/src/com/android/bluetooth/mapclient/MapClientService.java +++ b/android/app/src/com/android/bluetooth/mapclient/MapClientService.java @@ -310,7 +310,7 @@ public class MapClientService extends ProfileService { } @Override - protected synchronized void start() { + public synchronized void start() { Log.e(TAG, "start()"); mAdapterService = AdapterService.getAdapterService(); @@ -329,7 +329,7 @@ public class MapClientService extends ProfileService { } @Override - protected synchronized void stop() { + public synchronized void stop() { if (DBG) { Log.d(TAG, "stop()"); } @@ -353,7 +353,7 @@ public class MapClientService extends ProfileService { } @Override - protected void cleanup() { + public void cleanup() { if (DBG) { Log.d(TAG, "in Cleanup"); } diff --git a/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java b/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java index aa605a6059..444eb63a4c 100644 --- a/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java +++ b/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java @@ -725,21 +725,30 @@ class MceStateMachine extends StateMachine { case MSG_GET_MESSAGE_LISTING: // Get latest 50 Unread messages in the last week - MessagesFilter filter = new MessagesFilter(); + Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.DATE, -7); + byte messageType; if (Utils.isPtsTestMode()) { - filter.setMessageType( + messageType = (byte) SystemProperties.getInt( FETCH_MESSAGE_TYPE, - MessagesFilter.MESSAGE_TYPE_ALL)); + MessagesFilter.MESSAGE_TYPE_ALL); } else { - filter.setMessageType(MessagesFilter.MESSAGE_TYPE_ALL); + messageType = MessagesFilter.MESSAGE_TYPE_ALL; } - Calendar calendar = Calendar.getInstance(); - calendar.add(Calendar.DATE, -7); - filter.setPeriod(calendar.getTime(), null); - mMasClient.makeRequest(new RequestGetMessagesListing( - (String) message.obj, 0, filter, 0, 50, 0)); + + mMasClient.makeRequest( + new RequestGetMessagesListing( + (String) message.obj, + 0, + new MessagesFilter.Builder() + .setPeriod(calendar.getTime(), null) + .setMessageType(messageType) + .build(), + 0, + 50, + 0)); break; case MSG_SET_MESSAGE_STATUS: diff --git a/android/app/src/com/android/bluetooth/mapclient/obex/MessagesFilter.java b/android/app/src/com/android/bluetooth/mapclient/obex/MessagesFilter.java index c2a7f78b2b..918b0a98fe 100644 --- a/android/app/src/com/android/bluetooth/mapclient/obex/MessagesFilter.java +++ b/android/app/src/com/android/bluetooth/mapclient/obex/MessagesFilter.java @@ -41,6 +41,16 @@ public final class MessagesFilter { public MessagesFilter() { } + public MessagesFilter(MessagesFilter filter) { + this.messageType = filter.messageType; + this.periodBegin = filter.periodBegin; + this.periodEnd = filter.periodEnd; + this.readStatus = filter.readStatus; + this.recipient = filter.recipient; + this.originator = filter.originator; + this.priority = filter.priority; + } + public void setMessageType(byte filter) { messageType = filter; } @@ -78,4 +88,87 @@ public final class MessagesFilter { public void setPriority(byte filter) { priority = filter; } + + /** Builder for a {@link MessagesFilter}. */ + public static class Builder { + private MessagesFilter mMessagesFilter = new MessagesFilter(); + + /** + * Sets the `Message Type` field of the filter. + * + * @param messageType to filter on. + * @return This {@link Builder} object. + */ + public Builder setMessageType(byte messageType) { + mMessagesFilter.setMessageType(messageType); + return this; + } + + /** + * Sets the `Originator` field of the filter. + * + * @param originator to filter on. + * @return This {@link Builder} object. + */ + public Builder setOriginator(String originator) { + mMessagesFilter.setOriginator(originator); + return this; + } + + /** + * Sets the `Period` field of the filter. + * + * @param filterBegin filter out messages that arrive before this time instance. Can be + * {@code null}, in which case no limit on how old a message can be. + * @param filterEnd filter out messages that arrive after this time instance. Can be {@code + * null}, in which case no limit on how new a message can be. + * @return This {@link Builder} object. + */ + public Builder setPeriod(Date filterBegin, Date filterEnd) { + mMessagesFilter.setPeriod(filterBegin, filterEnd); + return this; + } + + /** + * Sets the `Priority` field of the filter. + * + * @param priority to filter on. + * @return This {@link Builder} object. + */ + public Builder setPriority(byte priority) { + mMessagesFilter.setPriority(priority); + return this; + } + + /** + * Sets the `Read Status` field of the filter. + * + * @param status to filter on. + * @return This {@link Builder} object. + */ + public Builder setReadStatus(byte status) { + mMessagesFilter.setReadStatus(status); + return this; + } + + /** + * Sets the `Recipient` field of the filter. + * + * @param recipient to filter on. + * @return This {@link Builder} object. + */ + public Builder setRecipient(String recipient) { + mMessagesFilter.setRecipient(recipient); + return this; + } + + /** + * Build the {@link MessagesFilter}. + * + * @return A {@link MessagesFilter} object. + */ + public MessagesFilter build() { + return new MessagesFilter(mMessagesFilter); + } + } } diff --git a/android/app/src/com/android/bluetooth/mcp/McpService.java b/android/app/src/com/android/bluetooth/mcp/McpService.java index acdae147c3..dd56a34121 100644 --- a/android/app/src/com/android/bluetooth/mcp/McpService.java +++ b/android/app/src/com/android/bluetooth/mcp/McpService.java @@ -101,7 +101,7 @@ public class McpService extends ProfileService { } @Override - protected void start() { + public void start() { if (DBG) { Log.d(TAG, "start()"); } @@ -133,7 +133,7 @@ public class McpService extends ProfileService { } @Override - protected void stop() { + public void stop() { if (DBG) { Log.d(TAG, "stop()"); } @@ -161,7 +161,7 @@ public class McpService extends ProfileService { } @Override - protected void cleanup() { + public void cleanup() { if (DBG) { Log.d(TAG, "cleanup()"); } @@ -200,6 +200,17 @@ public class McpService extends ProfileService { setDeviceAuthorized(device, false); } + /** + * Remove authorization information for the device. + * + * @param device device to remove from the service information + * @hide + */ + public void removeDeviceAuthorizationInfo(BluetoothDevice device) { + Log.i(TAG, "removeDeviceAuthorizationInfo(): device: " + device); + mDeviceAuthorizations.remove(device); + } + public void setDeviceAuthorized(BluetoothDevice device, boolean isAuthorized) { Log.i(TAG, "\tsetDeviceAuthorized(): device: " + device + ", isAuthorized: " + isAuthorized); diff --git a/android/app/src/com/android/bluetooth/airplane/NotificationHelperService.java b/android/app/src/com/android/bluetooth/notification/NotificationHelperService.java index b8c2d07a45..b411565d84 100644 --- a/android/app/src/com/android/bluetooth/airplane/NotificationHelperService.java +++ b/android/app/src/com/android/bluetooth/notification/NotificationHelperService.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.bluetooth.airplane; +package com.android.bluetooth.notification; import static java.util.Objects.requireNonNull; @@ -47,8 +47,8 @@ public class NotificationHelperService extends Service { private static final String APM_BT_ENABLED_NOTIFICATION = "apm_bt_enabled_notification"; private static final String NOTIFICATION_TAG = "com.android.bluetooth"; - private static final String APM_NOTIFICATION_CHANNEL = "apm_notification_channel"; - private static final String APM_NOTIFICATION_GROUP = "apm_notification_group"; + private static final String NOTIFICATION_CHANNEL = "notification_toggle_channel"; + private static final String NOTIFICATION_GROUP = "notification_toggle_group"; private static final Map<String, Pair<Integer /* titleId */, Integer /* messageId */>> NOTIFICATION_MAP = @@ -73,24 +73,24 @@ public class NotificationHelperService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { - sendAirplaneModeNotification( - intent.getStringExtra("android.bluetooth.airplane.extra.NOTIFICATION_STATE")); + sendToggleNotification( + intent.getStringExtra("android.bluetooth.notification.extra.NOTIFICATION_REASON")); return Service.START_NOT_STICKY; } - private void sendAirplaneModeNotification(String notificationState) { - String logHeader = "sendAirplaneModeNotification(" + notificationState + "): "; - Pair<Integer, Integer> notificationContent = NOTIFICATION_MAP.get(notificationState); + private void sendToggleNotification(String notificationReason) { + String logHeader = "sendToggleNotification(" + notificationReason + "): "; + Pair<Integer, Integer> notificationContent = NOTIFICATION_MAP.get(notificationReason); if (notificationContent == null) { Log.e(TAG, logHeader + "unknown action"); return; } - if (!isFirstTimeNotification(notificationState)) { + if (!isFirstTimeNotification(notificationReason)) { Log.d(TAG, logHeader + "already displayed"); return; } - Settings.Secure.putInt(getContentResolver(), notificationState, 1); + Settings.Secure.putInt(getContentResolver(), notificationReason, 1); Log.d(TAG, logHeader + "sending"); @@ -104,8 +104,8 @@ public class NotificationHelperService extends Service { notificationManager.createNotificationChannel( new NotificationChannel( - APM_NOTIFICATION_CHANNEL, - APM_NOTIFICATION_GROUP, + NOTIFICATION_CHANNEL, + NOTIFICATION_GROUP, NotificationManager.IMPORTANCE_HIGH)); String title = getString(notificationContent.first); @@ -115,7 +115,7 @@ public class NotificationHelperService extends Service { notificationManager.notify( NOTIFICATION_TAG, SystemMessage.ID.NOTE_BT_APM_NOTIFICATION_VALUE, - new Notification.Builder(this, APM_NOTIFICATION_CHANNEL) + new Notification.Builder(this, NOTIFICATION_CHANNEL) .setAutoCancel(true) .setLocalOnly(true) .setContentTitle(title) diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java index 4ffe010d60..eaaa2583d6 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java @@ -72,13 +72,23 @@ class BluetoothOppNotification { BluetoothShare.STATUS + " >= '200' AND " + VISIBLE + " AND " + NOT_THROUGH_HANDOVER; // Don't show handover-initiated transfers - private static final String WHERE_COMPLETED_OUTBOUND = - WHERE_COMPLETED + " AND " + "(" + BluetoothShare.DIRECTION + " == " - + BluetoothShare.DIRECTION_OUTBOUND + ")"; - - private static final String WHERE_COMPLETED_INBOUND = - WHERE_COMPLETED + " AND " + "(" + BluetoothShare.DIRECTION + " == " - + BluetoothShare.DIRECTION_INBOUND + ")"; + static final String WHERE_COMPLETED_OUTBOUND = + WHERE_COMPLETED + + " AND " + + "(" + + BluetoothShare.DIRECTION + + " == " + + BluetoothShare.DIRECTION_OUTBOUND + + ")"; + + static final String WHERE_COMPLETED_INBOUND = + WHERE_COMPLETED + + " AND " + + "(" + + BluetoothShare.DIRECTION + + " == " + + BluetoothShare.DIRECTION_INBOUND + + ")"; private static final String WHERE_CONFIRM_PENDING = BluetoothShare.USER_CONFIRMATION + " == '" + BluetoothShare.USER_CONFIRMATION_PENDING @@ -105,6 +115,8 @@ class BluetoothOppNotification { @VisibleForTesting static final int NOTIFICATION_ID_INBOUND_COMPLETE = -1000006; + static final int NOTIFICATION_ID_COMPLETE_SUMMARY = -1000007; + private static final String NOTIFICATION_GROUP_KEY_PROGRESS = "PROGRESS"; private static final String NOTIFICATION_GROUP_KEY_TRANSFER_COMPLETE = "TRANSFER_COMPLETE"; @@ -454,8 +466,13 @@ class BluetoothOppNotification { pi = PendingIntent.getBroadcast(mContext, 0, in, PendingIntent.FLAG_IMMUTABLE); } - Intent deleteIntent = new Intent(Constants.ACTION_COMPLETE_HIDE).setClassName( - mContext, BluetoothOppReceiver.class.getName()); + Intent deleteIntent = new Intent(mContext, BluetoothOppReceiver.class); + if (Flags.oppFixMultipleNotificationsIssues()) { + deleteIntent.setAction(Constants.ACTION_HIDE_COMPLETED_OUTBOUND_TRANSFER); + } else { + deleteIntent.setAction(Constants.ACTION_COMPLETE_HIDE); + } + Notification.Builder b = new Notification.Builder(mContext, OPP_NOTIFICATION_CHANNEL).setOnlyAlertOnce( true) @@ -531,8 +548,13 @@ class BluetoothOppNotification { pi = PendingIntent.getBroadcast(mContext, 0, in, PendingIntent.FLAG_IMMUTABLE); } - Intent deleteIntent = new Intent(Constants.ACTION_COMPLETE_HIDE).setClassName( - mContext, BluetoothOppReceiver.class.getName()); + Intent deleteIntent = new Intent(mContext, BluetoothOppReceiver.class); + if (Flags.oppFixMultipleNotificationsIssues()) { + deleteIntent.setAction(Constants.ACTION_HIDE_COMPLETED_INBOUND_TRANSFER); + } else { + deleteIntent.setAction(Constants.ACTION_COMPLETE_HIDE); + } + Notification.Builder b = new Notification.Builder(mContext, OPP_NOTIFICATION_CHANNEL).setOnlyAlertOnce( true) @@ -563,6 +585,24 @@ class BluetoothOppNotification { } } } + + if (Flags.oppFixMultipleNotificationsIssues() && inboundNum > 0 && outboundNum > 0) { + Notification.Builder b = + new Notification.Builder(mContext, OPP_NOTIFICATION_CHANNEL) + .setGroup(NOTIFICATION_GROUP_KEY_TRANSFER_COMPLETE) + .setGroupSummary(true) + .setGroupAlertBehavior(Notification.GROUP_ALERT_CHILDREN) + .setSmallIcon(R.drawable.ic_bluetooth_file_transfer_notification) + .setColor( + mContext.getResources() + .getColor( + android.R.color + .system_notification_accent_color, + mContext.getTheme())) + .setLocalOnly(true); + + mNotificationMgr.notify(NOTIFICATION_ID_COMPLETE_SUMMARY, b.build()); + } } @VisibleForTesting @@ -636,7 +676,7 @@ class BluetoothOppNotification { R.string.incoming_file_confirm_Notification_content, info.mDeviceName, fileNameSafe))) .setSubText(Formatter.formatFileSize(mContext, info.mTotalBytes)) - .setSmallIcon(R.drawable.bt_incomming_file_notification) + .setSmallIcon(R.drawable.ic_bluetooth_file_transfer_notification) .setLocalOnly(true); if (Flags.oppFixMultipleNotificationsIssues()) { publicNotificationBuilder.setGroup(NOTIFICATION_GROUP_KEY_INCOMING_FILE_CONFIRM); @@ -663,7 +703,7 @@ class BluetoothOppNotification { R.string.incoming_file_confirm_Notification_content, info.mDeviceName, fileNameSafe))) .setSubText(Formatter.formatFileSize(mContext, info.mTotalBytes)) - .setSmallIcon(R.drawable.bt_incomming_file_notification) + .setSmallIcon(R.drawable.ic_bluetooth_file_transfer_notification) .setLocalOnly(true) .setVisibility(Notification.VISIBILITY_PRIVATE) .addAction(actionDecline) diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiver.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiver.java index e6d438f425..6db2dad207 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiver.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiver.java @@ -199,7 +199,8 @@ public class BluetoothOppReceiver extends BroadcastReceiver { } cursor.close(); } - } else if (action.equals(Constants.ACTION_COMPLETE_HIDE)) { + } else if (action.equals(Constants.ACTION_COMPLETE_HIDE) + && !Flags.oppFixMultipleNotificationsIssues()) { if (V) { Log.v(TAG, "Receiver ACTION_COMPLETE_HIDE"); } @@ -208,6 +209,34 @@ public class BluetoothOppReceiver extends BroadcastReceiver { BluetoothMethodProxy.getInstance().contentResolverUpdate( context.getContentResolver(), BluetoothShare.CONTENT_URI, updateValues, BluetoothOppNotification.WHERE_COMPLETED, null); + } else if (action.equals(Constants.ACTION_HIDE_COMPLETED_INBOUND_TRANSFER) + && Flags.oppFixMultipleNotificationsIssues()) { + if (V) { + Log.v(TAG, "Received ACTION_HIDE_COMPLETED_INBOUND_TRANSFER"); + } + ContentValues updateValues = new ContentValues(); + updateValues.put(BluetoothShare.VISIBILITY, BluetoothShare.VISIBILITY_HIDDEN); + BluetoothMethodProxy.getInstance() + .contentResolverUpdate( + context.getContentResolver(), + BluetoothShare.CONTENT_URI, + updateValues, + BluetoothOppNotification.WHERE_COMPLETED_INBOUND, + null); + } else if (action.equals(Constants.ACTION_HIDE_COMPLETED_OUTBOUND_TRANSFER) + && Flags.oppFixMultipleNotificationsIssues()) { + if (V) { + Log.v(TAG, "Received ACTION_HIDE_COMPLETED_OUTBOUND_TRANSFER"); + } + ContentValues updateValues = new ContentValues(); + updateValues.put(BluetoothShare.VISIBILITY, BluetoothShare.VISIBILITY_HIDDEN); + BluetoothMethodProxy.getInstance() + .contentResolverUpdate( + context.getContentResolver(), + BluetoothShare.CONTENT_URI, + updateValues, + BluetoothOppNotification.WHERE_COMPLETED_OUTBOUND, + null); } else if (action.equals(BluetoothShare.TRANSFER_COMPLETED_ACTION)) { if (V) { Log.v(TAG, "Receiver Transfer Complete Intent for " + intent.getData()); diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppService.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppService.java index 3b35ac7a03..268fb8d86b 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppService.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppService.java @@ -601,7 +601,7 @@ public class BluetoothOppService extends ProfileService implements IObexConnecti } @Override - protected void cleanup() { + public void cleanup() { if (V) { Log.v(TAG, "onDestroy"); } diff --git a/android/app/src/com/android/bluetooth/opp/Constants.java b/android/app/src/com/android/bluetooth/opp/Constants.java index 51c8808f41..b214655b07 100644 --- a/android/app/src/com/android/bluetooth/opp/Constants.java +++ b/android/app/src/com/android/bluetooth/opp/Constants.java @@ -142,11 +142,21 @@ public class Constants { static final String ACTION_DECLINE = "android.btopp.intent.action.DECLINE"; /** - * the intent that gets sent when deleting the notifications of outbound and - * inbound completed transfer + * The intent that gets sent when deleting the notifications of outbound and inbound completed + * transfer. */ + // TODO(b/323096132): Remove this variable when the flag + // opp_fix_multiple_notifications_issues is ramped up. static final String ACTION_COMPLETE_HIDE = "android.btopp.intent.action.HIDE_COMPLETE"; + /** The intent that gets sent when deleting the notifications of completed inbound transfer. */ + static final String ACTION_HIDE_COMPLETED_INBOUND_TRANSFER = + "android.btopp.intent.action.HIDE_COMPLETED_INBOUND_TRANSFER"; + + /** The intent that gets sent when deleting the notifications of completed outbound transfer. */ + static final String ACTION_HIDE_COMPLETED_OUTBOUND_TRANSFER = + "android.btopp.intent.action.HIDE_COMPLETED_OUTBOUND_TRANSFER"; + /** the intent that gets sent when clicking a incoming file confirm notification */ static final String ACTION_INCOMING_FILE_CONFIRM = "android.btopp.intent.action.CONFIRM"; diff --git a/android/app/src/com/android/bluetooth/pan/PanService.java b/android/app/src/com/android/bluetooth/pan/PanService.java index f10338a157..04a169fd43 100644 --- a/android/app/src/com/android/bluetooth/pan/PanService.java +++ b/android/app/src/com/android/bluetooth/pan/PanService.java @@ -148,7 +148,7 @@ public class PanService extends ProfileService { } @Override - protected void start() { + public void start() { mAdapterService = Objects.requireNonNull(AdapterService.getAdapterService(), "AdapterService cannot be null when PanService starts"); mDatabaseManager = Objects.requireNonNull(AdapterService.getAdapterService().getDatabase(), @@ -178,7 +178,7 @@ public class PanService extends ProfileService { } @Override - protected void stop() { + public void stop() { if (!mStarted) { Log.w(TAG, "stop() called before start()"); return; @@ -192,7 +192,7 @@ public class PanService extends ProfileService { } @Override - protected void cleanup() { + public void cleanup() { // TODO(b/72948646): this should be moved to stop() setPanService(null); diff --git a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java index 69ece29384..f87e345c87 100644 --- a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java +++ b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java @@ -725,7 +725,7 @@ public class BluetoothPbapService extends ProfileService implements IObexConnect } @Override - protected void start() { + public void start() { if (VERBOSE) { Log.v(TAG, "start()"); } @@ -791,7 +791,7 @@ public class BluetoothPbapService extends ProfileService implements IObexConnect } @Override - protected void stop() { + public void stop() { if (VERBOSE) { Log.v(TAG, "stop()"); } diff --git a/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java b/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java index 2239194862..abd92ee18f 100644 --- a/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java +++ b/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java @@ -134,7 +134,7 @@ public class PbapClientService extends ProfileService { } @Override - protected void start() { + public void start() { if (VDBG) { Log.v(TAG, "onStart"); } @@ -163,7 +163,7 @@ public class PbapClientService extends ProfileService { } @Override - protected void stop() { + public void stop() { setPbapClientService(null); cleanUpSdpRecord(); try { diff --git a/android/app/src/com/android/bluetooth/sap/SapService.java b/android/app/src/com/android/bluetooth/sap/SapService.java index 4a9c4203ca..68dfc155c6 100644 --- a/android/app/src/com/android/bluetooth/sap/SapService.java +++ b/android/app/src/com/android/bluetooth/sap/SapService.java @@ -680,7 +680,7 @@ public class SapService extends ProfileService implements AdapterService.Bluetoo } @Override - protected void start() { + public void start() { Log.v(TAG, "start()"); IntentFilter filter = new IntentFilter(); filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); @@ -702,7 +702,7 @@ public class SapService extends ProfileService implements AdapterService.Bluetoo } @Override - protected void stop() { + public void stop() { Log.v(TAG, "stop()"); if (!mIsRegistered) { Log.i(TAG, "Avoid unregister when receiver it is not registered"); diff --git a/android/app/src/com/android/bluetooth/tbs/TbsService.java b/android/app/src/com/android/bluetooth/tbs/TbsService.java index 69302eb78d..676958808c 100644 --- a/android/app/src/com/android/bluetooth/tbs/TbsService.java +++ b/android/app/src/com/android/bluetooth/tbs/TbsService.java @@ -65,7 +65,7 @@ public class TbsService extends ProfileService { } @Override - protected void start() { + public void start() { if (DBG) { Log.d(TAG, "start()"); @@ -81,7 +81,7 @@ public class TbsService extends ProfileService { } @Override - protected void stop() { + public void stop() { if (DBG) { Log.d(TAG, "stop()"); } @@ -99,7 +99,7 @@ public class TbsService extends ProfileService { } @Override - protected void cleanup() { + public void cleanup() { if (DBG) { Log.d(TAG, "cleanup()"); } @@ -144,6 +144,17 @@ public class TbsService extends ProfileService { } /** + * Remove authorization information for the device. + * + * @param device device to remove from the service information + * @hide + */ + public void removeDeviceAuthorizationInfo(BluetoothDevice device) { + Log.i(TAG, "removeDeviceAuthorizationInfo(): device: " + device); + mDeviceAuthorizations.remove(device); + } + + /** * Sets device authorization for TBS. * * @param device device that would be authorized diff --git a/android/app/src/com/android/bluetooth/vc/VolumeControlService.java b/android/app/src/com/android/bluetooth/vc/VolumeControlService.java index 81699c6d67..897122e1d0 100644 --- a/android/app/src/com/android/bluetooth/vc/VolumeControlService.java +++ b/android/app/src/com/android/bluetooth/vc/VolumeControlService.java @@ -239,7 +239,7 @@ public class VolumeControlService extends ProfileService { } @Override - protected void start() { + public void start() { if (DBG) { Log.d(TAG, "start()"); } @@ -280,7 +280,7 @@ public class VolumeControlService extends ProfileService { } @Override - protected void stop() { + public void stop() { if (DBG) { Log.d(TAG, "stop()"); } @@ -338,7 +338,7 @@ public class VolumeControlService extends ProfileService { } @Override - protected void cleanup() { + public void cleanup() { if (DBG) { Log.d(TAG, "cleanup()"); } @@ -1031,10 +1031,23 @@ public class VolumeControlService extends ProfileService { // Copied from AudioService.getBluetoothContextualVolumeStream() and modified it. int getBluetoothContextualVolumeStream() { int mode = mAudioManager.getMode(); + + if (DBG) { + Log.d(TAG, "Volume mode: " + mode + "0: normal, 1: ring, 2,3: call"); + } + switch (mode) { case AudioManager.MODE_IN_COMMUNICATION: case AudioManager.MODE_IN_CALL: return AudioManager.STREAM_VOICE_CALL; + case AudioManager.MODE_RINGTONE: + if (mFeatureFlags.leaudioVolumeChangeOnRingtoneFix()) { + if (DBG) { + Log.d(TAG, " Update during ringtone applied to voice call"); + } + return AudioManager.STREAM_VOICE_CALL; + } + // fall through case AudioManager.MODE_NORMAL: default: // other conditions will influence the stream type choice, read on... 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 4200598a1a..6dacf8fe8c 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 @@ -108,7 +108,8 @@ public class A2dpServiceTest { doReturn(mSilenceDeviceManager).when(mAdapterService).getSilenceDeviceManager(); mA2dpService = new A2dpService(mContext, mMockNativeInterface); - mA2dpService.doStart(); + mA2dpService.start(); + mA2dpService.setAvailable(true); // Override the timeout value to speed up the test A2dpStateMachine.sConnectTimeoutMs = (int) TIMEOUT.toMillis(); @@ -124,7 +125,7 @@ public class A2dpServiceTest { @After public void tearDown() throws Exception { - mA2dpService.doStop(); + mA2dpService.stop(); TestUtils.clearAdapterService(mAdapterService); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceTest.java index a48b5be2e9..6f546daa9d 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceTest.java @@ -103,7 +103,7 @@ public class A2dpSinkServiceTest { doReturn(true).when(mNativeInterface).setActiveDevice(any()); mService = new A2dpSinkService(mTargetContext, mNativeInterface, mLooper.getLooper()); - mService.doStart(); + mService.start(); assertThat(mLooper.nextMessage()).isNull(); } @@ -111,7 +111,7 @@ public class A2dpSinkServiceTest { public void tearDown() throws Exception { assertThat(mLooper.nextMessage()).isNull(); - mService.doStop(); + mService.stop(); assertThat(A2dpSinkService.getA2dpSinkService()).isNull(); TestUtils.clearAdapterService(mAdapterService); } @@ -295,6 +295,26 @@ public class A2dpSinkServiceTest { assertThat(config).isEqualTo(expected); } + /** Make sure we ignore audio configuration changes for disconnected/unknown devices */ + @Test + public void testOnAudioConfigChanged_withNullDevice_eventDropped() { + StackEvent audioConfigChanged = + StackEvent.audioConfigChanged(null, TEST_SAMPLE_RATE, TEST_CHANNEL_COUNT); + mService.messageFromNative(audioConfigChanged); + assertThat(mService.getAudioConfig(null)).isNull(); + } + + /** Make sure we ignore audio configuration changes for disconnected/unknown devices */ + @Test + public void testOnAudioConfigChanged_withUnknownDevice_eventDropped() { + assertThat(mService.getConnectionState(mDevice1)) + .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + StackEvent audioConfigChanged = + StackEvent.audioConfigChanged(mDevice1, TEST_SAMPLE_RATE, TEST_CHANNEL_COUNT); + mService.messageFromNative(audioConfigChanged); + assertThat(mService.getAudioConfig(mDevice1)).isNull(); + } + /** * Getting an audio config for a device that hasn't received one yet should return null */ diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStreamHandlerTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStreamHandlerTest.java index c8019353a7..4b25bbba1d 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStreamHandlerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStreamHandlerTest.java @@ -84,7 +84,7 @@ public class A2dpSinkStreamHandlerTest { TestUtils.setAdapterService(mAdapterService); AvrcpControllerNativeInterface.setInstance(mMockAvrcpControllerNativeInterface); mService = new AvrcpControllerService(mTargetContext, mMockAvrcpControllerNativeInterface); - mService.doStart(); + mService.start(); final Intent bluetoothBrowserMediaServiceStartIntent = TestUtils.prepareIntentToStartBluetoothBrowserMediaService(); mBluetoothBrowserMediaServiceTestRule.startService(bluetoothBrowserMediaServiceStartIntent); @@ -111,7 +111,7 @@ public class A2dpSinkStreamHandlerTest { @After public void tearDown() throws Exception { - mService.doStop(); + mService.stop(); AvrcpControllerNativeInterface.setInstance(null); TestUtils.clearAdapterService(mAdapterService); } 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 f748dad866..e3dd565833 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 @@ -19,8 +19,6 @@ package com.android.bluetooth.avrcpcontroller; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doReturn; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; @@ -68,7 +66,7 @@ public class AvrcpBipClientTest { TestUtils.setAdapterService(mAdapterService); AvrcpControllerNativeInterface.setInstance(mNativeInterface); mService = new AvrcpControllerService(targetContext, mNativeInterface); - mService.doStart(); + mService.start(); final Intent bluetoothBrowserMediaServiceStartIntent = TestUtils.prepareIntentToStartBluetoothBrowserMediaService(); mBluetoothBrowserMediaServiceTestRule.startService(bluetoothBrowserMediaServiceStartIntent); @@ -86,7 +84,7 @@ public class AvrcpBipClientTest { @After public void tearDown() throws Exception { - mService.doStop(); + mService.stop(); AvrcpControllerNativeInterface.setInstance(null); mService = AvrcpControllerService.getAvrcpControllerService(); assertThat(mService).isNull(); 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 5ad1408ec9..19b8f6c95e 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 @@ -18,9 +18,7 @@ package com.android.bluetooth.avrcpcontroller; import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.any; -import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -82,7 +80,7 @@ public class AvrcpControllerServiceTest { TestUtils.setAdapterService(mAdapterService); AvrcpControllerNativeInterface.setInstance(mNativeInterface); mService = new AvrcpControllerService(targetContext, mNativeInterface); - mService.doStart(); + mService.start(); // Try getting the Bluetooth adapter mAdapter = BluetoothAdapter.getDefaultAdapter(); assertThat(mAdapter).isNotNull(); @@ -95,7 +93,7 @@ public class AvrcpControllerServiceTest { @After public void tearDown() throws Exception { - mService.doStop(); + mService.stop(); AvrcpControllerNativeInterface.setInstance(null); mService = AvrcpControllerService.getAvrcpControllerService(); assertThat(mService).isNull(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryServiceTest.java index fbee892a5d..64753a466d 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryServiceTest.java @@ -17,7 +17,6 @@ package com.android.bluetooth.bas; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; @@ -95,11 +94,12 @@ public class BatteryServiceTest { private void startService() throws TimeoutException { mService = new BatteryService(mTargetContext); - mService.doStart(); + mService.start(); + mService.setAvailable(true); } private void stopService() throws TimeoutException { - mService.doStop(); + mService.stop(); mService = BatteryService.getBatteryService(); Assert.assertNull(mService); } 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 a554946ae4..578ba86937 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 @@ -247,7 +247,8 @@ public class BassClientServiceTest { mFakeFlagsImpl.setFlag(Flags.FLAG_LEAUDIO_BROADCAST_AUDIO_HANDOVER_POLICIES, false); mBassClientService = new BassClientService(mTargetContext, mFakeFlagsImpl); - mBassClientService.doStart(); + mBassClientService.start(); + mBassClientService.setAvailable(true); mBassClientService.mServiceFactory = mServiceFactory; doReturn(mCsipService).when(mServiceFactory).getCsipSetCoordinatorService(); @@ -276,7 +277,7 @@ public class BassClientServiceTest { } mBassClientService.unregisterCallback(mCallback); - mBassClientService.doStop(); + mBassClientService.stop(); mBassClientService = BassClientService.getBassClientService(); assertThat(mBassClientService).isNull(); mStateMachines.clear(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/AudioRoutingManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/AudioRoutingManagerTest.java index 907eaca9a4..362c9532c2 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/AudioRoutingManagerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/AudioRoutingManagerTest.java @@ -250,25 +250,26 @@ public class AudioRoutingManagerTest { } /** - * Two A2DP devices are connected and the current active is then disconnected. Should then set - * active device to fallback device. + * A2DP Headset and A2DP only devices are connected and the current activated A2DP only is then + * disconnected. Should then set active device to fallback device. */ @Test - public void a2dpSecondDeviceDisconnected_fallbackDeviceActive() { + public void a2dpDeviceDisconnected_fallbackA2dpHeadset() { + a2dpConnected(mA2dpHeadsetDevice, true); + headsetConnected(mA2dpHeadsetDevice, true); + mTestLooper.dispatchAll(); + verify(mA2dpService).setActiveDevice(mA2dpHeadsetDevice); + verify(mHeadsetService).setActiveDevice(mA2dpHeadsetDevice); + a2dpConnected(mA2dpDevice, false); switchA2dpActiveDevice(mA2dpDevice); mTestLooper.dispatchAll(); verify(mA2dpService).setActiveDevice(mA2dpDevice); - a2dpConnected(mSecondaryAudioDevice, false); - switchA2dpActiveDevice(mSecondaryAudioDevice); - mTestLooper.dispatchAll(); - verify(mA2dpService).setActiveDevice(mSecondaryAudioDevice); - - Mockito.clearInvocations(mA2dpService); - a2dpDisconnected(mSecondaryAudioDevice); + Mockito.clearInvocations(mA2dpService, mHeadsetService); + a2dpDisconnected(mA2dpDevice); mTestLooper.dispatchAll(); - verify(mA2dpService).setActiveDevice(mA2dpDevice); + verify(mA2dpService).setActiveDevice(mA2dpHeadsetDevice); } /** One Headset is connected. */ @@ -323,11 +324,11 @@ public class AudioRoutingManagerTest { } /** - * Two Headsets are connected and the current active is then disconnected. Should then set - * active device to fallback device. + * Two Headset only devices are connected and the current active is then disconnected. Then it + * should be fallback to phone. */ @Test - public void headsetSecondDeviceDisconnected_fallbackDeviceActive() { + public void headsetSecondDeviceDisconnected_fallbackToPhone() { when(mAudioManager.getMode()).thenReturn(AudioManager.MODE_IN_CALL); headsetConnected(mHeadsetDevice, false); @@ -343,27 +344,28 @@ public class AudioRoutingManagerTest { Mockito.clearInvocations(mHeadsetService); headsetDisconnected(mSecondaryAudioDevice); mTestLooper.dispatchAll(); - verify(mHeadsetService).setActiveDevice(mHeadsetDevice); + verify(mHeadsetService, never()).setActiveDevice(mHeadsetDevice); } @Test public void headsetSecondDeviceDisconnected_fallbackDeviceActiveWhileRinging() { when(mAudioManager.getMode()).thenReturn(AudioManager.MODE_RINGTONE); + headsetConnected(mA2dpHeadsetDevice, true); + a2dpConnected(mA2dpHeadsetDevice, true); + mTestLooper.dispatchAll(); + verify(mHeadsetService).setActiveDevice(mA2dpHeadsetDevice); + verify(mA2dpService).setActiveDevice(mA2dpHeadsetDevice); + headsetConnected(mHeadsetDevice, false); switchHeadsetActiveDevice(mHeadsetDevice); mTestLooper.dispatchAll(); verify(mHeadsetService).setActiveDevice(mHeadsetDevice); - headsetConnected(mSecondaryAudioDevice, false); - switchHeadsetActiveDevice(mSecondaryAudioDevice); - mTestLooper.dispatchAll(); - verify(mHeadsetService).setActiveDevice(mSecondaryAudioDevice); - Mockito.clearInvocations(mHeadsetService); - headsetDisconnected(mSecondaryAudioDevice); + headsetDisconnected(mHeadsetDevice); mTestLooper.dispatchAll(); - verify(mHeadsetService).setActiveDevice(mHeadsetDevice); + verify(mHeadsetService).setActiveDevice(mA2dpHeadsetDevice); } @Test @@ -842,11 +844,11 @@ public class AudioRoutingManagerTest { } /** - * An A2DP connected. An LE Audio connected. The LE Audio disconnected. Then the A2DP should be - * the active one. + * An A2DP only device connected. An LE Audio connected. The LE Audio disconnected. Then it + * should be fallback to phone instead of the A2DP only device. */ @Test - public void a2dpAndLeAudioConnectedThenLeAudioDisconnected_fallbackToA2dp() { + public void a2dpAndLeAudioConnectedThenLeAudioDisconnected_fallbackToPhone() { when(mAudioManager.getMode()).thenReturn(AudioManager.MODE_NORMAL); a2dpConnected(mA2dpDevice, false); @@ -861,8 +863,34 @@ public class AudioRoutingManagerTest { Mockito.clearInvocations(mA2dpService); leAudioDisconnected(mLeAudioDevice); mTestLooper.dispatchAll(); + verify(mLeAudioService).removeActiveDevice(false); + verify(mA2dpService, never()).setActiveDevice(mA2dpDevice); + } + + /** + * An A2DP headset connected. An LE Audio connected. The LE Audio disconnected. Then the A2DP + * headset should be the active one. + */ + @Test + public void a2dpHeadsetAndLeAudioConnectedThenLeAudioDisconnected_fallbackToA2dpHeadset() { + when(mAudioManager.getMode()).thenReturn(AudioManager.MODE_NORMAL); + + a2dpConnected(mHeadsetDevice, true); + headsetConnected(mHeadsetDevice, true); + mTestLooper.dispatchAll(); + verify(mA2dpService).setActiveDevice(mHeadsetDevice); + verify(mHeadsetService).setActiveDevice(mHeadsetDevice); + + leAudioConnected(mLeAudioDevice); + mTestLooper.dispatchAll(); + verify(mLeAudioService).setActiveDevice(mLeAudioDevice); + + Mockito.clearInvocations(mA2dpService, mHeadsetService); + leAudioDisconnected(mLeAudioDevice); + mTestLooper.dispatchAll(); verify(mLeAudioService).removeActiveDevice(true); - verify(mA2dpService).setActiveDevice(mA2dpDevice); + verify(mA2dpService).setActiveDevice(mHeadsetDevice); + verify(mHeadsetService).setActiveDevice(mHeadsetDevice); } /** @@ -920,7 +948,7 @@ public class AudioRoutingManagerTest { Mockito.clearInvocations(mHearingAidService, mA2dpService, mLeAudioService); leAudioDisconnected(mLeAudioDevice); mTestLooper.dispatchAll(); - verify(mA2dpService).setActiveDevice(mA2dpDevice); + verify(mHearingAidService).setActiveDevice(mHearingAidDevice); verify(mLeAudioService).removeActiveDevice(true); } 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 0045e71a1c..54d3e7bf10 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 @@ -742,6 +742,12 @@ public class RemoteDevicesTest { Assert.assertFalse(deviceProp.isCoordinatedSetMember()); } + @Test + public void testIsDeviceNull() { + Assert.assertNull(mRemoteDevices.getDeviceProperties(null)); + } + + private static void verifyBatteryLevelChangedIntent(BluetoothDevice device, int batteryLevel, ArgumentCaptor<Intent> intentArgument) { verifyBatteryLevelChangedIntent(device, batteryLevel, intentArgument.getValue()); 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 72f9b7ce28..73d715dd52 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 @@ -1454,6 +1454,30 @@ public final class DatabaseManagerTest { } } + @Test + public void testDatabaseMigration_119_120() throws IOException { + // Create a database with version 119 + SupportSQLiteDatabase db = testHelper.createDatabase(DB_NAME, 119); + // insert a device to the database + ContentValues device = new ContentValues(); + device.put("address", TEST_BT_ADDR); + device.put("migrated", false); + assertThat( + db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device), + CoreMatchers.not(-1)); + // Migrate database from 119 to 120 + db.close(); + db = + testHelper.runMigrationsAndValidate( + DB_NAME, 120, true, MetadataDatabase.MIGRATION_119_120); + Cursor cursor = db.query("SELECT * FROM metadata"); + assertHasColumn(cursor, "active_audio_device_policy", true); + while (cursor.moveToNext()) { + // Check the new columns was added with default value + assertColumnIntData(cursor, "active_audio_device_policy", 0); + } + } + /** * Helper function to check whether the database has the expected column */ diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/schemas/com.android.bluetooth.btservice.storage.MetadataDatabase/120.json b/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/schemas/com.android.bluetooth.btservice.storage.MetadataDatabase/120.json new file mode 100644 index 0000000000..889402da63 --- /dev/null +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/schemas/com.android.bluetooth.btservice.storage.MetadataDatabase/120.json @@ -0,0 +1,400 @@ +{ + "formatVersion": 1, + "database": { + "version": 120, + "identityHash": "5e9dc09807d50827ab4928ae23ac4173", + "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, `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": "profileConnectionPolicies.a2dp_connection_policy", + "columnName": "a2dp_connection_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "profileConnectionPolicies.a2dp_sink_connection_policy", + "columnName": "a2dp_sink_connection_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "profileConnectionPolicies.hfp_connection_policy", + "columnName": "hfp_connection_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "profileConnectionPolicies.hfp_client_connection_policy", + "columnName": "hfp_client_connection_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "profileConnectionPolicies.hid_host_connection_policy", + "columnName": "hid_host_connection_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "profileConnectionPolicies.pan_connection_policy", + "columnName": "pan_connection_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "profileConnectionPolicies.pbap_connection_policy", + "columnName": "pbap_connection_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "profileConnectionPolicies.pbap_client_connection_policy", + "columnName": "pbap_client_connection_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "profileConnectionPolicies.map_connection_policy", + "columnName": "map_connection_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "profileConnectionPolicies.sap_connection_policy", + "columnName": "sap_connection_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "profileConnectionPolicies.hearing_aid_connection_policy", + "columnName": "hearing_aid_connection_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "profileConnectionPolicies.hap_client_connection_policy", + "columnName": "hap_client_connection_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "profileConnectionPolicies.map_client_connection_policy", + "columnName": "map_client_connection_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "profileConnectionPolicies.le_audio_connection_policy", + "columnName": "le_audio_connection_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "profileConnectionPolicies.volume_control_connection_policy", + "columnName": "volume_control_connection_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "profileConnectionPolicies.csip_set_coordinator_connection_policy", + "columnName": "csip_set_coordinator_connection_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "profileConnectionPolicies.le_call_control_connection_policy", + "columnName": "le_call_control_connection_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "profileConnectionPolicies.bass_client_connection_policy", + "columnName": "bass_client_connection_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "profileConnectionPolicies.battery_connection_policy", + "columnName": "battery_connection_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "publicMetadata.manufacturer_name", + "columnName": "manufacturer_name", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.model_name", + "columnName": "model_name", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.software_version", + "columnName": "software_version", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.hardware_version", + "columnName": "hardware_version", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.companion_app", + "columnName": "companion_app", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.main_icon", + "columnName": "main_icon", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.is_untethered_headset", + "columnName": "is_untethered_headset", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.untethered_left_icon", + "columnName": "untethered_left_icon", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.untethered_right_icon", + "columnName": "untethered_right_icon", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.untethered_case_icon", + "columnName": "untethered_case_icon", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.untethered_left_battery", + "columnName": "untethered_left_battery", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.untethered_right_battery", + "columnName": "untethered_right_battery", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.untethered_case_battery", + "columnName": "untethered_case_battery", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.untethered_left_charging", + "columnName": "untethered_left_charging", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.untethered_right_charging", + "columnName": "untethered_right_charging", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.untethered_case_charging", + "columnName": "untethered_case_charging", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.enhanced_settings_ui_uri", + "columnName": "enhanced_settings_ui_uri", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.device_type", + "columnName": "device_type", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.main_battery", + "columnName": "main_battery", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.main_charging", + "columnName": "main_charging", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.main_low_battery_threshold", + "columnName": "main_low_battery_threshold", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.untethered_left_low_battery_threshold", + "columnName": "untethered_left_low_battery_threshold", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.untethered_right_low_battery_threshold", + "columnName": "untethered_right_low_battery_threshold", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.untethered_case_low_battery_threshold", + "columnName": "untethered_case_low_battery_threshold", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.spatial_audio", + "columnName": "spatial_audio", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.fastpair_customized", + "columnName": "fastpair_customized", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.le_audio", + "columnName": "le_audio", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.gmcs_cccd", + "columnName": "gmcs_cccd", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.gtbs_cccd", + "columnName": "gtbs_cccd", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "publicMetadata.exclusive_manager", + "columnName": "exclusive_manager", + "affinity": "BLOB", + "notNull": false + }, + { + "fieldPath": "audioPolicyMetadata.callEstablishAudioPolicy", + "columnName": "call_establish_audio_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "audioPolicyMetadata.connectingTimeAudioPolicy", + "columnName": "connecting_time_audio_policy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "audioPolicyMetadata.inBandRingtoneAudioPolicy", + "columnName": "in_band_ringtone_audio_policy", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "address" + ] + }, + "indices": [], + "foreignKeys": [] + } + ], + "views": [], + "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, '5e9dc09807d50827ab4928ae23ac4173')" + ] + } +}
\ No newline at end of file diff --git a/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java index 10f57c54ad..fdfcfc2700 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java @@ -163,11 +163,12 @@ public class CsipSetCoordinatorServiceTest { private void startService() throws TimeoutException { mService = new CsipSetCoordinatorService(mTargetContext); - mService.doStart(); + mService.start(); + mService.setAvailable(true); } private void stopService() throws TimeoutException { - mService.doStop(); + mService.stop(); mService = CsipSetCoordinatorService.getCsipSetCoordinatorService(); Assert.assertNull(mService); } 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 e197a3d04c..1d129592f2 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 @@ -47,6 +47,8 @@ import android.os.RemoteException; import android.os.WorkSource; import android.platform.test.annotations.RequiresFlagsEnabled; +import android.platform.test.flag.junit.CheckFlagsRule; +import android.platform.test.flag.junit.DeviceFlagsValueProvider; import androidx.test.InstrumentationRegistry; import androidx.test.filters.SmallTest; import androidx.test.rule.ServiceTestRule; @@ -59,8 +61,10 @@ import com.android.bluetooth.le_scan.AppScanStats; import com.android.bluetooth.le_scan.PeriodicScanManager; import com.android.bluetooth.le_scan.ScanClient; import com.android.bluetooth.le_scan.ScanManager; +import com.android.bluetooth.le_scan.TransitionalScanHelper; import com.android.bluetooth.flags.Flags; + import org.junit.After; import org.junit.Assert; import org.junit.Assume; @@ -95,8 +99,8 @@ public class GattServiceTest { private Context mTargetContext; private GattService mService; @Mock private GattService.ClientMap mClientMap; - @Mock private GattService.ScannerMap mScannerMap; - @Mock private GattService.ScannerMap.App mApp; + @Mock private TransitionalScanHelper.ScannerMap mScannerMap; + @Mock private TransitionalScanHelper.ScannerMap.App mApp; @Mock private GattService.PendingIntentInfo mPiInfo; @Mock private PeriodicScanManager mPeriodicScanManager; @Mock private ScanManager mScanManager; @@ -107,6 +111,9 @@ public class GattServiceTest { @Rule public final ServiceTestRule mServiceRule = new ServiceTestRule(); + @Rule + public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule(); + private BluetoothDevice mDevice; private BluetoothAdapter mAdapter; private AttributionSource mAttributionSource; @@ -153,7 +160,7 @@ public class GattServiceTest { mService.start(); mService.mClientMap = mClientMap; - mService.mScannerMap = mScannerMap; + mService.mTransitionalScanHelper.setScannerMap(mScannerMap); mService.mReliableQueue = mReliableQueue; mService.mServerMap = mServerMap; } @@ -241,7 +248,7 @@ public class GattServiceTest { mService.connectionParameterUpdate(clientIf, address, connectionPriority, mAttributionSource); - connectionPriority = BluetoothGatt.CONNECTION_PRIORITY_BALANCED;; + connectionPriority = BluetoothGatt.CONNECTION_PRIORITY_BALANCED; mService.connectionParameterUpdate(clientIf, address, connectionPriority, mAttributionSource); @@ -885,4 +892,46 @@ public class GattServiceTest { BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); } + + @RequiresFlagsEnabled(Flags.FLAG_GATT_CLEANUP_RESTRICTED_HANDLES) + @Test + public void restrictedHandles() throws Exception { + int clientIf = 1; + int connId = 1; + ArrayList<GattDbElement> db = new ArrayList<>(); + + GattService.ClientMap.App app = mock(GattService.ClientMap.App.class); + IBluetoothGattCallback callback = mock(IBluetoothGattCallback.class); + + doReturn(app).when(mClientMap).getByConnId(connId); + app.callback = callback; + + GattDbElement hidService = + GattDbElement.createPrimaryService( + UUID.fromString("00001812-0000-1000-8000-00805F9B34FB")); + hidService.id = 1; + + GattDbElement hidInfoChar = + GattDbElement.createCharacteristic( + UUID.fromString("00002A4A-0000-1000-8000-00805F9B34FB"), 0, 0); + hidInfoChar.id = 2; + + GattDbElement randomChar = + GattDbElement.createCharacteristic( + UUID.fromString("0000FFFF-0000-1000-8000-00805F9B34FB"), 0, 0); + randomChar.id = 3; + + db.add(hidService); + db.add(hidInfoChar); + db.add(randomChar); + + mService.onGetGattDb(connId, db); + // HID characteristics should be restricted + assertThat(mService.mRestrictedHandles.get(connId)).contains(hidInfoChar.id); + assertThat(mService.mRestrictedHandles.get(connId)).doesNotContain(randomChar.id); + + mService.onDisconnected( + clientIf, connId, BluetoothGatt.GATT_SUCCESS, REMOTE_DEVICE_ADDRESS); + assertThat(mService.mRestrictedHandles).doesNotContainKey(connId); + } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientTest.java b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientTest.java index 73e57f0e3a..915088ae49 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientTest.java @@ -17,15 +17,31 @@ package com.android.bluetooth.hap; +import static androidx.test.espresso.intent.matcher.IntentMatchers.hasAction; +import static androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra; + import static org.mockito.Mockito.after; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyInt; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.times; +import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; +import static org.hamcrest.core.AllOf.allOf; + +import static android.bluetooth.BluetoothHapClient.ACTION_HAP_CONNECTION_STATE_CHANGED; +import static android.bluetooth.BluetoothHapClient.ACTION_HAP_DEVICE_AVAILABLE; + +import static android.bluetooth.BluetoothProfile.EXTRA_STATE; +import static android.bluetooth.BluetoothProfile.EXTRA_PREVIOUS_STATE; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; @@ -36,10 +52,7 @@ import android.bluetooth.BluetoothStatusCodes; import android.bluetooth.BluetoothUuid; import android.bluetooth.IBluetoothHapClientCallback; import android.content.AttributionSource; -import android.content.BroadcastReceiver; import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; import android.os.Binder; import android.os.Looper; import android.os.ParcelUuid; @@ -63,6 +76,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -74,7 +88,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeoutException; @MediumTest @@ -87,13 +100,11 @@ public class HapClientTest { private BluetoothDevice mDevice; private BluetoothDevice mDevice2; private BluetoothDevice mDevice3; - private Context mTargetContext; private HapClientService mService; private HapClientService.BluetoothHapClientBinder mServiceBinder; private AttributionSource mAttributionSource; - private HasIntentReceiver mHasIntentReceiver; - private HashMap<BluetoothDevice, LinkedBlockingQueue<Intent>> mIntentQueue; + @Mock private Context mContext; @Mock private AdapterService mAdapterService; @Mock private DatabaseManager mDatabaseManager; @Mock private HapClientNativeInterface mNativeInterface; @@ -108,7 +119,6 @@ public class HapClientTest { System.setProperty("dexmaker.share_classloader", "true"); } - mTargetContext = InstrumentationRegistry.getTargetContext(); // Set up mocks and test assets MockitoAnnotations.initMocks(this); @@ -131,18 +141,9 @@ public class HapClientTest { mServiceBinder = (HapClientService.BluetoothHapClientBinder) mService.initBinder(); mServiceBinder.mIsTesting = true; - // Set up the State Changed receiver - IntentFilter filter = new IntentFilter(); - filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); - filter.addAction(BluetoothHapClient.ACTION_HAP_CONNECTION_STATE_CHANGED); - filter.addAction(BluetoothHapClient.ACTION_HAP_DEVICE_AVAILABLE); - when(mCallback.asBinder()).thenReturn(mBinder); mService.mCallbacks.register(mCallback); - mHasIntentReceiver = new HasIntentReceiver(); - mTargetContext.registerReceiver(mHasIntentReceiver, filter, Context.RECEIVER_EXPORTED); - mDevice = TestUtils.getTestDevice(mAdapter, 0); when(mNativeInterface.getDevice(getByteAddress(mDevice))).thenReturn(mDevice); mDevice2 = TestUtils.getTestDevice(mAdapter, 1); @@ -192,11 +193,6 @@ public class HapClientTest { doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); doReturn(mDatabaseManager).when(mAdapterService).getDatabase(); - - mIntentQueue = new HashMap<>(); - mIntentQueue.put(mDevice, new LinkedBlockingQueue<>()); - mIntentQueue.put(mDevice2, new LinkedBlockingQueue<>()); - mIntentQueue.put(mDevice3, new LinkedBlockingQueue<>()); } @After @@ -214,27 +210,21 @@ public class HapClientTest { stopService(); HapClientNativeInterface.setInstance(null); - if (mHasIntentReceiver != null) { - mTargetContext.unregisterReceiver(mHasIntentReceiver); - } - mAdapter = null; if (mAdapterService != null) { TestUtils.clearAdapterService(mAdapterService); } - - if (mIntentQueue != null) - mIntentQueue.clear(); } private void startService() throws TimeoutException { - mService = new HapClientService(mTargetContext); - mService.doStart(); + mService = new HapClientService(mContext); + mService.start(); + mService.setAvailable(true); } private void stopService() throws TimeoutException { - mService.doStop(); + mService.stop(); mService = HapClientService.getHapClientService(); Assert.assertNull(mService); } @@ -381,7 +371,7 @@ public class HapClientTest { // Send a connect request Assert.assertTrue("Connect expected to succeed", mService.connect(mDevice)); - TestUtils.waitForIntent(TIMEOUT_MS, mIntentQueue.get(mDevice)); + verify(mContext, timeout(TIMEOUT_MS)).sendBroadcast(any(), any()); } /** @@ -406,6 +396,8 @@ public class HapClientTest { */ @Test public void testOutgoingConnectTimeout() throws Exception { + InOrder order = inOrder(mContext); + // Update the device policy so okToConnect() returns true when(mDatabaseManager .getProfileConnectionPolicy(mDevice, BluetoothProfile.HAP_CLIENT)) @@ -416,15 +408,30 @@ public class HapClientTest { // Send a connect request Assert.assertTrue("Connect failed", mService.connect(mDevice)); - // Verify the connection state broadcast, and that we are in Connecting state - verifyConnectionStateIntent(TIMEOUT_MS, mDevice, BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_DISCONNECTED); + order.verify(mContext, timeout(TIMEOUT_MS)) + .sendBroadcast( + argThat( + allOf( + hasAction(ACTION_HAP_CONNECTION_STATE_CHANGED), + hasExtra(BluetoothDevice.EXTRA_DEVICE, mDevice), + hasExtra(EXTRA_STATE, STATE_CONNECTING), + hasExtra(EXTRA_PREVIOUS_STATE, STATE_DISCONNECTED))), + any()); + Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, mService.getConnectionState(mDevice)); // Verify the connection state broadcast, and that we are in Disconnected state via binder - verifyConnectionStateIntent(HapClientStateMachine.sConnectTimeoutMs * 2, - mDevice, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); + order.verify(mContext, timeout(HapClientStateMachine.sConnectTimeoutMs * 2)) + .sendBroadcast( + argThat( + allOf( + hasAction(ACTION_HAP_CONNECTION_STATE_CHANGED), + hasExtra(BluetoothDevice.EXTRA_DEVICE, mDevice), + hasExtra(EXTRA_STATE, STATE_DISCONNECTED), + hasExtra(EXTRA_PREVIOUS_STATE, STATE_CONNECTING))), + any()); + final SynchronousResultReceiver<Integer> recv = SynchronousResultReceiver.get(); int defaultRecvValue = -1000; mServiceBinder.getConnectionState(mDevice, mAttributionSource, recv); @@ -438,15 +445,16 @@ public class HapClientTest { */ @Test public void testConnectTwo() throws Exception { + InOrder order = inOrder(mContext); doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); // Send a connect request for the 1st device - testConnectingDevice(mDevice); + testConnectingDevice(order, mDevice); // Send a connect request for the 2nd device BluetoothDevice Device2 = TestUtils.getTestDevice(mAdapter, 1); - testConnectingDevice(Device2); + testConnectingDevice(order, Device2); // indirect call of mService.getConnectedDevices to test BluetoothHearingAidBinder final SynchronousResultReceiver<List<BluetoothDevice>> recv = @@ -473,11 +481,12 @@ public class HapClientTest { */ @Test public void testGetHapGroupCoordinatedOps() throws Exception { + InOrder order = inOrder(mContext); doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); - testConnectingDevice(mDevice); - testConnectingDevice(mDevice2); - testConnectingDevice(mDevice3); + testConnectingDevice(order, mDevice); + testConnectingDevice(order, mDevice2); + testConnectingDevice(order, mDevice3); int flags = 0x04; mNativeInterface.onFeaturesUpdate(getByteAddress(mDevice), flags); @@ -510,9 +519,10 @@ public class HapClientTest { */ @Test public void testSelectPresetNative() { + InOrder order = inOrder(mContext); doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); - testConnectingDevice(mDevice); + testConnectingDevice(order, mDevice); // Verify Native Interface call mService.selectPreset(mDevice, 0x00); @@ -535,9 +545,10 @@ public class HapClientTest { */ @Test public void testGroupSelectActivePresetNative() { + InOrder order = inOrder(mContext); doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); - testConnectingDevice(mDevice3); + testConnectingDevice(order, mDevice3); int flags = 0x01; mNativeInterface.onFeaturesUpdate(getByteAddress(mDevice3), flags); @@ -561,9 +572,10 @@ public class HapClientTest { */ @Test public void testSwitchToNextPreset() { + InOrder order = inOrder(mContext); doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); - testConnectingDevice(mDevice); + testConnectingDevice(order, mDevice); // Verify Native Interface call mServiceBinder.switchToNextPreset(mDevice, mAttributionSource); @@ -576,9 +588,10 @@ public class HapClientTest { */ @Test public void testSwitchToNextPresetForGroup() { + InOrder order = inOrder(mContext); doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); - testConnectingDevice(mDevice3); + testConnectingDevice(order, mDevice3); int flags = 0x01; mNativeInterface.onFeaturesUpdate(getByteAddress(mDevice3), flags); @@ -592,9 +605,10 @@ public class HapClientTest { */ @Test public void testSwitchToPreviousPreset() { + InOrder order = inOrder(mContext); doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); - testConnectingDevice(mDevice); + testConnectingDevice(order, mDevice); // Verify Native Interface call mServiceBinder.switchToPreviousPreset(mDevice, mAttributionSource); @@ -607,10 +621,11 @@ public class HapClientTest { */ @Test public void testSwitchToPreviousPresetForGroup() { + InOrder order = inOrder(mContext); doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); - testConnectingDevice(mDevice); - testConnectingDevice(mDevice2); + testConnectingDevice(order, mDevice); + testConnectingDevice(order, mDevice2); int flags = 0x01; mNativeInterface.onFeaturesUpdate(getByteAddress(mDevice), flags); @@ -625,9 +640,10 @@ public class HapClientTest { */ @Test public void testGetActivePresetIndex() throws Exception { + InOrder order = inOrder(mContext); doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); - testConnectingDevice(mDevice); + testConnectingDevice(order, mDevice); testOnPresetSelected(mDevice, 0x01); // Verify cached value via binder @@ -644,9 +660,10 @@ public class HapClientTest { */ @Test public void testGetPresetInfoAndActivePresetInfo() throws Exception { + InOrder order = inOrder(mContext); doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); - testConnectingDevice(mDevice2); + testConnectingDevice(order, mDevice2); // Check when active preset is not known yet final SynchronousResultReceiver<List<BluetoothHapPresetInfo>> presetListRecv = @@ -686,9 +703,10 @@ public class HapClientTest { */ @Test public void testSetPresetNameNative() { + InOrder order = inOrder(mContext); doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); - testConnectingDevice(mDevice); + testConnectingDevice(order, mDevice); mServiceBinder.setPresetName(mDevice, 0x00, "ExamplePresetName", mAttributionSource); verify(mNativeInterface, times(0)) @@ -711,11 +729,12 @@ public class HapClientTest { */ @Test public void testSetPresetNameForGroup() { + InOrder order = inOrder(mContext); doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); int test_group = 0x02; for (BluetoothDevice device : mCsipService.getGroupDevicesOrdered(test_group)) { - testConnectingDevice(device); + testConnectingDevice(order, device); } int flags = 0x21; @@ -757,12 +776,14 @@ public class HapClientTest { .onDeviceAvailable(any(byte[].class), anyInt()); mNativeInterface.onDeviceAvailable(getByteAddress(mDevice), 0x03); - Intent intent = TestUtils.waitForIntent(TIMEOUT_MS, mIntentQueue.get(mDevice)); - Assert.assertNotNull(intent); - Assert.assertEquals(BluetoothHapClient.ACTION_HAP_DEVICE_AVAILABLE, intent.getAction()); - Assert.assertEquals(mDevice, intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)); - Assert.assertEquals(0x03, - intent.getIntExtra(BluetoothHapClient.EXTRA_HAP_FEATURES, 0x00)); + verify(mContext, timeout(TIMEOUT_MS)) + .sendBroadcast( + argThat( + allOf( + hasAction(ACTION_HAP_DEVICE_AVAILABLE), + hasExtra(BluetoothDevice.EXTRA_DEVICE, mDevice), + hasExtra(BluetoothHapClient.EXTRA_HAP_FEATURES, 0x03))), + any()); } /** @@ -817,11 +838,12 @@ public class HapClientTest { */ @Test public void testStackEventOnPresetInfo() { + InOrder order = inOrder(mContext); doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService) .getRemoteUuids(any(BluetoothDevice.class)); // Connect and inject initial presets - testConnectingDevice(mDevice); + testConnectingDevice(order, mDevice); int info_reason = HapClientStackEvent.PRESET_INFO_REASON_PRESET_INFO_UPDATE; BluetoothHapPresetInfo[] info = @@ -1047,7 +1069,7 @@ public class HapClientTest { // Add state machine for testing dump() mService.connect(mDevice); - TestUtils.waitForIntent(TIMEOUT_MS, mIntentQueue.get(mDevice)); + verify(mContext, timeout(TIMEOUT_MS)).sendBroadcast(any(), any()); mService.dump(new StringBuilder()); } @@ -1057,7 +1079,6 @@ public class HapClientTest { */ private void prepareConnectingDevice(BluetoothDevice device) { // Prepare intent queue and all the mocks - mIntentQueue.put(device, new LinkedBlockingQueue<>()); when(mNativeInterface.getDevice(getByteAddress(device))).thenReturn(device); when(mDatabaseManager .getProfileConnectionPolicy(device, BluetoothProfile.HAP_CLIENT)) @@ -1066,23 +1087,26 @@ public class HapClientTest { doReturn(true).when(mNativeInterface).disconnectHapClient(any(BluetoothDevice.class)); } - /** - * Helper function to test device connecting - */ - private void testConnectingDevice(BluetoothDevice device) { + /** Helper function to test device connecting */ + private void testConnectingDevice(InOrder order, BluetoothDevice device) { prepareConnectingDevice(device); // Send a connect request Assert.assertTrue("Connect expected to succeed", mService.connect(device)); - verifyConnectingDevice(device); + verifyConnectingDevice(order, device); } - /** - * Helper function to test device connecting - */ - private void verifyConnectingDevice(BluetoothDevice device) { + /** Helper function to test device connecting */ + private void verifyConnectingDevice(InOrder order, BluetoothDevice device) { // Verify the connection state broadcast, and that we are in Connecting state - verifyConnectionStateIntent(TIMEOUT_MS, device, BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_DISCONNECTED); + order.verify(mContext, timeout(TIMEOUT_MS)) + .sendBroadcast( + argThat( + allOf( + hasAction(ACTION_HAP_CONNECTION_STATE_CHANGED), + hasExtra(BluetoothDevice.EXTRA_DEVICE, device), + hasExtra(EXTRA_STATE, STATE_CONNECTING), + hasExtra(EXTRA_PREVIOUS_STATE, STATE_DISCONNECTED))), + any()); Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, mService.getConnectionState(device)); // Send a message to trigger connection completed @@ -1093,8 +1117,15 @@ public class HapClientTest { mService.messageFromNative(evt); // Verify the connection state broadcast, and that we are in Connected state - verifyConnectionStateIntent(TIMEOUT_MS, device, BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_CONNECTING); + order.verify(mContext, timeout(TIMEOUT_MS)) + .sendBroadcast( + argThat( + allOf( + hasAction(ACTION_HAP_CONNECTION_STATE_CHANGED), + hasExtra(BluetoothDevice.EXTRA_DEVICE, device), + hasExtra(EXTRA_STATE, STATE_CONNECTED), + hasExtra(EXTRA_PREVIOUS_STATE, STATE_CONNECTING))), + any()); Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, mService.getConnectionState(device)); evt = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_DEVICE_AVAILABLE); @@ -1102,12 +1133,14 @@ public class HapClientTest { evt.valueInt1 = 0x01; // features mService.messageFromNative(evt); - Intent intent = TestUtils.waitForIntent(TIMEOUT_MS, mIntentQueue.get(device)); - Assert.assertNotNull(intent); - Assert.assertEquals(BluetoothHapClient.ACTION_HAP_DEVICE_AVAILABLE, intent.getAction()); - Assert.assertEquals(device, intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)); - Assert.assertEquals(evt.valueInt1, - intent.getIntExtra(BluetoothHapClient.EXTRA_HAP_FEATURES, -1)); + order.verify(mContext, timeout(TIMEOUT_MS)) + .sendBroadcast( + argThat( + allOf( + hasAction(ACTION_HAP_DEVICE_AVAILABLE), + hasExtra(BluetoothDevice.EXTRA_DEVICE, device), + hasExtra(BluetoothHapClient.EXTRA_HAP_FEATURES, 0x01))), + any()); evt = new HapClientStackEvent(HapClientStackEvent.EVENT_TYPE_DEVICE_FEATURES); evt.device = device; @@ -1149,21 +1182,6 @@ public class HapClientTest { } /** - * Helper function to test ConnectionStateIntent() method - */ - private void verifyConnectionStateIntent(int timeoutMs, BluetoothDevice device, - int newState, int prevState) { - Intent intent = TestUtils.waitForIntent(timeoutMs, mIntentQueue.get(device)); - Assert.assertNotNull(intent); - Assert.assertEquals(BluetoothHapClient.ACTION_HAP_CONNECTION_STATE_CHANGED, - intent.getAction()); - Assert.assertEquals(device, intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)); - Assert.assertEquals(newState, intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1)); - Assert.assertEquals(prevState, intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, - -1)); - } - - /** * Helper function to test okToConnect() method */ private void testOkToConnectCase(BluetoothDevice device, int bondState, int policy, @@ -1183,20 +1201,4 @@ public class HapClientTest { } return Utils.getBytesFromAddress(device.getAddress()); } - - private class HasIntentReceiver extends BroadcastReceiver { - @Override - public void onReceive(Context context, Intent intent) { - try { - BluetoothDevice device = intent.getParcelableExtra( - BluetoothDevice.EXTRA_DEVICE); - Assert.assertNotNull(device); - LinkedBlockingQueue<Intent> queue = mIntentQueue.get(device); - Assert.assertNotNull(queue); - queue.put(intent); - } catch (InterruptedException e) { - Assert.fail("Cannot add Intent to the queue: " + e.getMessage()); - } - } - } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidServiceTest.java index 4eaf759fd2..51c1450f70 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidServiceTest.java @@ -153,11 +153,12 @@ public class HearingAidServiceTest { private void startService() throws TimeoutException { mService = new HearingAidService(mContext); - mService.doStart(); + mService.start(); + mService.setAvailable(true); } private void stopService() throws TimeoutException { - mService.doStop(); + mService.stop(); mService = HearingAidService.getHearingAidService(); assertThat(mService).isNull(); } 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 3eaa5cfa52..86d5bacd70 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 @@ -220,7 +220,8 @@ public class HeadsetServiceAndStateMachineTest { mOriginalVrTimeoutMs = HeadsetService.sStartVrTimeoutMs; HeadsetService.sStartVrTimeoutMs = START_VR_TIMEOUT_MILLIS; mHeadsetService = new HeadsetService(mTargetContext); - mHeadsetService.doStart(); + mHeadsetService.start(); + mHeadsetService.setAvailable(true); mIsHeadsetServiceStarted = true; Assert.assertNotNull(mHeadsetService); verify(mObjectsFactory).makeSystemInterface(mHeadsetService); @@ -247,7 +248,7 @@ public class HeadsetServiceAndStateMachineTest { if (mIsHeadsetServiceStarted) { mTargetContext.unregisterReceiver(mHeadsetIntentReceiver); - mHeadsetService.doStop(); + mHeadsetService.stop(); mHeadsetService = HeadsetService.getHeadsetService(); Assert.assertNull(mHeadsetService); // Clear classes that is spied on and has static life time 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 fd4d22f3c0..2aa1e1ff0d 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 @@ -19,7 +19,6 @@ package com.android.bluetooth.hfp; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyBoolean; import static org.mockito.Mockito.anyInt; -import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; @@ -159,7 +158,8 @@ public class HeadsetServiceTest { doReturn(mNativeInterface).when(mObjectsFactory).getNativeInterface(); HeadsetNativeInterface.setInstance(mNativeInterface); mHeadsetService = new HeadsetService(mTargetContext); - mHeadsetService.doStart(); + mHeadsetService.start(); + mHeadsetService.setAvailable(true); verify(mObjectsFactory).makeSystemInterface(mHeadsetService); verify(mObjectsFactory).getNativeInterface(); mHeadsetService.setForceScoAudio(true); @@ -167,7 +167,7 @@ public class HeadsetServiceTest { @After public void tearDown() throws Exception { - mHeadsetService.doStop(); + mHeadsetService.stop(); HeadsetNativeInterface.setInstance(null); mHeadsetService = HeadsetService.getHeadsetService(); Assert.assertNull(mHeadsetService); diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceTest.java index 92923b6798..a6288f647f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceTest.java @@ -20,7 +20,6 @@ import static android.content.pm.PackageManager.FEATURE_WATCH; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyInt; -import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.never; @@ -176,11 +175,11 @@ public class HeadsetClientServiceTest { doReturn(packageManager).when(context).getPackageManager(); HeadsetClientService service = new HeadsetClientService(context); - service.doStart(); + service.start(); verify(context).startService(any(Intent.class)); - service.doStop(); + service.stop(); } @Test @@ -192,17 +191,18 @@ public class HeadsetClientServiceTest { doReturn(packageManager).when(context).getPackageManager(); HeadsetClientService service = new HeadsetClientService(context); - service.doStart(); + service.start(); verify(context, never()).startService(any(Intent.class)); - service.doStop(); + service.stop(); } private void startService() throws Exception { // At this point the service should have started so check NOT null mService = new HeadsetClientService(mTargetContext); - mService.doStart(); + mService.start(); + mService.setAvailable(true); // Try getting the Bluetooth adapter mAdapter = BluetoothAdapter.getDefaultAdapter(); Assert.assertNotNull(mAdapter); @@ -211,7 +211,7 @@ public class HeadsetClientServiceTest { private void stopServiceIfStarted() throws Exception { if (mIsHeadsetClientServiceStarted) { - mService.doStop(); + mService.stop(); mService = HeadsetClientService.getHeadsetClientService(); Assert.assertNull(mService); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hid/HidDeviceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hid/HidDeviceTest.java index fe59fd6df9..db4a62ee35 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hid/HidDeviceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hid/HidDeviceTest.java @@ -111,7 +111,8 @@ public class HidDeviceTest { mTestDevice = mAdapter.getRemoteDevice("10:11:12:13:14:15"); mHidDeviceService = new HidDeviceService(mTargetContext); - mHidDeviceService.doStart(); + mHidDeviceService.start(); + mHidDeviceService.setAvailable(true); // Force unregister app first mHidDeviceService.unregisterApp(); @@ -137,7 +138,7 @@ public class HidDeviceTest { @After public void tearDown() throws Exception { - mHidDeviceService.doStop(); + mHidDeviceService.stop(); mHidDeviceService = HidDeviceService.getHidDeviceService(); Assert.assertNull(mHidDeviceService); mTargetContext.unregisterReceiver(mConnectionStateChangedReceiver); 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 f90f867d5b..8bedfb3e2a 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 @@ -17,17 +17,16 @@ package com.android.bluetooth.hid; import static org.mockito.Mockito.verify; - +import android.platform.test.flag.junit.SetFlagsRule; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; - import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; - +import com.android.bluetooth.flags.Flags; import com.android.bluetooth.x.com.android.modules.utils.SynchronousResultReceiver; - import org.junit.Before; +import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; @@ -36,7 +35,7 @@ import org.mockito.MockitoAnnotations; @SmallTest @RunWith(AndroidJUnit4.class) public class HidHostServiceBinderTest { - + @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule(); private static final String REMOTE_DEVICE_ADDRESS = "00:00:00:00:00:00"; @Mock @@ -107,6 +106,24 @@ public class HidHostServiceBinderTest { } @Test + public void setPreferredTransport_callsServiceMethod() { + mSetFlagsRule.enableFlags(Flags.FLAG_ALLOW_SWITCHING_HID_AND_HOGP); + int preferredTransport = BluetoothDevice.TRANSPORT_AUTO; + mBinder.setPreferredTransport( + mRemoteDevice, preferredTransport, null, SynchronousResultReceiver.get()); + + verify(mService).setPreferredTransport(mRemoteDevice, preferredTransport); + } + + @Test + public void getPreferredTransport_callsServiceMethod() { + mSetFlagsRule.enableFlags(Flags.FLAG_ALLOW_SWITCHING_HID_AND_HOGP); + mBinder.getPreferredTransport(mRemoteDevice, null, SynchronousResultReceiver.get()); + + verify(mService).getPreferredTransport(mRemoteDevice); + } + + @Test public void getProtocolMode_callsServiceMethod() { mBinder.getProtocolMode(mRemoteDevice, null, SynchronousResultReceiver.get()); diff --git a/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceTest.java index d92f70d8f5..41652ab673 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceTest.java @@ -58,7 +58,8 @@ public class HidHostServiceTest { when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager); HidHostNativeInterface.setInstance(mNativeInterface); mService = new HidHostService(mTargetContext); - mService.doStart(); + mService.start(); + mService.setAvailable(true); // Try getting the Bluetooth adapter mAdapter = BluetoothAdapter.getDefaultAdapter(); Assert.assertNotNull(mAdapter); @@ -69,7 +70,8 @@ public class HidHostServiceTest { @After public void tearDown() throws Exception { - mService.doStop(); + mService.stop(); + mService.cleanup(); HidHostNativeInterface.setInstance(null); mService = HidHostService.getHidHostService(); Assert.assertNull(mService); 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 660d1c571c..4c6d909339 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 @@ -90,7 +90,7 @@ public class LeAudioBinderTest { InstrumentationRegistry.getTargetContext(), mNativeInterface, mFakeFlagsImpl)); - mLeAudioService.doStart(); + mLeAudioService.start(); mAdapter = BluetoothAdapter.getDefaultAdapter(); mBinder = new LeAudioService.BluetoothLeAudioBinder(mLeAudioService); mLeAudioService.mLeAudioCallbacks = mLeAudioCallbacks; @@ -100,7 +100,7 @@ public class LeAudioBinderTest { @After public void cleanUp() { mBinder.cleanup(); - mLeAudioService.doStop(); + mLeAudioService.stop(); TestUtils.clearAdapterService(mAdapterService); } 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 3568a9302f..33894b8500 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 @@ -226,11 +226,12 @@ public class LeAudioBroadcastServiceTest { private void startService() throws TimeoutException { mService = new LeAudioService(mTargetContext); - mService.doStart(); + mService.start(); + mService.setAvailable(true); } private void stopService() throws TimeoutException { - mService.doStop(); + mService.stop(); mService = LeAudioService.getLeAudioService(); Assert.assertNull(mService); } 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 e5cae8315d..7ad652060c 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 @@ -198,6 +198,7 @@ public class LeAudioServiceTest { mFakeFlagsImpl.setFlag(Flags.FLAG_LEAUDIO_UNICAST_INACTIVATE_DEVICE_BASED_ON_CONTEXT, false); mFakeFlagsImpl.setFlag(Flags.FLAG_AUDIO_ROUTING_CENTRALIZATION, false); mFakeFlagsImpl.setFlag(Flags.FLAG_LEAUDIO_BROADCAST_AUDIO_HANDOVER_POLICIES, false); + mFakeFlagsImpl.setFlag(Flags.FLAG_LEAUDIO_MCS_TBS_AUTHORIZATION_REBOND_FIX, false); mService.setFeatureFlags(mFakeFlagsImpl); mService.mAudioManager = mAudioManager; @@ -274,13 +275,14 @@ public class LeAudioServiceTest { // LeAudioService#init and expect it to be run after start // has finished. // To ensure that we run start on the main looper as well. - FutureTask task = new FutureTask(mService::doStart, null); + mService.setAvailable(true); + FutureTask task = new FutureTask(mService::start, null); new Handler(Looper.getMainLooper()).post(task); task.get(); } private void stopService() throws TimeoutException { - mService.doStop(); + mService.stop(); mService = LeAudioService.getLeAudioService(); assertThat(mService).isNull(); } @@ -804,6 +806,138 @@ public class LeAudioServiceTest { assertThat(mService.getDevices().contains(mLeftDevice)).isFalse(); } + /** Test that authorization info is removed from TBS and MCS after the device is unbond. */ + @Test + public void testAuthorizationInfoRemovedFromTbsMcsOnUnbondEvents() { + mFakeFlagsImpl.setFlag(Flags.FLAG_AUDIO_ROUTING_CENTRALIZATION, true); + mFakeFlagsImpl.setFlag(Flags.FLAG_LEAUDIO_MCS_TBS_AUTHORIZATION_REBOND_FIX, true); + + // Update the device priority so okToConnect() returns true + when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + when(mDatabaseManager.getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO)) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) + .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + doReturn(true).when(mNativeInterface).connectLeAudio(any(BluetoothDevice.class)); + doReturn(true).when(mNativeInterface).disconnectLeAudio(any(BluetoothDevice.class)); + + // Create device descriptor with connect request + assertWithMessage("Connect failed").that(mService.connect(mLeftDevice)).isTrue(); + + // Unbond received in CONNECTION_STATE_CONNECTING state + generateConnectionMessageFromNative( + mLeftDevice, + BluetoothProfile.STATE_CONNECTING, + BluetoothProfile.STATE_DISCONNECTED); + assertThat(mService.getConnectionState(mLeftDevice)) + .isEqualTo(BluetoothProfile.STATE_CONNECTING); + assertThat(mService.getDevices().contains(mLeftDevice)).isTrue(); + + // Device unbond + doReturn(BluetoothDevice.BOND_NONE) + .when(mAdapterService) + .getBondState(any(BluetoothDevice.class)); + mService.bondStateChanged(mLeftDevice, BluetoothDevice.BOND_NONE); + + verifyConnectionStateIntent( + TIMEOUT_MS, + mLeftDevice, + BluetoothProfile.STATE_DISCONNECTED, + BluetoothProfile.STATE_CONNECTING); + verify(mTbsService, times(1)).removeDeviceAuthorizationInfo(mLeftDevice); + verify(mMcpService, times(1)).removeDeviceAuthorizationInfo(mLeftDevice); + + reset(mTbsService); + reset(mMcpService); + + assertThat(mService.getDevices().contains(mLeftDevice)).isFalse(); + + // Unbond received in CONNECTION_STATE_CONNECTED + // Create device descriptor with connect request. To connect service, + // device needs to be bonded + doReturn(BluetoothDevice.BOND_BONDED) + .when(mAdapterService) + .getBondState(any(BluetoothDevice.class)); + assertWithMessage("Connect failed").that(mService.connect(mLeftDevice)).isTrue(); + + generateConnectionMessageFromNative( + mLeftDevice, + BluetoothProfile.STATE_CONNECTING, + BluetoothProfile.STATE_DISCONNECTED); + generateConnectionMessageFromNative( + mLeftDevice, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING); + assertThat(mService.getConnectionState(mLeftDevice)) + .isEqualTo(BluetoothProfile.STATE_CONNECTED); + + assertThat(mService.getDevices().contains(mLeftDevice)).isTrue(); + + // Device unbond + doReturn(BluetoothDevice.BOND_NONE) + .when(mAdapterService) + .getBondState(any(BluetoothDevice.class)); + mService.bondStateChanged(mLeftDevice, BluetoothDevice.BOND_NONE); + + assertThat(mService.getDevices().contains(mLeftDevice)).isTrue(); + verifyConnectionStateIntent( + TIMEOUT_MS, + mLeftDevice, + BluetoothProfile.STATE_DISCONNECTING, + BluetoothProfile.STATE_CONNECTED); + assertThat(mService.getConnectionState(mLeftDevice)) + .isEqualTo(BluetoothProfile.STATE_DISCONNECTING); + assertThat(mService.getDevices().contains(mLeftDevice)).isTrue(); + verify(mTbsService, times(0)).removeDeviceAuthorizationInfo(mLeftDevice); + verify(mMcpService, times(0)).removeDeviceAuthorizationInfo(mLeftDevice); + + reset(mTbsService); + reset(mMcpService); + + // Inject CONNECTION_STATE_DISCONNECTED + generateConnectionMessageFromNative( + mLeftDevice, + BluetoothProfile.STATE_DISCONNECTED, + BluetoothProfile.STATE_DISCONNECTING); + + verify(mTbsService, times(1)).removeDeviceAuthorizationInfo(mLeftDevice); + verify(mMcpService, times(1)).removeDeviceAuthorizationInfo(mLeftDevice); + + reset(mTbsService); + reset(mMcpService); + + // Unbond received in CONNECTION_STATE_DISCONNECTED + // Create device descriptor with connect request. To connect service, + // device needs to be bonded + doReturn(BluetoothDevice.BOND_BONDED) + .when(mAdapterService) + .getBondState(any(BluetoothDevice.class)); + assertWithMessage("Connect failed").that(mService.connect(mLeftDevice)).isTrue(); + + generateConnectionMessageFromNative( + mLeftDevice, + BluetoothProfile.STATE_CONNECTING, + BluetoothProfile.STATE_DISCONNECTED); + generateConnectionMessageFromNative( + mLeftDevice, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING); + assertThat(mService.getConnectionState(mLeftDevice)) + .isEqualTo(BluetoothProfile.STATE_CONNECTED); + + injectAndVerifyDeviceDisconnected(mLeftDevice); + assertThat(mService.getDevices().contains(mLeftDevice)).isTrue(); + + verify(mTbsService, times(0)).removeDeviceAuthorizationInfo(mLeftDevice); + verify(mMcpService, times(0)).removeDeviceAuthorizationInfo(mLeftDevice); + + reset(mTbsService); + reset(mMcpService); + + // Device unbond + mService.bondStateChanged(mLeftDevice, BluetoothDevice.BOND_NONE); + + verify(mTbsService, times(1)).removeDeviceAuthorizationInfo(mLeftDevice); + verify(mMcpService, times(1)).removeDeviceAuthorizationInfo(mLeftDevice); + } + /** * Test that a CONNECTION_STATE_DISCONNECTED Le Audio stack event will remove the state * machine only if the device is unbond. 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 8aa4c0c6f8..5989177b80 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 @@ -23,7 +23,6 @@ import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyInt; -import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.spy; @@ -74,7 +73,8 @@ public class BluetoothMapServiceTest { TestUtils.setAdapterService(mAdapterService); doReturn(mDatabaseManager).when(mAdapterService).getDatabase(); mService = new BluetoothMapService(targetContext); - mService.doStart(); + mService.start(); + mService.setAvailable(true); // Try getting the Bluetooth adapter mAdapter = BluetoothAdapter.getDefaultAdapter(); assertThat(mAdapter).isNotNull(); @@ -83,7 +83,7 @@ public class BluetoothMapServiceTest { @After public void tearDown() throws Exception { - mService.doStop(); + mService.stop(); mService = BluetoothMapService.getBluetoothMapService(); assertThat(mService).isNull(); TestUtils.clearAdapterService(mAdapterService); 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 82168adfb2..5c735c9d45 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 @@ -462,6 +462,20 @@ public class MapClientContentTest { MapClientContent.clearAllContent(mMockContext); } + /** + * Test verifying dumpsys does not cause Bluetooth to crash (esp since we're querying the + * database to generate dump). + */ + @Test + public void testDumpsysDoesNotCauseCrash() { + testStoreOneSMSOneMMS(); + // mMapClientContent is set in testStoreOneSMSOneMMS + StringBuilder sb = new StringBuilder("Hello world!\n"); + mMapClientContent.dump(sb); + + assertThat(sb.toString()).isNotNull(); + } + void createTestMessages() { mOriginator = new VCardEntry(); VCardProperty property = new VCardProperty(); 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 1fe5d6040b..0622a7eba3 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 @@ -74,7 +74,8 @@ public class MapClientServiceTest { MnsService mnsServer = null; mService = new MapClientService(targetContext, mTestLooper.getLooper(), mnsServer); - mService.doStart(); + mService.start(); + mService.setAvailable(true); // Try getting the Bluetooth adapter mAdapter = BluetoothAdapter.getDefaultAdapter(); @@ -84,7 +85,8 @@ public class MapClientServiceTest { @After public void tearDown() throws Exception { - mService.doStop(); + mService.stop(); + mService.cleanup(); mService = MapClientService.getMapClientService(); assertThat(mService).isNull(); TestUtils.clearAdapterService(mAdapterService); diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientTest.java index aef59c7e46..ab5f97b95d 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientTest.java @@ -71,14 +71,16 @@ public class MapClientTest { mIsMapClientServiceStarted = true; Looper looper = null; mService = new MapClientService(mTargetContext, looper, mMockMnsService); - mService.doStart(); + mService.start(); + mService.setAvailable(true); mAdapter = BluetoothAdapter.getDefaultAdapter(); } @After public void tearDown() throws Exception { if (mIsMapClientServiceStarted) { - mService.doStop(); + mService.stop(); + mService.cleanup(); mService = MapClientService.getMapClientService(); Assert.assertNull(mService); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MessagesFilterTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MessagesFilterTest.java index 9c6a30756b..3ba4decf8f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MessagesFilterTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MessagesFilterTest.java @@ -21,6 +21,8 @@ import static com.google.common.truth.Truth.assertThat; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; +import java.util.Calendar; + import org.junit.Test; import org.junit.runner.RunWith; @@ -78,4 +80,35 @@ public class MessagesFilterTest { assertThat(filter.recipient).isEqualTo(null); } + /** Test Builder creates and sets everything correctly. */ + @Test + public void testBuilder() { + String originator = "test_originator"; + String recipient = "test_recipient"; + byte messageType = MessagesFilter.MESSAGE_TYPE_EMAIL; + byte readStatus = MessagesFilter.READ_STATUS_READ; + byte priority = MessagesFilter.PRIORITY_HIGH; + Calendar begin = Calendar.getInstance(); + begin.add(Calendar.DATE, -14); + Calendar end = Calendar.getInstance(); + end.add(Calendar.DATE, -7); + + MessagesFilter filter = + new MessagesFilter.Builder() + .setOriginator(originator) + .setRecipient(recipient) + .setMessageType(messageType) + .setReadStatus(readStatus) + .setPriority(priority) + .setPeriod(begin.getTime(), end.getTime()) + .build(); + + assertThat(filter.originator).isEqualTo(originator); + assertThat(filter.recipient).isEqualTo(recipient); + assertThat(filter.messageType).isEqualTo(messageType); + assertThat(filter.readStatus).isEqualTo(readStatus); + assertThat(filter.priority).isEqualTo(priority); + assertThat(filter.periodBegin).isEqualTo((new ObexTime(begin.getTime())).toString()); + assertThat(filter.periodEnd).isEqualTo((new ObexTime(end.getTime())).toString()); + } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/mcp/McpServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/mcp/McpServiceTest.java index 3d72e0b24e..5c77c88ba5 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mcp/McpServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mcp/McpServiceTest.java @@ -67,7 +67,8 @@ public class McpServiceTest { McpService.setMediaControlProfileForTesting(mMediaControlProfile); mMcpService = new McpService(mTargetContext); - mMcpService.doStart(); + mMcpService.start(); + mMcpService.setAvailable(true); } @After @@ -76,7 +77,7 @@ public class McpServiceTest { return; } - mMcpService.doStop(); + mMcpService.stop(); mMcpService = McpService.getMcpService(); Assert.assertNull(mMcpService); reset(mMediaControlProfile); diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiverTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiverTest.java index e081642487..c01b3ba9a1 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiverTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiverTest.java @@ -43,6 +43,9 @@ import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.platform.test.annotations.RequiresFlagsDisabled; +import android.platform.test.annotations.RequiresFlagsEnabled; +import android.platform.test.flag.junit.CheckFlagsRule; +import android.platform.test.flag.junit.DeviceFlagsValueProvider; import androidx.test.core.app.ActivityScenario; import androidx.test.espresso.intent.Intents; @@ -56,9 +59,9 @@ import com.android.bluetooth.flags.Flags; import com.google.common.base.Objects; import org.junit.After; -import org.junit.Assume; 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; @@ -69,6 +72,10 @@ import java.util.List; @RunWith(AndroidJUnit4.class) public class BluetoothOppReceiverTest { + + @Rule + public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule(); + Context mContext; @Mock @@ -124,8 +131,6 @@ public class BluetoothOppReceiverTest { @Test @RequiresFlagsDisabled(Flags.FLAG_OPP_START_ACTIVITY_DIRECTLY_FROM_NOTIFICATION) public void onReceive_withActionIncomingFileConfirm_startsIncomingFileConfirmActivity() { - Assume.assumeFalse(Flags.oppStartActivityDirectlyFromNotification()); - Intent intent = new Intent(); intent.setAction(Constants.ACTION_INCOMING_FILE_CONFIRM); intent.setData(Uri.parse("content:///not/important")); @@ -160,8 +165,6 @@ public class BluetoothOppReceiverTest { @Test @RequiresFlagsDisabled(Flags.FLAG_OPP_START_ACTIVITY_DIRECTLY_FROM_NOTIFICATION) public void onReceive_withActionOutboundTransfer_startsTransferHistoryActivity() { - Assume.assumeFalse(Flags.oppStartActivityDirectlyFromNotification()); - Intent intent = new Intent(); intent.setAction(Constants.ACTION_OPEN_OUTBOUND_TRANSFER); intent.setData(Uri.parse("content:///not/important")); @@ -176,8 +179,6 @@ public class BluetoothOppReceiverTest { @Test @RequiresFlagsDisabled(Flags.FLAG_OPP_START_ACTIVITY_DIRECTLY_FROM_NOTIFICATION) public void onReceive_withActionInboundTransfer_startsTransferHistoryActivity() { - Assume.assumeFalse(Flags.oppStartActivityDirectlyFromNotification()); - Intent intent = new Intent(); intent.setAction(Constants.ACTION_OPEN_INBOUND_TRANSFER); intent.setData(Uri.parse("content:///not/important")); @@ -215,7 +216,8 @@ public class BluetoothOppReceiverTest { } @Test - public void onReceive_withActionCompleteHide_contentUpdate() { + @RequiresFlagsDisabled(Flags.FLAG_OPP_FIX_MULTIPLE_NOTIFICATIONS_ISSUES) + public void onReceive_withActionCompleteHide_makeAllVisibilityHidden() { Intent intent = new Intent(); intent.setAction(Constants.ACTION_COMPLETE_HIDE); mReceiver.onReceive(mContext, intent); @@ -225,6 +227,44 @@ public class BluetoothOppReceiverTest { } @Test + @RequiresFlagsEnabled(Flags.FLAG_OPP_FIX_MULTIPLE_NOTIFICATIONS_ISSUES) + public void onReceive_withActionHideCompletedInboundTransfer_makesInboundVisibilityHidden() { + Intent intent = new Intent(); + intent.setAction(Constants.ACTION_HIDE_COMPLETED_INBOUND_TRANSFER); + mReceiver.onReceive(mContext, intent); + verify(mBluetoothMethodProxy) + .contentResolverUpdate( + any(), + eq(BluetoothShare.CONTENT_URI), + argThat( + arg -> + Objects.equal( + BluetoothShare.VISIBILITY_HIDDEN, + arg.get(BluetoothShare.VISIBILITY))), + eq(BluetoothOppNotification.WHERE_COMPLETED_INBOUND), + any()); + } + + @Test + @RequiresFlagsEnabled(Flags.FLAG_OPP_FIX_MULTIPLE_NOTIFICATIONS_ISSUES) + public void onReceive_withActionHideCompletedOutboundTransfer_makesOutboundVisibilityHidden() { + Intent intent = new Intent(); + intent.setAction(Constants.ACTION_HIDE_COMPLETED_OUTBOUND_TRANSFER); + mReceiver.onReceive(mContext, intent); + verify(mBluetoothMethodProxy) + .contentResolverUpdate( + any(), + eq(BluetoothShare.CONTENT_URI), + argThat( + arg -> + Objects.equal( + BluetoothShare.VISIBILITY_HIDDEN, + arg.get(BluetoothShare.VISIBILITY))), + eq(BluetoothOppNotification.WHERE_COMPLETED_OUTBOUND), + any()); + } + + @Test public void onReceive_withActionTransferCompletedAndHandoverInitiated_contextSendBroadcast() { List<BluetoothOppTestUtils.CursorMockData> cursorMockDataList; Cursor cursor = mock(Cursor.class); diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppServiceTest.java index cead686129..05b0460834 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppServiceTest.java @@ -80,7 +80,8 @@ public class BluetoothOppServiceTest { TestUtils.setAdapterService(mAdapterService); mIsAdapterServiceSet = true; mService = new BluetoothOppService(targetContext); - mService.doStart(); + mService.start(); + mService.setAvailable(true); mIsBluetoothOppServiceStarted = true; // Try getting the Bluetooth adapter @@ -112,7 +113,7 @@ public class BluetoothOppServiceTest { BluetoothMethodProxy.setInstanceForTesting(null); if (mIsBluetoothOppServiceStarted) { - mService.doStop(); + mService.stop(); } if (mIsAdapterServiceSet) { TestUtils.clearAdapterService(mAdapterService); 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 729875aaef..e08f5207d9 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 @@ -21,7 +21,6 @@ import static android.net.TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL; import static com.google.common.truth.Truth.assertThat; -import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; @@ -72,7 +71,8 @@ public class PanServiceTest { doReturn(mDatabaseManager).when(mAdapterService).getDatabase(); PanNativeInterface.setInstance(mNativeInterface); mService = new PanService(targetContext); - mService.doStart(); + mService.start(); + mService.setAvailable(true); // Try getting the Bluetooth adapter mAdapter = BluetoothAdapter.getDefaultAdapter(); @@ -83,7 +83,8 @@ public class PanServiceTest { @After public void tearDown() throws Exception { - mService.doStop(); + mService.stop(); + mService.cleanup(); PanNativeInterface.setInstance(null); mService = PanService.getPanService(); assertThat(mService).isNull(); 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 48db9a7b99..69dac461ad 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 @@ -19,7 +19,6 @@ import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; @@ -82,7 +81,8 @@ public class BluetoothPbapServiceTest { mIsAdapterServiceSet = true; doReturn(mDatabaseManager).when(mAdapterService).getDatabase(); mService = new BluetoothPbapService(targetContext); - mService.doStart(); + mService.start(); + mService.setAvailable(true); mIsBluetoothPabpServiceStarted = true; // Try getting the Bluetooth adapter mAdapter = BluetoothAdapter.getDefaultAdapter(); @@ -98,7 +98,7 @@ public class BluetoothPbapServiceTest { return; } if (mIsBluetoothPabpServiceStarted) { - mService.doStop(); + mService.stop(); mService = BluetoothPbapService.getBluetoothPbapService(); assertThat(mService).isNull(); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandlerTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandlerTest.java index 832efadd28..50f96db865 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandlerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandlerTest.java @@ -18,7 +18,6 @@ package com.android.bluetooth.pbapclient; import static com.google.common.truth.Truth.assertThat; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -82,7 +81,7 @@ public class PbapClientConnectionHandlerTest { TestUtils.setAdapterService(mAdapterService); doReturn(mDatabaseManager).when(mAdapterService).getDatabase(); mService = new PbapClientService(mTargetContext); - mService.doStart(); + mService.start(); mAdapter = BluetoothAdapter.getDefaultAdapter(); @@ -102,7 +101,7 @@ public class PbapClientConnectionHandlerTest { @After public void tearDown() throws Exception { - mService.doStop(); + mService.stop(); mService = PbapClientService.getPbapClientService(); assertThat(mService).isNull(); TestUtils.clearAdapterService(mAdapterService); 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 1fae91169a..06e63c9519 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 @@ -19,7 +19,6 @@ import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.any; -import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; @@ -79,7 +78,8 @@ public class PbapClientServiceTest { mIsAdapterServiceSet = true; doReturn(mDatabaseManager).when(mAdapterService).getDatabase(); mService = new PbapClientService(mTargetContext); - mService.doStart(); + mService.start(); + mService.setAvailable(true); mIsPbapClientServiceStarted = true; // Try getting the Bluetooth adapter mAdapter = BluetoothAdapter.getDefaultAdapter(); @@ -93,7 +93,7 @@ public class PbapClientServiceTest { return; } if (mIsPbapClientServiceStarted) { - mService.doStop(); + mService.stop(); mService = PbapClientService.getPbapClientService(); Assert.assertNull(mService); } 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 d1f641abd3..27cb3a96dc 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 @@ -61,7 +61,8 @@ public class SapServiceTest { MockitoAnnotations.initMocks(this); TestUtils.setAdapterService(mAdapterService); mService = new SapService(mTargetContext); - mService.doStart(); + mService.start(); + mService.setAvailable(true); // Try getting the Bluetooth adapter mAdapter = BluetoothAdapter.getDefaultAdapter(); assertThat(mAdapter).isNotNull(); @@ -70,7 +71,7 @@ public class SapServiceTest { @After public void tearDown() throws Exception { - mService.doStop(); + mService.stop(); mService = SapService.getSapService(); assertThat(mService).isNull(); TestUtils.clearAdapterService(mAdapterService); diff --git a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlServiceTest.java index 1832cd6f41..f8ba79c75c 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlServiceTest.java @@ -129,7 +129,8 @@ public class VolumeControlServiceTest { VolumeControlNativeInterface.setInstance(mNativeInterface); mService = new VolumeControlService(mTargetContext, mFakeFlagsImpl); - mService.doStart(); + mService.start(); + mService.setAvailable(true); mService.mAudioManager = mAudioManager; mService.mFactory = mServiceFactory; @@ -168,7 +169,7 @@ public class VolumeControlServiceTest { return; } - mService.doStop(); + mService.stop(); VolumeControlNativeInterface.setInstance(null); mTargetContext.unregisterReceiver(mVolumeControlIntentReceiver); mDeviceQueueMap.clear(); diff --git a/android/pandora/server/src/Opp.kt b/android/pandora/server/src/Opp.kt index 8ebb96d463..6b077a2766 100644 --- a/android/pandora/server/src/Opp.kt +++ b/android/pandora/server/src/Opp.kt @@ -119,6 +119,11 @@ class Opp(val context: Context) : OppImplBase(), Closeable { uiDevice .wait(Until.findObject(By.text(INCOMING_FILE_TITLE)), INCOMING_FILE_WAIT_TIMEOUT) .click() + uiDevice.wait( + Until.hasObject(By.text(INCOMING_FILE_ACCEPT_BTN)), + INCOMING_FILE_WAIT_TIMEOUT + ) + uiDevice.waitForIdle() uiDevice .wait(Until.findObject(By.text(INCOMING_FILE_ACCEPT_BTN)), INCOMING_FILE_WAIT_TIMEOUT) .click() @@ -127,6 +127,7 @@ REQUIRED_APT_PACKAGES = [ 'liblz4-tool', 'libncurses5', 'libnss3-dev', + 'libfmt-dev', 'libprotobuf-dev', 'libre2-9', 'libre2-dev', diff --git a/flags/Android.bp b/flags/Android.bp index 61e62bb902..6fe1b7cd08 100644 --- a/flags/Android.bp +++ b/flags/Android.bp @@ -6,6 +6,7 @@ package { aconfig_declarations { name: "bluetooth_aconfig_flags", package: "com.android.bluetooth.flags", + container: "com.android.btservices", srcs: [ "**/*.aconfig", ], @@ -18,6 +19,7 @@ java_aconfig_library { "//cts/tests/tests/bluetooth:__subpackages__", "//packages/modules/Bluetooth/android/app", "//packages/modules/Bluetooth/framework", + "//packages/modules/Bluetooth/framework/tests/bumble", "//packages/modules/Bluetooth/framework/tests/util", "//packages/modules/Bluetooth/service:__subpackages__", ], diff --git a/flags/a2dp.aconfig b/flags/a2dp.aconfig index 456a2632c2..0e3db857db 100644 --- a/flags/a2dp.aconfig +++ b/flags/a2dp.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "a2dp_offload_codec_extensibility" diff --git a/flags/asha.aconfig b/flags/asha.aconfig index 368a237002..e20012c05b 100644 --- a/flags/asha.aconfig +++ b/flags/asha.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "higher_l2cap_flush_threshold" diff --git a/flags/audio_routing.aconfig b/flags/audio_routing.aconfig index e46c83b0cc..f34f8a57ad 100644 --- a/flags/audio_routing.aconfig +++ b/flags/audio_routing.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "audio_routing_centralization" diff --git a/flags/bta_dm.aconfig b/flags/bta_dm.aconfig index 38a0e4af5a..332fa4958d 100644 --- a/flags/bta_dm.aconfig +++ b/flags/bta_dm.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "synchronous_bta_sec" diff --git a/flags/btif_dm.aconfig b/flags/btif_dm.aconfig index aeb88e210b..0d058900d0 100644 --- a/flags/btif_dm.aconfig +++ b/flags/btif_dm.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "ignore_bond_type_for_le" diff --git a/flags/connectivity.aconfig b/flags/connectivity.aconfig index 1d50dadb57..ef83336d00 100644 --- a/flags/connectivity.aconfig +++ b/flags/connectivity.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "api_get_connection_state_using_identity_address" diff --git a/flags/content_profiles.aconfig b/flags/content_profiles.aconfig index 6f371307b1..c51d11feb2 100644 --- a/flags/content_profiles.aconfig +++ b/flags/content_profiles.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "content_profiles_errors_metrics" diff --git a/flags/discovery_service.aconfig b/flags/discovery_service.aconfig index eaecd0f124..f3ccef970f 100644 --- a/flags/discovery_service.aconfig +++ b/flags/discovery_service.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "gdx_device_discovery" diff --git a/flags/dumpsys.aconfig b/flags/dumpsys.aconfig index 66fb79d730..ae7ff19fb3 100644 --- a/flags/dumpsys.aconfig +++ b/flags/dumpsys.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "dumpsys_use_passed_in_fd" diff --git a/flags/framework.aconfig b/flags/framework.aconfig index ab09f711bb..daa1119afe 100644 --- a/flags/framework.aconfig +++ b/flags/framework.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "mfi_has_uuid" diff --git a/flags/gap.aconfig b/flags/gap.aconfig index 8ac7124fa0..810e34507e 100644 --- a/flags/gap.aconfig +++ b/flags/gap.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "encrypted_advertising_data" diff --git a/flags/hal.aconfig b/flags/hal.aconfig index 101650dcd4..ebcf64390f 100644 --- a/flags/hal.aconfig +++ b/flags/hal.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "audio_hal_version_class" diff --git a/flags/hap.aconfig b/flags/hap.aconfig index 45c8749e6d..32da69b575 100644 --- a/flags/hap.aconfig +++ b/flags/hap.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "settings_can_control_hap_preset" diff --git a/flags/hfp.aconfig b/flags/hfp.aconfig index 3ff6dc7b17..b50bb4a5cd 100644 --- a/flags/hfp.aconfig +++ b/flags/hfp.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "auto_connect_on_hfp_when_no_a2dp_device" diff --git a/flags/hid.aconfig b/flags/hid.aconfig index ebad661a70..cfca613123 100644 --- a/flags/hid.aconfig +++ b/flags/hid.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "break_uhid_polling_early" diff --git a/flags/l2cap.aconfig b/flags/l2cap.aconfig index 7b7dd68f28..86b36f74f9 100644 --- a/flags/l2cap.aconfig +++ b/flags/l2cap.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "l2cap_tx_complete_cb_info" diff --git a/flags/le_advertising.aconfig b/flags/le_advertising.aconfig index 4b12c8a44b..524d0461e5 100644 --- a/flags/le_advertising.aconfig +++ b/flags/le_advertising.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "nrpa_non_connectable_adv" diff --git a/flags/leaudio.aconfig b/flags/leaudio.aconfig index 911526ca52..c79cfd2039 100644 --- a/flags/leaudio.aconfig +++ b/flags/leaudio.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "leaudio_broadcast_monitor_source_sync_status" @@ -104,3 +105,47 @@ flag { description: "Adds missing frequencies defined by the Bluetooth SIG" bug: "323287937" } + +flag { + name: "leaudio_callback_on_group_stream_status" + namespace: "bluetooth" + description: "Add group stream status callback to notify about playing state" + bug: "323288608" +} + +flag { + name: "leaudio_mcs_tbs_authorization_rebond_fix" + namespace: "bluetooth" + description: "Removes authorization data for unbonded devices in MCS and TBS service" + bug: "323339440" + metadata { + purpose: PURPOSE_BUGFIX + } +} + +flag { + name: "leaudio_multiple_vocs_instances_api" + namespace: "bluetooth" + description: "Support multiple audio outputs for volume offset" + bug: "323156655" +} + +flag { + name: "leaudio_volume_change_on_ringtone_fix" + namespace: "bluetooth" + description: "Apply the volume update to call volume during ringtone" + bug: "324041939" + metadata { + purpose: PURPOSE_BUGFIX + } +} + +flag { + name: "leaudio_active_device_manager_group_handling_fix" + namespace: "bluetooth" + description: "Make sure Active Device Manager understands LeAudio groups" + bug: "324364321" + metadata { + purpose: PURPOSE_BUGFIX + } +} diff --git a/flags/opp.aconfig b/flags/opp.aconfig index 5dc0c289e1..d32b73f95d 100644 --- a/flags/opp.aconfig +++ b/flags/opp.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "opp_start_activity_directly_from_notification" @@ -12,4 +13,7 @@ flag { namespace: "bluetooth" description: "Fix UI issues related to multiple OPP notifications" bug: "323096132" + metadata { + purpose: PURPOSE_BUGFIX + } } diff --git a/flags/ranging.aconfig b/flags/ranging.aconfig index 1be1b6edf7..811bf611de 100644 --- a/flags/ranging.aconfig +++ b/flags/ranging.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "channel_sounding" @@ -6,3 +7,10 @@ flag { description: "Enable Channel Sounding" bug: "317683528" } + +flag { + name: "channel_sounding_in_stack" + namespace: "bluetooth" + description: "Enable Channel Sounding in the Bluetooth stack" + bug: "324185011" +}
\ No newline at end of file diff --git a/flags/rfcomm.aconfig b/flags/rfcomm.aconfig index f7e9fe9695..a801f4b96e 100644 --- a/flags/rfcomm.aconfig +++ b/flags/rfcomm.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "rfcomm_always_use_mitm" diff --git a/flags/rnr.aconfig b/flags/rnr.aconfig index d1b91435c3..3acc5d02a0 100644 --- a/flags/rnr.aconfig +++ b/flags/rnr.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "rnr_cancel_before_event_race" diff --git a/flags/security.aconfig b/flags/security.aconfig index 85bedde180..3addb59a68 100644 --- a/flags/security.aconfig +++ b/flags/security.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "correct_bond_type_of_loaded_devices" diff --git a/flags/sniff.aconfig b/flags/sniff.aconfig index 14aa2b0370..5b66d7494a 100644 --- a/flags/sniff.aconfig +++ b/flags/sniff.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "enable_sniff_offload" diff --git a/flags/sockets.aconfig b/flags/sockets.aconfig index 8310fedc35..c6770cd6e8 100644 --- a/flags/sockets.aconfig +++ b/flags/sockets.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "unix_file_socket_creation_failure" diff --git a/flags/system_service.aconfig b/flags/system_service.aconfig index c749e1817a..64bdedcca1 100644 --- a/flags/system_service.aconfig +++ b/flags/system_service.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "airplane_ressources_in_app" @@ -8,6 +9,13 @@ flag { } flag { + name: "auto_on_feature" + namespace: "bluetooth" + description: "Turn bluetooth on next morning at 5 am" + bug: "323060869" +} + +flag { name: "system_server_messenger" namespace: "bluetooth" description: "Replace binder call to the system server with a Messenger to enforce thread safety" diff --git a/flags/vcp.aconfig b/flags/vcp.aconfig index 2869941017..bdc00477c7 100644 --- a/flags/vcp.aconfig +++ b/flags/vcp.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "vcp_mute_unmute" diff --git a/flags/vsc.aconfig b/flags/vsc.aconfig index 7f77e57bb4..fe312876ca 100644 --- a/flags/vsc.aconfig +++ b/flags/vsc.aconfig @@ -1,4 +1,5 @@ package: "com.android.bluetooth.flags" +container: "com.android.btservices" flag { name: "report_vsc_data_from_the_gd_controller" diff --git a/floss/build/Dockerfile b/floss/build/Dockerfile index e0e4824856..2be3277773 100644 --- a/floss/build/Dockerfile +++ b/floss/build/Dockerfile @@ -31,6 +31,7 @@ RUN apt-get update && \ libdouble-conversion-dev \ libevent-dev \ libflatbuffers-dev \ + libfmt-dev \ libgl1-mesa-dev \ libglib2.0-dev \ libgtest-dev \ diff --git a/framework/api/current.txt b/framework/api/current.txt index fc76276367..4b56783247 100644 --- a/framework/api/current.txt +++ b/framework/api/current.txt @@ -627,6 +627,7 @@ package android.bluetooth { field public static final int CONNECTION_PRIORITY_HIGH = 1; // 0x1 field public static final int CONNECTION_PRIORITY_LOW_POWER = 2; // 0x2 field public static final int GATT_CONNECTION_CONGESTED = 143; // 0x8f + field @FlaggedApi("com.android.bluetooth.flags.enumerate_gatt_errors") public static final int GATT_CONNECTION_TIMEOUT = 147; // 0x93 field public static final int GATT_FAILURE = 257; // 0x101 field public static final int GATT_INSUFFICIENT_AUTHENTICATION = 5; // 0x5 field public static final int GATT_INSUFFICIENT_AUTHORIZATION = 8; // 0x8 @@ -976,12 +977,19 @@ package android.bluetooth { field public static final int FRAME_DURATION_10000 = 2; // 0x2 field public static final int FRAME_DURATION_7500 = 1; // 0x1 field public static final int FRAME_DURATION_NONE = 0; // 0x0 + field @FlaggedApi("com.android.bluetooth.flags.leaudio_add_sampling_frequencies") public static final int SAMPLE_RATE_11025 = 2; // 0x2 field public static final int SAMPLE_RATE_16000 = 4; // 0x4 + field @FlaggedApi("com.android.bluetooth.flags.leaudio_add_sampling_frequencies") public static final int SAMPLE_RATE_176400 = 1024; // 0x400 + field @FlaggedApi("com.android.bluetooth.flags.leaudio_add_sampling_frequencies") public static final int SAMPLE_RATE_192000 = 2048; // 0x800 + field @FlaggedApi("com.android.bluetooth.flags.leaudio_add_sampling_frequencies") public static final int SAMPLE_RATE_22050 = 8; // 0x8 field public static final int SAMPLE_RATE_24000 = 16; // 0x10 field public static final int SAMPLE_RATE_32000 = 32; // 0x20 + field @FlaggedApi("com.android.bluetooth.flags.leaudio_add_sampling_frequencies") public static final int SAMPLE_RATE_384000 = 4096; // 0x1000 field public static final int SAMPLE_RATE_44100 = 64; // 0x40 field public static final int SAMPLE_RATE_48000 = 128; // 0x80 field public static final int SAMPLE_RATE_8000 = 1; // 0x1 + field @FlaggedApi("com.android.bluetooth.flags.leaudio_add_sampling_frequencies") public static final int SAMPLE_RATE_88200 = 256; // 0x100 + field @FlaggedApi("com.android.bluetooth.flags.leaudio_add_sampling_frequencies") public static final int SAMPLE_RATE_96000 = 512; // 0x200 field public static final int SAMPLE_RATE_NONE = 0; // 0x0 field public static final int SOURCE_CODEC_TYPE_INVALID = 1000000; // 0xf4240 field public static final int SOURCE_CODEC_TYPE_LC3 = 0; // 0x0 diff --git a/framework/api/system-current.txt b/framework/api/system-current.txt index 5e779c2c89..52c366fa91 100644 --- a/framework/api/system-current.txt +++ b/framework/api/system-current.txt @@ -184,6 +184,7 @@ package android.bluetooth { method @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public boolean createBondOutOfBand(int, @Nullable android.bluetooth.OobData, @Nullable android.bluetooth.OobData); method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int disconnect(); method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public boolean fetchUuidsWithSdp(int); + method @FlaggedApi("com.android.bluetooth.flags.metadata_api_inactive_audio_device_upon_connection") @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int getActiveAudioDevicePolicy(); method @NonNull @RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED) public String getAnonymizedAddress(); method @IntRange(from=0xffffff9c, to=100) @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public int getBatteryLevel(); method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int getConnectionHandle(int); @@ -202,6 +203,7 @@ package android.bluetooth { method @RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED) public void prepareToEnterProcess(@NonNull android.content.AttributionSource); method @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public boolean removeBond(); method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int requestAudioPolicyAsSink(@NonNull android.bluetooth.BluetoothSinkAudioPolicy); + method @FlaggedApi("com.android.bluetooth.flags.metadata_api_inactive_audio_device_upon_connection") @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int setActiveAudioDevicePolicy(int); method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public boolean setLowLatencyAudioAllowed(boolean); method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public boolean setMessageAccessPermission(int); method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public boolean setMetadata(int, @NonNull byte[]); @@ -220,6 +222,9 @@ package android.bluetooth { field @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public static final String ACTION_PAIRING_CANCEL = "android.bluetooth.device.action.PAIRING_CANCEL"; field @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public static final String ACTION_SILENCE_MODE_CHANGED = "android.bluetooth.device.action.SILENCE_MODE_CHANGED"; field @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public static final String ACTION_SWITCH_BUFFER_SIZE = "android.bluetooth.device.action.SWITCH_BUFFER_SIZE"; + field @FlaggedApi("com.android.bluetooth.flags.metadata_api_inactive_audio_device_upon_connection") public static final int ACTIVE_AUDIO_DEVICE_POLICY_ALL_PROFILES_ACTIVE_UPON_CONNECTION = 1; // 0x1 + field @FlaggedApi("com.android.bluetooth.flags.metadata_api_inactive_audio_device_upon_connection") public static final int ACTIVE_AUDIO_DEVICE_POLICY_ALL_PROFILES_INACTIVE_UPON_CONNECTION = 2; // 0x2 + field @FlaggedApi("com.android.bluetooth.flags.metadata_api_inactive_audio_device_upon_connection") public static final int ACTIVE_AUDIO_DEVICE_POLICY_DEFAULT = 0; // 0x0 field public static final int BATTERY_LEVEL_BLUETOOTH_OFF = -100; // 0xffffff9c field public static final int BATTERY_LEVEL_UNKNOWN = -1; // 0xffffffff field public static final int CONNECTION_ACCESS_NO = 2; // 0x2 @@ -437,7 +442,9 @@ package android.bluetooth { method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int getConnectionPolicy(@NonNull android.bluetooth.BluetoothDevice); method @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public int getConnectionState(@NonNull android.bluetooth.BluetoothDevice); method @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public java.util.List<android.bluetooth.BluetoothDevice> getDevicesMatchingConnectionStates(int[]); + method @FlaggedApi("com.android.bluetooth.flags.allow_switching_hid_and_hogp") @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int getPreferredTransport(@NonNull android.bluetooth.BluetoothDevice); method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public boolean setConnectionPolicy(@NonNull android.bluetooth.BluetoothDevice, int); + method @FlaggedApi("com.android.bluetooth.flags.allow_switching_hid_and_hogp") @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public boolean setPreferredTransport(@NonNull android.bluetooth.BluetoothDevice, int); field @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public static final String ACTION_CONNECTION_STATE_CHANGED = "android.bluetooth.input.profile.action.CONNECTION_STATE_CHANGED"; } @@ -489,6 +496,7 @@ package android.bluetooth { method public void onGroupNodeAdded(@NonNull android.bluetooth.BluetoothDevice, int); method public void onGroupNodeRemoved(@NonNull android.bluetooth.BluetoothDevice, int); method public void onGroupStatusChanged(int, int); + method @FlaggedApi("com.android.bluetooth.flags.leaudio_callback_on_group_stream_status") public default void onGroupStreamStatusChanged(int, int); } public final class BluetoothLeAudioCodecConfigMetadata implements android.os.Parcelable { @@ -1336,7 +1344,7 @@ package android.bluetooth.le { method @NonNull public android.bluetooth.le.DistanceMeasurementResult build(); method @NonNull public android.bluetooth.le.DistanceMeasurementResult.Builder setAltitudeAngle(@FloatRange(from=-90.0, to=90.0) double); method @NonNull public android.bluetooth.le.DistanceMeasurementResult.Builder setAzimuthAngle(@FloatRange(from=0.0, to=360.0) double); - method @FlaggedApi("com.android.bluetooth.flags.channel_sounding") @NonNull public android.bluetooth.le.DistanceMeasurementResult.Builder setConfidenceLevel(@FloatRange(from=0.0, to=100.0) double); + method @FlaggedApi("com.android.bluetooth.flags.channel_sounding") @NonNull public android.bluetooth.le.DistanceMeasurementResult.Builder setConfidenceLevel(@FloatRange(from=0.0, to=1.0) double); method @FlaggedApi("com.android.bluetooth.flags.channel_sounding") @NonNull public android.bluetooth.le.DistanceMeasurementResult.Builder setDelaySpreadMeters(double); method @FlaggedApi("com.android.bluetooth.flags.channel_sounding") @NonNull public android.bluetooth.le.DistanceMeasurementResult.Builder setDetectedAttackLevel(int); method @NonNull public android.bluetooth.le.DistanceMeasurementResult.Builder setErrorAltitudeAngle(@FloatRange(from=0.0, to=180.0) double); diff --git a/framework/java/android/bluetooth/BluetoothDevice.java b/framework/java/android/bluetooth/BluetoothDevice.java index 5840398e8d..679b45080f 100644 --- a/framework/java/android/bluetooth/BluetoothDevice.java +++ b/framework/java/android/bluetooth/BluetoothDevice.java @@ -1363,6 +1363,37 @@ public final class BluetoothDevice implements Parcelable, Attributable { @FlaggedApi(Flags.FLAG_GET_ADDRESS_TYPE_API) public static final int ADDRESS_TYPE_ANONYMOUS = 0xFF; + /** + * Indicates default active audio device policy is applied to this device + * + * @hide + */ + @FlaggedApi(Flags.FLAG_METADATA_API_INACTIVE_AUDIO_DEVICE_UPON_CONNECTION) + @SystemApi + public static final int ACTIVE_AUDIO_DEVICE_POLICY_DEFAULT = 0; + + /** + * Indicates all profiles active audio device policy is applied to this device + * + * <p>all profiles are active upon device connection + * + * @hide + */ + @FlaggedApi(Flags.FLAG_METADATA_API_INACTIVE_AUDIO_DEVICE_UPON_CONNECTION) + @SystemApi + public static final int ACTIVE_AUDIO_DEVICE_POLICY_ALL_PROFILES_ACTIVE_UPON_CONNECTION = 1; + + /** + * Indicates all profiles inactive audio device policy is applied to this device + * + * <p>all profiles are inactive upon device connection + * + * @hide + */ + @FlaggedApi(Flags.FLAG_METADATA_API_INACTIVE_AUDIO_DEVICE_UPON_CONNECTION) + @SystemApi + public static final int ACTIVE_AUDIO_DEVICE_POLICY_ALL_PROFILES_INACTIVE_UPON_CONNECTION = 2; + private static final String NULL_MAC_ADDRESS = "00:00:00:00:00:00"; private final String mAddress; @@ -3667,6 +3698,118 @@ public final class BluetoothDevice implements Parcelable, Attributable { return defaultValue; } + /** @hide */ + @IntDef( + value = { + BluetoothStatusCodes.SUCCESS, + BluetoothStatusCodes.ERROR_BLUETOOTH_NOT_ENABLED, + BluetoothStatusCodes.ERROR_BLUETOOTH_NOT_ALLOWED, + BluetoothStatusCodes.ERROR_MISSING_BLUETOOTH_CONNECT_PERMISSION, + BluetoothStatusCodes.ERROR_DEVICE_NOT_BONDED + }) + @Retention(RetentionPolicy.SOURCE) + public @interface SetActiveAudioDevicePolicyReturnValues {} + + /** + * Active audio device policy for this device + * + * @hide + */ + @IntDef( + prefix = "ACTIVE_AUDIO_DEVICE_POLICY_", + value = { + ACTIVE_AUDIO_DEVICE_POLICY_DEFAULT, + ACTIVE_AUDIO_DEVICE_POLICY_ALL_PROFILES_ACTIVE_UPON_CONNECTION, + ACTIVE_AUDIO_DEVICE_POLICY_ALL_PROFILES_INACTIVE_UPON_CONNECTION + }) + @Retention(RetentionPolicy.SOURCE) + public @interface ActiveAudioDevicePolicy {} + + /** + * Set the active audio device policy for this {@link BluetoothDevice} to indicate what {@link + * ActiveAudioDevicePolicy} is applied upon device connection. + * + * <p>This API allows application to set the audio device profiles active policy upon + * connection, only bonded device's policy will be persisted across Bluetooth restart. Policy + * setting will be removed when the device's bond state is moved to {@link #BOND_NONE}. + * + * @param activeAudioDevicePolicy is the active audio device policy to set for this device + * @return whether the policy was set properly + * @throws IllegalArgumentException if this BluetoothDevice object has an invalid address + * @hide + */ + @FlaggedApi(Flags.FLAG_METADATA_API_INACTIVE_AUDIO_DEVICE_UPON_CONNECTION) + @SystemApi + @RequiresBluetoothConnectPermission + @RequiresPermission( + allOf = { + android.Manifest.permission.BLUETOOTH_CONNECT, + android.Manifest.permission.BLUETOOTH_PRIVILEGED, + }) + public @SetActiveAudioDevicePolicyReturnValues int setActiveAudioDevicePolicy( + @ActiveAudioDevicePolicy int activeAudioDevicePolicy) { + if (DBG) log("setActiveAudioDevicePolicy(" + activeAudioDevicePolicy + ")"); + if (!BluetoothAdapter.checkBluetoothAddress(getAddress())) { + throw new IllegalArgumentException("device cannot have an invalid address"); + } + + final IBluetooth service = getService(); + final int defaultValue = BluetoothStatusCodes.ERROR_BLUETOOTH_NOT_ENABLED; + if (service == null || !isBluetoothEnabled()) { + Log.e(TAG, "Bluetooth is not enabled. Cannot set active audio device policy."); + if (DBG) log(Log.getStackTraceString(new Throwable())); + } else { + try { + final SynchronousResultReceiver<Integer> recv = SynchronousResultReceiver.get(); + service.setActiveAudioDevicePolicy( + this, activeAudioDevicePolicy, mAttributionSource, recv); + return recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(defaultValue); + } catch (TimeoutException e) { + Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); + } catch (RemoteException e) { + Log.e(TAG, "", e); + throw e.rethrowAsRuntimeException(); + } + } + return defaultValue; + } + + /** + * Get the active audio device policy for this {@link BluetoothDevice}. + * + * @return active audio device policy of the device + * @hide + */ + @FlaggedApi(Flags.FLAG_METADATA_API_INACTIVE_AUDIO_DEVICE_UPON_CONNECTION) + @SystemApi + @RequiresBluetoothConnectPermission + @RequiresPermission( + allOf = { + android.Manifest.permission.BLUETOOTH_CONNECT, + android.Manifest.permission.BLUETOOTH_PRIVILEGED, + }) + public @ActiveAudioDevicePolicy int getActiveAudioDevicePolicy() { + if (DBG) log("getActiveAudioDevicePolicy"); + final IBluetooth service = getService(); + final int defaultValue = ACTIVE_AUDIO_DEVICE_POLICY_DEFAULT; + if (service == null || !isBluetoothEnabled()) { + Log.e(TAG, "Bluetooth is not enabled. Cannot get active audio device policy."); + if (DBG) log(Log.getStackTraceString(new Throwable())); + } else { + try { + final SynchronousResultReceiver<Integer> recv = SynchronousResultReceiver.get(); + service.getActiveAudioDevicePolicy(this, mAttributionSource, recv); + return recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(defaultValue); + } catch (TimeoutException e) { + Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); + } catch (RemoteException e) { + Log.e(TAG, "", e); + throw e.rethrowAsRuntimeException(); + } + } + return defaultValue; + } + 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 e09aa434b9..0c0a333138 100644 --- a/framework/java/android/bluetooth/BluetoothGatt.java +++ b/framework/java/android/bluetooth/BluetoothGatt.java @@ -18,6 +18,7 @@ package android.bluetooth; import static android.bluetooth.BluetoothUtils.getSyncTimeout; +import android.annotation.FlaggedApi; import android.annotation.IntDef; import android.annotation.NonNull; import android.annotation.RequiresNoPermission; @@ -35,6 +36,7 @@ import android.os.ParcelUuid; import android.os.RemoteException; import android.util.Log; +import com.android.bluetooth.flags.Flags; import com.android.modules.utils.SynchronousResultReceiver; import java.lang.annotation.Retention; @@ -128,6 +130,13 @@ public final class BluetoothGatt implements BluetoothProfile { /** A remote device connection is congested. */ public static final int GATT_CONNECTION_CONGESTED = 0x8f; + /** + * GATT connection timed out, likely due to the remote device being out of range or not + * advertising as connectable. + */ + @FlaggedApi(Flags.FLAG_ENUMERATE_GATT_ERRORS) + public static final int GATT_CONNECTION_TIMEOUT = 0x93; + /** A GATT operation failed, errors other than the above */ public static final int GATT_FAILURE = 0x101; diff --git a/framework/java/android/bluetooth/BluetoothHidHost.java b/framework/java/android/bluetooth/BluetoothHidHost.java index 4c55ad19dc..69bdf2115a 100644 --- a/framework/java/android/bluetooth/BluetoothHidHost.java +++ b/framework/java/android/bluetooth/BluetoothHidHost.java @@ -19,12 +19,14 @@ package android.bluetooth; import static android.bluetooth.BluetoothUtils.getSyncTimeout; import android.Manifest; +import android.annotation.FlaggedApi; import android.annotation.NonNull; import android.annotation.RequiresPermission; import android.annotation.SdkConstant; import android.annotation.SdkConstant.SdkConstantType; import android.annotation.SuppressLint; import android.annotation.SystemApi; +import android.bluetooth.BluetoothDevice.Transport; import android.bluetooth.annotations.RequiresBluetoothConnectPermission; import android.bluetooth.annotations.RequiresLegacyBluetoothAdminPermission; import android.bluetooth.annotations.RequiresLegacyBluetoothPermission; @@ -34,10 +36,12 @@ import android.os.IBinder; import android.os.RemoteException; import android.util.Log; +import com.android.bluetooth.flags.Flags; import com.android.modules.utils.SynchronousResultReceiver; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.concurrent.TimeoutException; /** @@ -64,12 +68,16 @@ public final class BluetoothHidHost implements BluetoothProfile { * <ul> * <li>{@link #EXTRA_STATE} - The current state of the profile. * <li>{@link #EXTRA_PREVIOUS_STATE}- The previous state of the profile. + * <li>{@link BluetoothDevice#EXTRA_TRANSPORT} - Transport of the connection. * <li>{@link BluetoothDevice#EXTRA_DEVICE} - The remote device. * </ul> * * <p>{@link #EXTRA_STATE} or {@link #EXTRA_PREVIOUS_STATE} can be any of {@link * #STATE_DISCONNECTED}, {@link #STATE_CONNECTING}, {@link #STATE_CONNECTED}, {@link * #STATE_DISCONNECTING}. + * + * <p>{@link BluetoothDevice#EXTRA_TRANSPORT} can be any of {@link + * BluetoothDevice#TRANSPORT_BREDR}, {@link BluetoothDevice#TRANSPORT_LE}. */ @SuppressLint("ActionValue") @RequiresLegacyBluetoothPermission @@ -465,6 +473,60 @@ public final class BluetoothHidHost implements BluetoothProfile { } /** + * Set preferred transport for the device + * + * <p>The device should already be paired, services must have been discovered. This API is + * effective only if both the HID and HOGP are supported on the remote device. + * + * @param device paired bluetooth device + * @param transport the preferred transport to set for this device + * @return true if preferred transport is set, false on error + * @throws IllegalArgumentException if the {@code device} invalid. + * @hide + */ + @FlaggedApi(Flags.FLAG_ALLOW_SWITCHING_HID_AND_HOGP) + @SystemApi + @RequiresBluetoothConnectPermission + @RequiresPermission( + allOf = { + android.Manifest.permission.BLUETOOTH_CONNECT, + android.Manifest.permission.BLUETOOTH_PRIVILEGED, + }) + public boolean setPreferredTransport( + @NonNull BluetoothDevice device, @Transport int transport) { + if (DBG) log("setPreferredTransport(" + device + ", " + transport + ")"); + + Objects.requireNonNull(device, "device must not be null"); + + if (transport != BluetoothDevice.TRANSPORT_AUTO + && transport != BluetoothDevice.TRANSPORT_BREDR + && transport != BluetoothDevice.TRANSPORT_LE) { + throw new IllegalArgumentException("Invalid transport value"); + } + + final IBluetoothHidHost service = getService(); + final boolean defaultValue = false; + + if (service == null) { + Log.w(TAG, "Proxy not attached to service"); + if (DBG) log(Log.getStackTraceString(new Throwable())); + } else if (!isEnabled()) { + Log.w(TAG, "Not ready"); + } else if (!isValidDevice(device)) { + throw new IllegalArgumentException("Invalid device"); + } else { + try { + final SynchronousResultReceiver<Boolean> recv = SynchronousResultReceiver.get(); + service.setPreferredTransport(device, transport, mAttributionSource, recv); + return recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(defaultValue); + } catch (RemoteException | TimeoutException e) { + Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); + } + } + return defaultValue; + } + + /** * Get the priority of the profile. * * <p>The priority can be any of: {@link #PRIORITY_OFF}, {@link #PRIORITY_ON}, {@link @@ -524,6 +586,48 @@ public final class BluetoothHidHost implements BluetoothProfile { return defaultValue; } + /** + * Get the preferred transport for the device. + * + * @param device Bluetooth device + * @return preferred transport for the device + * @throws IllegalArgumentException if the {@code device} invalid. + * @hide + */ + @FlaggedApi(Flags.FLAG_ALLOW_SWITCHING_HID_AND_HOGP) + @SystemApi + @RequiresBluetoothConnectPermission + @RequiresPermission( + allOf = { + android.Manifest.permission.BLUETOOTH_CONNECT, + android.Manifest.permission.BLUETOOTH_PRIVILEGED, + }) + public @Transport int getPreferredTransport(@NonNull BluetoothDevice device) { + if (VDBG) log("getPreferredTransport(" + device + ")"); + + Objects.requireNonNull(device, "device must not be null"); + + final IBluetoothHidHost service = getService(); + final int defaultValue = BluetoothDevice.TRANSPORT_AUTO; + if (service == null) { + Log.w(TAG, "Proxy not attached to service"); + if (DBG) log(Log.getStackTraceString(new Throwable())); + } else if (!isEnabled()) { + Log.w(TAG, "Not ready"); + } else if (!isValidDevice(device)) { + throw new IllegalArgumentException("Invalid device"); + } else { + try { + final SynchronousResultReceiver<Integer> recv = SynchronousResultReceiver.get(); + service.getPreferredTransport(device, mAttributionSource, recv); + return recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(defaultValue); + } catch (RemoteException | TimeoutException e) { + Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); + } + } + return defaultValue; + } + private boolean isEnabled() { return mAdapter.getState() == BluetoothAdapter.STATE_ON; } diff --git a/framework/java/android/bluetooth/BluetoothLeAudio.java b/framework/java/android/bluetooth/BluetoothLeAudio.java index 5a538d1145..1bbc0848c1 100644 --- a/framework/java/android/bluetooth/BluetoothLeAudio.java +++ b/framework/java/android/bluetooth/BluetoothLeAudio.java @@ -20,6 +20,7 @@ package android.bluetooth; import static android.bluetooth.BluetoothUtils.getSyncTimeout; import android.annotation.CallbackExecutor; +import android.annotation.FlaggedApi; import android.annotation.IntDef; import android.annotation.IntRange; import android.annotation.NonNull; @@ -38,6 +39,7 @@ import android.os.RemoteException; import android.util.CloseGuard; import android.util.Log; +import com.android.bluetooth.flags.Flags; import com.android.modules.utils.SynchronousResultReceiver; import java.lang.annotation.Retention; @@ -61,7 +63,7 @@ import java.util.concurrent.TimeoutException; */ public final class BluetoothLeAudio implements BluetoothProfile, AutoCloseable { private static final String TAG = "BluetoothLeAudio"; - private static final boolean DBG = false; + private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG); private static final boolean VDBG = false; private final Map<Callback, Executor> mCallbackExecutorMap = new HashMap<>(); @@ -85,6 +87,15 @@ public final class BluetoothLeAudio implements BluetoothProfile, AutoCloseable { }) @interface GroupStatus {} + /** @hide */ + @Retention(RetentionPolicy.SOURCE) + @IntDef( + value = { + GROUP_STREAM_STATUS_IDLE, + GROUP_STREAM_STATUS_STREAMING, + }) + @interface GroupStreamStatus {} + /** * Callback invoked when callback is registered and when codec config changes on the remote * device. @@ -127,6 +138,22 @@ public final class BluetoothLeAudio implements BluetoothProfile, AutoCloseable { */ @SystemApi void onGroupStatusChanged(int groupId, @GroupStatus int groupStatus); + + /** + * Callback invoked when the group's stream status changes. + * + * @param groupId the group id + * @param groupStreamStatus streaming or idle state. + * @hide + */ + @FlaggedApi(Flags.FLAG_LEAUDIO_CALLBACK_ON_GROUP_STREAM_STATUS) + @SystemApi + default void onGroupStreamStatusChanged( + int groupId, @GroupStreamStatus int groupStreamStatus) { + if (DBG) { + Log.d(TAG, " onGroupStreamStatusChanged is not implemented."); + } + } } @SuppressLint("AndroidFrameworkBluetoothPermission") @@ -620,6 +647,23 @@ public final class BluetoothLeAudio implements BluetoothProfile, AutoCloseable { */ public static final int GROUP_STATUS_INACTIVE = IBluetoothLeAudio.GROUP_STATUS_INACTIVE; + /** + * Indicating that group stream is in IDLE (not streaming) + * + * @hide + */ + @FlaggedApi(Flags.FLAG_LEAUDIO_CALLBACK_ON_GROUP_STREAM_STATUS) + public static final int GROUP_STREAM_STATUS_IDLE = IBluetoothLeAudio.GROUP_STREAM_STATUS_IDLE; + + /** + * Indicating that group is STREAMING + * + * @hide + */ + @FlaggedApi(Flags.FLAG_LEAUDIO_CALLBACK_ON_GROUP_STREAM_STATUS) + public static final int GROUP_STREAM_STATUS_STREAMING = + IBluetoothLeAudio.GROUP_STREAM_STATUS_STREAMING; + private IBluetoothLeAudio mService; /** diff --git a/framework/java/android/bluetooth/BluetoothLeAudioCodecConfig.java b/framework/java/android/bluetooth/BluetoothLeAudioCodecConfig.java index acf95c77e7..4c820b68d3 100644 --- a/framework/java/android/bluetooth/BluetoothLeAudioCodecConfig.java +++ b/framework/java/android/bluetooth/BluetoothLeAudioCodecConfig.java @@ -16,12 +16,15 @@ package android.bluetooth; +import android.annotation.FlaggedApi; import android.annotation.IntDef; import android.annotation.NonNull; import android.annotation.Nullable; import android.os.Parcel; import android.os.Parcelable; +import com.android.bluetooth.flags.Flags; + import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Objects; @@ -73,11 +76,18 @@ public final class BluetoothLeAudioCodecConfig implements Parcelable { value = { SAMPLE_RATE_NONE, SAMPLE_RATE_8000, + SAMPLE_RATE_11025, SAMPLE_RATE_16000, + SAMPLE_RATE_22050, SAMPLE_RATE_24000, SAMPLE_RATE_32000, SAMPLE_RATE_44100, - SAMPLE_RATE_48000 + SAMPLE_RATE_48000, + SAMPLE_RATE_88200, + SAMPLE_RATE_96000, + SAMPLE_RATE_176400, + SAMPLE_RATE_192000, + SAMPLE_RATE_384000 }) @Retention(RetentionPolicy.SOURCE) public @interface SampleRate {} @@ -85,16 +95,24 @@ public final class BluetoothLeAudioCodecConfig implements Parcelable { /** * Codec sample rate 0 Hz. Default value used for codec sample rate. Values are the bit mask as * defined in the Bluetooth Assigned Numbers, Generic Audio, Supported_Sampling_Frequencies - * table Note: We use only part of it. + * table. */ public static final int SAMPLE_RATE_NONE = 0; /** Codec sample rate 8000 Hz. */ public static final int SAMPLE_RATE_8000 = 0x01 << 0; + /** Codec sample rate 11025 Hz. */ + @FlaggedApi(Flags.FLAG_LEAUDIO_ADD_SAMPLING_FREQUENCIES) + public static final int SAMPLE_RATE_11025 = 0x01 << 1; + /** Codec sample rate 16000 Hz. */ public static final int SAMPLE_RATE_16000 = 0x01 << 2; + /** Codec sample rate 22050 Hz. */ + @FlaggedApi(Flags.FLAG_LEAUDIO_ADD_SAMPLING_FREQUENCIES) + public static final int SAMPLE_RATE_22050 = 0x01 << 3; + /** Codec sample rate 24000 Hz. */ public static final int SAMPLE_RATE_24000 = 0x01 << 4; @@ -107,6 +125,26 @@ public final class BluetoothLeAudioCodecConfig implements Parcelable { /** Codec sample rate 48000 Hz. */ public static final int SAMPLE_RATE_48000 = 0x01 << 7; + /** Codec sample rate 88200 Hz. */ + @FlaggedApi(Flags.FLAG_LEAUDIO_ADD_SAMPLING_FREQUENCIES) + public static final int SAMPLE_RATE_88200 = 0x01 << 8; + + /** Codec sample rate 96000 Hz. */ + @FlaggedApi(Flags.FLAG_LEAUDIO_ADD_SAMPLING_FREQUENCIES) + public static final int SAMPLE_RATE_96000 = 0x01 << 9; + + /** Codec sample rate 176400 Hz. */ + @FlaggedApi(Flags.FLAG_LEAUDIO_ADD_SAMPLING_FREQUENCIES) + public static final int SAMPLE_RATE_176400 = 0x01 << 10; + + /** Codec sample rate 192000 Hz. */ + @FlaggedApi(Flags.FLAG_LEAUDIO_ADD_SAMPLING_FREQUENCIES) + public static final int SAMPLE_RATE_192000 = 0x01 << 11; + + /** Codec sample rate 384000 Hz. */ + @FlaggedApi(Flags.FLAG_LEAUDIO_ADD_SAMPLING_FREQUENCIES) + public static final int SAMPLE_RATE_384000 = 0x01 << 12; + /** @hide */ @IntDef( flag = true, diff --git a/framework/java/android/bluetooth/BluetoothLeAudioCodecConfigMetadata.java b/framework/java/android/bluetooth/BluetoothLeAudioCodecConfigMetadata.java index 0cff465a46..680c15dfca 100644 --- a/framework/java/android/bluetooth/BluetoothLeAudioCodecConfigMetadata.java +++ b/framework/java/android/bluetooth/BluetoothLeAudioCodecConfigMetadata.java @@ -29,13 +29,18 @@ import static android.bluetooth.BluetoothLeAudioCodecConfig.SAMPLE_RATE_8000; import static android.bluetooth.BluetoothLeAudioCodecConfig.SAMPLE_RATE_NONE; import static android.bluetooth.BluetoothLeAudioCodecConfig.SampleRate; +import android.annotation.FlaggedApi; import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.SystemApi; +import android.bluetooth.BluetoothLeAudioCodecConfig.FrameDuration; +import android.bluetooth.BluetoothLeAudioCodecConfig.SampleRate; import android.bluetooth.BluetoothUtils.TypeValueEntry; import android.os.Parcel; import android.os.Parcelable; +import com.android.bluetooth.flags.Flags; + import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; @@ -70,6 +75,13 @@ public final class BluetoothLeAudioCodecConfigMetadata implements Parcelable { private static final int CONFIG_SAMPLING_FREQUENCY_32000 = 0x06; private static final int CONFIG_SAMPLING_FREQUENCY_44100 = 0x07; private static final int CONFIG_SAMPLING_FREQUENCY_48000 = 0x08; + private static final int CONFIG_SAMPLING_FREQUENCY_11025 = 0x09; + private static final int CONFIG_SAMPLING_FREQUENCY_22050 = 0x0a; + private static final int CONFIG_SAMPLING_FREQUENCY_88200 = 0x0b; + private static final int CONFIG_SAMPLING_FREQUENCY_96000 = 0x0c; + private static final int CONFIG_SAMPLING_FREQUENCY_176400 = 0x0d; + private static final int CONFIG_SAMPLING_FREQUENCY_192000 = 0x0e; + private static final int CONFIG_SAMPLING_FREQUENCY_384000 = 0x0f; /** Audio codec config frame duration from metadata. */ private static final int CONFIG_FRAME_DURATION_UNKNOWN = -1; @@ -375,7 +387,20 @@ public final class BluetoothLeAudioCodecConfigMetadata implements Parcelable { && sampleRate != SAMPLE_RATE_32000 && sampleRate != SAMPLE_RATE_44100 && sampleRate != SAMPLE_RATE_48000) { - throw new IllegalArgumentException("Invalid sample rate " + sampleRate); + + if (Flags.leaudioAddSamplingFrequencies()) { + if (sampleRate != BluetoothLeAudioCodecConfig.SAMPLE_RATE_11025 + && sampleRate != BluetoothLeAudioCodecConfig.SAMPLE_RATE_22050 + && sampleRate != BluetoothLeAudioCodecConfig.SAMPLE_RATE_88200 + && sampleRate != BluetoothLeAudioCodecConfig.SAMPLE_RATE_96000 + && sampleRate != BluetoothLeAudioCodecConfig.SAMPLE_RATE_176400 + && sampleRate != BluetoothLeAudioCodecConfig.SAMPLE_RATE_192000 + && sampleRate != BluetoothLeAudioCodecConfig.SAMPLE_RATE_384000) { + throw new IllegalArgumentException("Invalid sample rate " + sampleRate); + } + } else { + throw new IllegalArgumentException("Invalid sample rate " + sampleRate); + } } mSampleRate = sampleRate; return this; @@ -504,6 +529,24 @@ public final class BluetoothLeAudioCodecConfigMetadata implements Parcelable { case CONFIG_SAMPLING_FREQUENCY_48000: return SAMPLE_RATE_48000; default: + if (Flags.leaudioAddSamplingFrequencies()) { + switch (samplingFrequencyValue) { + case CONFIG_SAMPLING_FREQUENCY_11025: + return BluetoothLeAudioCodecConfig.SAMPLE_RATE_11025; + case CONFIG_SAMPLING_FREQUENCY_22050: + return BluetoothLeAudioCodecConfig.SAMPLE_RATE_22050; + case CONFIG_SAMPLING_FREQUENCY_88200: + return BluetoothLeAudioCodecConfig.SAMPLE_RATE_88200; + case CONFIG_SAMPLING_FREQUENCY_96000: + return BluetoothLeAudioCodecConfig.SAMPLE_RATE_96000; + case CONFIG_SAMPLING_FREQUENCY_176400: + return BluetoothLeAudioCodecConfig.SAMPLE_RATE_176400; + case CONFIG_SAMPLING_FREQUENCY_192000: + return BluetoothLeAudioCodecConfig.SAMPLE_RATE_192000; + case CONFIG_SAMPLING_FREQUENCY_384000: + return BluetoothLeAudioCodecConfig.SAMPLE_RATE_384000; + } + } return SAMPLE_RATE_NONE; } } @@ -523,6 +566,24 @@ public final class BluetoothLeAudioCodecConfigMetadata implements Parcelable { case SAMPLE_RATE_48000: return CONFIG_SAMPLING_FREQUENCY_48000; default: + if (Flags.leaudioAddSamplingFrequencies()) { + switch (sampleRateBitSet) { + case BluetoothLeAudioCodecConfig.SAMPLE_RATE_11025: + return CONFIG_SAMPLING_FREQUENCY_11025; + case BluetoothLeAudioCodecConfig.SAMPLE_RATE_22050: + return CONFIG_SAMPLING_FREQUENCY_22050; + case BluetoothLeAudioCodecConfig.SAMPLE_RATE_88200: + return CONFIG_SAMPLING_FREQUENCY_88200; + case BluetoothLeAudioCodecConfig.SAMPLE_RATE_96000: + return CONFIG_SAMPLING_FREQUENCY_96000; + case BluetoothLeAudioCodecConfig.SAMPLE_RATE_176400: + return CONFIG_SAMPLING_FREQUENCY_176400; + case BluetoothLeAudioCodecConfig.SAMPLE_RATE_192000: + return CONFIG_SAMPLING_FREQUENCY_192000; + case BluetoothLeAudioCodecConfig.SAMPLE_RATE_384000: + return CONFIG_SAMPLING_FREQUENCY_384000; + } + } return CONFIG_SAMPLING_FREQUENCY_UNKNOWN; } } diff --git a/framework/java/android/bluetooth/BluetoothVolumeControl.java b/framework/java/android/bluetooth/BluetoothVolumeControl.java index 29ae950f0b..0339034991 100644 --- a/framework/java/android/bluetooth/BluetoothVolumeControl.java +++ b/framework/java/android/bluetooth/BluetoothVolumeControl.java @@ -539,9 +539,9 @@ public final class BluetoothVolumeControl implements BluetoothProfile, AutoClose final boolean defaultValue = false; try { - final SynchronousResultReceiver recv = SynchronousResultReceiver.get(); + final SynchronousResultReceiver<Boolean> recv = SynchronousResultReceiver.get(); service.isVolumeOffsetAvailable(device, mAttributionSource, recv); - recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(defaultValue); + return recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(defaultValue); } catch (RemoteException | TimeoutException e) { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } diff --git a/framework/java/android/bluetooth/le/DistanceMeasurementResult.java b/framework/java/android/bluetooth/le/DistanceMeasurementResult.java index 676636ff7c..7c2815f52e 100644 --- a/framework/java/android/bluetooth/le/DistanceMeasurementResult.java +++ b/framework/java/android/bluetooth/le/DistanceMeasurementResult.java @@ -524,7 +524,7 @@ public final class DistanceMeasurementResult implements Parcelable { /** * Set the confidence of estimated distance. * - * @param confidenceLevel a normalized value from 0.0 (low confidence) to 100.0 (high + * @param confidenceLevel a normalized value from 0.0 (low confidence) to 1.0 (high * confidence) representing the confidence of estimated distance * @throws IllegalArgumentException if value is invalid * @hide @@ -533,8 +533,8 @@ public final class DistanceMeasurementResult implements Parcelable { @SystemApi @NonNull public Builder setConfidenceLevel( - @FloatRange(from = 0.0, to = 100.0) double confidenceLevel) { - if (confidenceLevel > 100.0 || confidenceLevel < 0.0) { + @FloatRange(from = 0.0, to = 1.0) double confidenceLevel) { + if (confidenceLevel > 1.0 || confidenceLevel < 0.0) { throw new IllegalArgumentException( "error confidenceLevel must be in the range from 0.0 to 100.0 : " + confidenceLevel); diff --git a/framework/tests/bumble/Android.bp b/framework/tests/bumble/Android.bp index d1cfa30015..a66ae1e26c 100644 --- a/framework/tests/bumble/Android.bp +++ b/framework/tests/bumble/Android.bp @@ -25,7 +25,9 @@ android_test_helper_app { "androidx.test.ext.truth", "androidx.test.rules", "bluetooth-test-util-lib", + "bluetooth_flags_java_lib", "compatibility-device-util-axt", + "flag-junit", "grpc-java-lite", "grpc-java-okhttp-client-lite", "mockito-kotlin2", diff --git a/framework/tests/bumble/src/android/bluetooth/GattClientTest.java b/framework/tests/bumble/src/android/bluetooth/GattClientTest.java index 051a3e33a9..ef5b6c1c8f 100644 --- a/framework/tests/bumble/src/android/bluetooth/GattClientTest.java +++ b/framework/tests/bumble/src/android/bluetooth/GattClientTest.java @@ -27,14 +27,17 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockingDetails; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; import android.bluetooth.le.BluetoothLeScanner; import android.content.Context; +import android.platform.test.annotations.RequiresFlagsEnabled; +import android.platform.test.flag.junit.CheckFlagsRule; +import android.platform.test.flag.junit.DeviceFlagsValueProvider; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; +import com.android.bluetooth.flags.Flags; import com.android.compatibility.common.util.AdoptShellPermissionsRule; import org.junit.ClassRule; @@ -45,6 +48,9 @@ import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.invocation.Invocation; +import java.util.Collection; +import java.util.UUID; + import pandora.GattProto.GattCharacteristicParams; import pandora.GattProto.GattServiceParams; import pandora.GattProto.RegisterServiceRequest; @@ -52,9 +58,6 @@ import pandora.HostProto.AdvertiseRequest; import pandora.HostProto.AdvertiseResponse; import pandora.HostProto.OwnAddressType; -import java.util.Collection; -import java.util.UUID; - @RunWith(AndroidJUnit4.class) public class GattClientTest { private static final String TAG = "GattClientTest"; @@ -68,6 +71,9 @@ public class GattClientTest { @Rule public final PandoraDevice mBumble = new PandoraDevice(); + @Rule + public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule(); + private final Context mContext = ApplicationProvider.getApplicationContext(); private final BluetoothManager mManager = mContext.getSystemService(BluetoothManager.class); private final BluetoothAdapter mAdapter = mManager.getAdapter(); @@ -134,8 +140,12 @@ public class GattClientTest { inOrder.verify(gattCallback, timeout(1000)) .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_CONNECTED)); + // TODO(323889717): Fix callback being called after gatt.close(). This disconnect shouldn't + // be necessary. + gatt.disconnect(); + inOrder.verify(gattCallback, timeout(1000)) + .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_DISCONNECTED)); gatt.close(); - verifyNoMoreInteractions(gattCallback); } @Test @@ -221,6 +231,24 @@ public class GattClientTest { } } + @Test + @RequiresFlagsEnabled(Flags.FLAG_ENUMERATE_GATT_ERRORS) + public void connectTimeout() { + BluetoothDevice device = + mAdapter.getRemoteLeDevice( + Utils.BUMBLE_RANDOM_ADDRESS, BluetoothDevice.ADDRESS_TYPE_RANDOM); + BluetoothGattCallback gattCallback = mock(BluetoothGattCallback.class); + + // Connecting to a device not advertising results in connection timeout after 30 seconds + device.connectGatt(mContext, false, gattCallback); + + verify(gattCallback, timeout(35000)) + .onConnectionStateChange( + any(), + eq(BluetoothGatt.GATT_CONNECTION_TIMEOUT), + eq(BluetoothProfile.STATE_DISCONNECTED)); + } + private void registerWritableGattService() { String characteristicUuidString = "11111111-1111-1111-1111-111111111111"; diff --git a/framework/tests/bumble/src/android/bluetooth/PandoraDevice.java b/framework/tests/bumble/src/android/bluetooth/PandoraDevice.java index a03115aae3..0b67929273 100644 --- a/framework/tests/bumble/src/android/bluetooth/PandoraDevice.java +++ b/framework/tests/bumble/src/android/bluetooth/PandoraDevice.java @@ -23,18 +23,20 @@ import androidx.test.core.app.ApplicationProvider; import com.google.protobuf.Empty; import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import io.grpc.okhttp.OkHttpChannelBuilder; import org.junit.rules.ExternalResource; +import java.util.concurrent.TimeUnit; + import pandora.DckGrpc; import pandora.GATTGrpc; import pandora.HostGrpc; import pandora.HostProto; import pandora.SecurityGrpc; -import java.util.concurrent.TimeUnit; - public final class PandoraDevice extends ExternalResource { private static final String TAG = PandoraDevice.class.getSimpleName(); private final String mNetworkAddress; @@ -59,7 +61,16 @@ public final class PandoraDevice extends ExternalResource { ManagedChannel channel = OkHttpChannelBuilder.forAddress(mNetworkAddress, mPort).usePlaintext().build(); HostGrpc.HostBlockingStub stub = HostGrpc.newBlockingStub(channel); - stub.factoryReset(Empty.getDefaultInstance()); + try { + stub.factoryReset(Empty.getDefaultInstance()); + } catch (StatusRuntimeException e) { + if (e.getStatus().getCode() == Status.Code.UNAVAILABLE) { + // Server is shutting down, the call might be canceled with an UNAVAILABLE status + // because the stream is closed. + } else { + throw e; + } + } try { // terminate the channel channel.shutdown().awaitTermination(1, TimeUnit.SECONDS); diff --git a/framework/tests/bumble/src/android/bluetooth/pairing/PairingTest.java b/framework/tests/bumble/src/android/bluetooth/pairing/PairingTest.java index f9257ebf69..585c0d893e 100644 --- a/framework/tests/bumble/src/android/bluetooth/pairing/PairingTest.java +++ b/framework/tests/bumble/src/android/bluetooth/pairing/PairingTest.java @@ -22,8 +22,10 @@ import static androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra; import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.any; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import android.bluetooth.BluetoothAdapter; @@ -36,15 +38,22 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; +import android.os.ParcelUuid; +import android.platform.test.annotations.RequiresFlagsEnabled; +import android.platform.test.flag.junit.CheckFlagsRule; +import android.platform.test.flag.junit.DeviceFlagsValueProvider; +import android.util.Log; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; +import com.android.bluetooth.flags.Flags; import com.android.compatibility.common.util.AdoptShellPermissionsRule; import io.grpc.stub.StreamObserver; import org.hamcrest.Matcher; +import org.hamcrest.Matchers; import org.hamcrest.core.AllOf; import org.junit.After; import org.junit.Before; @@ -57,30 +66,50 @@ import org.mockito.MockitoAnnotations; import org.mockito.hamcrest.MockitoHamcrest; import java.time.Duration; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; +import pandora.GattProto; +import pandora.HostProto.AdvertiseRequest; +import pandora.HostProto.AdvertiseResponse; +import pandora.HostProto.OwnAddressType; +import pandora.SecurityProto.LESecurityLevel; import pandora.SecurityProto.PairingEvent; import pandora.SecurityProto.PairingEventAnswer; +import pandora.SecurityProto.SecureRequest; +import pandora.SecurityProto.SecureResponse; @RunWith(AndroidJUnit4.class) public class PairingTest { + private static final String TAG = "PairingTest"; private static final Duration BOND_INTENT_TIMEOUT = Duration.ofSeconds(10); + private static final ParcelUuid BATTERY_UUID = + ParcelUuid.fromString("0000180F-0000-1000-8000-00805F9B34FB"); + private static final Context sTargetContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); private static final BluetoothAdapter sAdapter = sTargetContext.getSystemService(BluetoothManager.class).getAdapter(); - @Rule public final AdoptShellPermissionsRule mPermissionRule = new AdoptShellPermissionsRule(); + @Rule(order = 0) + public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule(); + + @Rule(order = 1) + public final AdoptShellPermissionsRule mPermissionRule = new AdoptShellPermissionsRule(); - @Rule public final PandoraDevice mBumble = new PandoraDevice(); + @Rule(order = 2) + public final PandoraDevice mBumble = new PandoraDevice(); - @Rule + @Rule(order = 3) public final EnableBluetoothRule mEnableBluetoothRule = new EnableBluetoothRule(false /* enableTestMode */, true /* toggleBluetooth */); @Mock private BroadcastReceiver mReceiver; + private final Map<String, Integer> mActionRegistrationCounts = new HashMap<>(); private InOrder mInOrder = null; private BluetoothDevice mBumbleDevice; @@ -90,12 +119,30 @@ public class PairingTest { @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); - mInOrder = inOrder(mReceiver); - IntentFilter filter = new IntentFilter(); - filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); - filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST); - sTargetContext.registerReceiver(mReceiver, filter); + doAnswer( + inv -> { + Log.d( + TAG, + "onReceive(): intent=" + Arrays.toString(inv.getArguments())); + Intent intent = inv.getArgument(1); + String action = intent.getAction(); + if (BluetoothDevice.ACTION_UUID.equals(action)) { + ParcelUuid[] uuids = + intent.getParcelableArrayExtra( + BluetoothDevice.EXTRA_UUID, ParcelUuid.class); + Log.d(TAG, "onReceive(): UUID=" + Arrays.toString(uuids)); + } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { + int bondState = + intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1); + Log.d(TAG, "onReceive(): bondState=" + bondState); + } + return null; + }) + .when(mReceiver) + .onReceive(any(), any()); + + mInOrder = inOrder(mReceiver); mBumbleDevice = mBumble.getRemoteDevice(); Set<BluetoothDevice> bondedDevices = sAdapter.getBondedDevices(); @@ -111,7 +158,10 @@ public class PairingTest { removeBond(mBumbleDevice); } mBumbleDevice = null; - sTargetContext.unregisterReceiver(mReceiver); + if (getTotalActionRegistrationCounts() > 0) { + sTargetContext.unregisterReceiver(mReceiver); + mActionRegistrationCounts.clear(); + } } /** @@ -129,6 +179,9 @@ public class PairingTest { */ @Test public void testBrEdrPairing_phoneInitiatedBrEdrInquiryOnlyJustWorks() { + registerIntentActions( + BluetoothDevice.ACTION_BOND_STATE_CHANGED, BluetoothDevice.ACTION_PAIRING_REQUEST); + StreamObserver<PairingEventAnswer> pairingEventAnswerObserver = mBumble.security() .withDeadlineAfter(BOND_INTENT_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS) @@ -159,15 +212,219 @@ public class PairingTest { hasExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_BONDED)); verifyNoMoreInteractions(mReceiver); + + unregisterIntentActions( + BluetoothDevice.ACTION_BOND_STATE_CHANGED, BluetoothDevice.ACTION_PAIRING_REQUEST); + } + + /** + * Test if parallel GATT service discovery interrupts cancelling LE pairing + * + * <p>Prerequisites: + * + * <ol> + * <li>Bumble and Android are not bonded + * <li>Bumble has GATT services in addition to GAP and GATT services + * </ol> + * + * <p>Steps: + * + * <ol> + * <li>Bumble is discoverable and connectable over LE + * <li>Android connects to Bumble over LE + * <li>Android starts GATT service discovery + * <li>Bumble initiates pairing + * <li>Android does not confirm the pairing immediately + * <li>Service discovery completes + * <li>Android cancels the pairing + * </ol> + * + * Expectation: Pairing gets cancelled instead of getting timed out + */ + @Test + @RequiresFlagsEnabled(Flags.FLAG_RESET_PAIRING_ONLY_FOR_RELATED_SERVICE_DISCOVERY) + public void testCancelBondLe_WithGattServiceDiscovery() { + registerIntentActions(BluetoothDevice.ACTION_BOND_STATE_CHANGED); + + // Outgoing GATT service discovery and incoming LE pairing in parallel + StreamObserverSpliterator<SecureResponse> responseObserver = + helper_OutgoingGattServiceDiscoveryWithIncomingLePairing(); + + // Cancel pairing from Android + assertThat(mBumbleDevice.cancelBondProcess()).isTrue(); + + SecureResponse secureResponse = responseObserver.iterator().next(); + assertThat(secureResponse.hasPairingFailure()).isTrue(); + + // Pairing should be cancelled in a moment instead of timing out in 30 + // seconds + verifyIntentReceived( + hasAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED), + hasExtra(BluetoothDevice.EXTRA_DEVICE, mBumbleDevice), + hasExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE)); + + verifyNoMoreInteractions(mReceiver); + + unregisterIntentActions(BluetoothDevice.ACTION_BOND_STATE_CHANGED); + } + + /** + * Test if parallel GATT service discovery interrupts the LE pairing + * + * <p>Prerequisites: + * + * <ol> + * <li>Bumble and Android are not bonded + * <li>Bumble has GATT services in addition to GAP and GATT services + * </ol> + * + * <p>Steps: + * + * <ol> + * <li>Bumble is discoverable and connectable over LE + * <li>Android connects to Bumble over LE + * <li>Android starts GATT service discovery + * <li>Bumble starts pairing + * <li>Service discovery completes + * <li>Android does confirms the pairing + * <li>Pairing is successful + * </ol> + * + * Expectation: Pairing succeeds + */ + @Test + @RequiresFlagsEnabled(Flags.FLAG_RESET_PAIRING_ONLY_FOR_RELATED_SERVICE_DISCOVERY) + public void testBondLe_WithGattServiceDiscovery() { + registerIntentActions(BluetoothDevice.ACTION_BOND_STATE_CHANGED); + + // Outgoing GATT service discovery and incoming LE pairing in parallel + StreamObserverSpliterator<SecureResponse> responseObserver = + helper_OutgoingGattServiceDiscoveryWithIncomingLePairing(); + + // Approve pairing from Android + assertThat(mBumbleDevice.setPairingConfirmation(true)).isTrue(); + + SecureResponse secureResponse = responseObserver.iterator().next(); + assertThat(secureResponse.hasSuccess()).isTrue(); + + // Ensure that pairing succeeds + verifyIntentReceived( + hasAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED), + hasExtra(BluetoothDevice.EXTRA_DEVICE, mBumbleDevice), + hasExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_BONDED)); + + verifyNoMoreInteractions(mReceiver); + + unregisterIntentActions(BluetoothDevice.ACTION_BOND_STATE_CHANGED); + } + + /* Starts outgoing GATT service discovery and incoming LE pairing in parallel */ + private StreamObserverSpliterator<SecureResponse> + helper_OutgoingGattServiceDiscoveryWithIncomingLePairing() { + // Setup intent filters + registerIntentActions( + BluetoothDevice.ACTION_BOND_STATE_CHANGED, + BluetoothDevice.ACTION_PAIRING_REQUEST, + BluetoothDevice.ACTION_UUID, + BluetoothDevice.ACTION_ACL_CONNECTED); + + // Register lots of interesting GATT services on Bumble + for (int i = 0; i < 40; i++) { + mBumble.gattBlocking() + .registerService( + GattProto.RegisterServiceRequest.newBuilder() + .setService( + GattProto.GattServiceParams.newBuilder() + .setUuid(BATTERY_UUID.toString()) + .build()) + .build()); + } + + // Start GATT service discovery, this will establish LE ACL + assertThat(mBumbleDevice.fetchUuidsWithSdp(BluetoothDevice.TRANSPORT_LE)).isTrue(); + + // Make Bumble connectable + AdvertiseResponse advertiseResponse = + mBumble.hostBlocking() + .advertise( + AdvertiseRequest.newBuilder() + .setLegacy(true) + .setConnectable(true) + .setOwnAddressType(OwnAddressType.PUBLIC) + .build()) + .next(); + + // Todo: Unexpected empty ACTION_UUID intent is generated + verifyIntentReceived(hasAction(BluetoothDevice.ACTION_UUID)); + + // Wait for connection on Android + verifyIntentReceived( + hasAction(BluetoothDevice.ACTION_ACL_CONNECTED), + hasExtra(BluetoothDevice.EXTRA_TRANSPORT, BluetoothDevice.TRANSPORT_LE)); + + // Start pairing from Bumble + StreamObserverSpliterator<SecureResponse> responseObserver = + new StreamObserverSpliterator<>(); + mBumble.security() + .secure( + SecureRequest.newBuilder() + .setConnection(advertiseResponse.getConnection()) + .setLe(LESecurityLevel.LE_LEVEL3) + .build(), + responseObserver); + + // Wait for incoming pairing notification on Android + // TODO: Order of these events is not deterministic + verifyIntentReceivedUnordered( + hasAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED), + hasExtra(BluetoothDevice.EXTRA_DEVICE, mBumbleDevice), + hasExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_BONDING)); + verifyIntentReceivedUnordered( + hasAction(BluetoothDevice.ACTION_PAIRING_REQUEST), + hasExtra(BluetoothDevice.EXTRA_DEVICE, mBumbleDevice), + hasExtra( + BluetoothDevice.EXTRA_PAIRING_VARIANT, + BluetoothDevice.PAIRING_VARIANT_CONSENT)); + + // Allow participating in the incoming pairing on Android + assertThat(mBumbleDevice.setPairingConfirmation(true)).isTrue(); + + // Wait for pairing approval notification on Android + verifyIntentReceivedUnordered( + 2, + hasAction(BluetoothDevice.ACTION_PAIRING_REQUEST), + hasExtra(BluetoothDevice.EXTRA_DEVICE, mBumbleDevice), + hasExtra( + BluetoothDevice.EXTRA_PAIRING_VARIANT, + BluetoothDevice.PAIRING_VARIANT_CONSENT)); + + // Wait for GATT service discovery to complete on Android + // so that ACTION_UUID is received here. + verifyIntentReceived( + hasAction(BluetoothDevice.ACTION_UUID), + hasExtra( + BluetoothDevice.EXTRA_UUID, + Matchers.arrayContainingInAnyOrder(BATTERY_UUID))); + + unregisterIntentActions( + BluetoothDevice.ACTION_BOND_STATE_CHANGED, + BluetoothDevice.ACTION_PAIRING_REQUEST, + BluetoothDevice.ACTION_UUID, + BluetoothDevice.ACTION_ACL_CONNECTED); + + return responseObserver; } private void removeBond(BluetoothDevice device) { + registerIntentActions(BluetoothDevice.ACTION_BOND_STATE_CHANGED); + assertThat(device.removeBond()).isTrue(); verifyIntentReceived( hasAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED), hasExtra(BluetoothDevice.EXTRA_DEVICE, mBumbleDevice), hasExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE)); - verifyNoMoreInteractions(mReceiver); + + unregisterIntentActions(BluetoothDevice.ACTION_BOND_STATE_CHANGED); } @SafeVarargs @@ -175,4 +432,95 @@ public class PairingTest { mInOrder.verify(mReceiver, timeout(BOND_INTENT_TIMEOUT.toMillis())) .onReceive(any(Context.class), MockitoHamcrest.argThat(AllOf.allOf(matchers))); } + + @SafeVarargs + private void verifyIntentReceivedUnordered(int num, Matcher<Intent>... matchers) { + verify(mReceiver, timeout(BOND_INTENT_TIMEOUT.toMillis()).times(num)) + .onReceive(any(Context.class), MockitoHamcrest.argThat(AllOf.allOf(matchers))); + } + + @SafeVarargs + private void verifyIntentReceivedUnordered(Matcher<Intent>... matchers) { + verifyIntentReceivedUnordered(1, matchers); + } + + /** + * Helper function to add reference count to registered intent actions + * + * @param actions new intent actions to add. If the array is empty, it is a no-op. + */ + private void registerIntentActions(String... actions) { + if (actions.length == 0) { + return; + } + if (getTotalActionRegistrationCounts() > 0) { + Log.d(TAG, "registerIntentActions(): unregister ALL intents"); + sTargetContext.unregisterReceiver(mReceiver); + } + for (String action : actions) { + mActionRegistrationCounts.merge(action, 1, Integer::sum); + } + IntentFilter filter = new IntentFilter(); + mActionRegistrationCounts.entrySet().stream() + .filter(entry -> entry.getValue() > 0) + .forEach( + entry -> { + Log.d( + TAG, + "registerIntentActions(): Registering action = " + + entry.getKey()); + filter.addAction(entry.getKey()); + }); + sTargetContext.registerReceiver(mReceiver, filter); + } + + /** + * Helper function to reduce reference count to registered intent actions If total reference + * count is zero after removal, no broadcast receiver will be registered. + * + * @param actions intent actions to be removed. If some action is not registered, it is no-op + * for that action. If the actions array is empty, it is also a no-op. + */ + private void unregisterIntentActions(String... actions) { + if (actions.length == 0) { + return; + } + if (getTotalActionRegistrationCounts() <= 0) { + return; + } + Log.d(TAG, "unregisterIntentActions(): unregister ALL intents"); + sTargetContext.unregisterReceiver(mReceiver); + for (String action : actions) { + if (!mActionRegistrationCounts.containsKey(action)) { + continue; + } + mActionRegistrationCounts.put(action, mActionRegistrationCounts.get(action) - 1); + if (mActionRegistrationCounts.get(action) <= 0) { + mActionRegistrationCounts.remove(action); + } + } + if (getTotalActionRegistrationCounts() > 0) { + IntentFilter filter = new IntentFilter(); + mActionRegistrationCounts.entrySet().stream() + .filter(entry -> entry.getValue() > 0) + .forEach( + entry -> { + Log.d( + TAG, + "unregisterIntentActions(): Registering action = " + + entry.getKey()); + filter.addAction(entry.getKey()); + }); + sTargetContext.registerReceiver(mReceiver, filter); + } + } + + /** + * Get sum of reference count from all registered actions + * + * @return sum of reference count from all registered actions + */ + private int getTotalActionRegistrationCounts() { + return mActionRegistrationCounts.values().stream().reduce(0, Integer::sum); + } } diff --git a/service/generate_local_coverage.sh b/service/generate_local_coverage.sh index 38dbc88ace..83e1138cbd 100755 --- a/service/generate_local_coverage.sh +++ b/service/generate_local_coverage.sh @@ -13,7 +13,7 @@ script -q ${COVERAGE_TMP_FOLDER}/atest_log \ --jacocoagent-path gs://tradefed_test_resources/teams/code_coverage/jacocoagent.jar \ --coverage --coverage-toolchain JACOCO' -COVERAGE_COLLECTED=$(rg 'Test Logs have saved in ' ${COVERAGE_TMP_FOLDER}/atest_log | sed -e 's/^.* //' -e 's/log.*$/log/') +COVERAGE_COLLECTED=$(rg 'Test Logs have been saved in ' ${COVERAGE_TMP_FOLDER}/atest_log | sed -e 's/^.* //' -e 's/log.*$/log/') # Link source into the tmp folder ln -s "${ANDROID_BUILD_TOP}"/packages/modules/Bluetooth/service/src ${COVERAGE_TMP_FOLDER}/com/android/server/bluetooth diff --git a/service/src/com/android/server/bluetooth/BluetoothAirplaneModeListener.java b/service/src/com/android/server/bluetooth/BluetoothAirplaneModeListener.java index 45aa7365e1..64eefcb311 100644 --- a/service/src/com/android/server/bluetooth/BluetoothAirplaneModeListener.java +++ b/service/src/com/android/server/bluetooth/BluetoothAirplaneModeListener.java @@ -227,9 +227,9 @@ class BluetoothAirplaneModeListener extends Handler { } else { if (mFeatureFlags.airplaneRessourcesInApp()) { if (isWifiEnabledOnApm()) { - mBluetoothManager.sendAirplaneModeNotification(APM_WIFI_BT_NOTIFICATION); + mBluetoothManager.sendToggleNotification(APM_WIFI_BT_NOTIFICATION); } else { - mBluetoothManager.sendAirplaneModeNotification(APM_BT_NOTIFICATION); + mBluetoothManager.sendToggleNotification(APM_BT_NOTIFICATION); } return; } @@ -330,7 +330,7 @@ class BluetoothAirplaneModeListener extends Handler { setSettingsSecureInt(APM_USER_TOGGLED_BLUETOOTH, USED); if (mFeatureFlags.airplaneRessourcesInApp()) { if (isOn) { - mBluetoothManager.sendAirplaneModeNotification(APM_BT_ENABLED_NOTIFICATION); + mBluetoothManager.sendToggleNotification(APM_BT_ENABLED_NOTIFICATION); } return; } diff --git a/service/src/com/android/server/bluetooth/BluetoothManagerService.java b/service/src/com/android/server/bluetooth/BluetoothManagerService.java index 945613acb9..32497dd4bc 100644 --- a/service/src/com/android/server/bluetooth/BluetoothManagerService.java +++ b/service/src/com/android/server/bluetooth/BluetoothManagerService.java @@ -115,11 +115,11 @@ class BluetoothManagerService { private static final int DEFAULT_REBIND_COUNT = 3; // Maximum msec to wait for a bind private static final int TIMEOUT_BIND_MS = - 3000 * SystemProperties.getInt("ro.hw_timeout_multiplier", 1); + 3000 * SystemProperties.getInt("ro.hw_timeout_multiplier", 1); // Timeout value for synchronous binder call private static final Duration SYNC_CALLS_TIMEOUT = - Duration.ofSeconds(3 * SystemProperties.getInt("ro.hw_timeout_multiplier", 1)); + Duration.ofSeconds(3 * SystemProperties.getInt("ro.hw_timeout_multiplier", 1)); /** * @return timeout value for synchronous binder call @@ -129,20 +129,20 @@ class BluetoothManagerService { } // Maximum msec to wait for service restart - private static final int SERVICE_RESTART_TIME_MS - = 400 * SystemProperties.getInt("ro.hw_timeout_multiplier", 1); + private static final int SERVICE_RESTART_TIME_MS = + 400 * SystemProperties.getInt("ro.hw_timeout_multiplier", 1); // Maximum msec to wait for restart due to error - private static final int ERROR_RESTART_TIME_MS - = 3000 * SystemProperties.getInt("ro.hw_timeout_multiplier", 1); + private static final int ERROR_RESTART_TIME_MS = + 3000 * SystemProperties.getInt("ro.hw_timeout_multiplier", 1); // Maximum msec to delay MESSAGE_USER_SWITCHED - private static final int USER_SWITCHED_TIME_MS - = 200 * SystemProperties.getInt("ro.hw_timeout_multiplier", 1); + private static final int USER_SWITCHED_TIME_MS = + 200 * SystemProperties.getInt("ro.hw_timeout_multiplier", 1); // Delay for the addProxy function in msec - private static final int ADD_PROXY_DELAY_MS - = 100 * SystemProperties.getInt("ro.hw_timeout_multiplier", 1); + private static final int ADD_PROXY_DELAY_MS = + 100 * SystemProperties.getInt("ro.hw_timeout_multiplier", 1); // Delay for retrying enable and disable in msec - private static final int ENABLE_DISABLE_DELAY_MS - = 300 * SystemProperties.getInt("ro.hw_timeout_multiplier", 1); + private static final int ENABLE_DISABLE_DELAY_MS = + 300 * SystemProperties.getInt("ro.hw_timeout_multiplier", 1); @VisibleForTesting static final int MESSAGE_ENABLE = 1; @VisibleForTesting static final int MESSAGE_DISABLE = 2; @@ -429,10 +429,12 @@ class BluetoothManagerService { } /** Send Intent to the Notification Service in the Bluetooth app */ - Unit sendAirplaneModeNotification(String notificationState) { - Intent intent = new Intent("android.bluetooth.airplane.action.SEND_NOTIFICATION"); + Unit sendToggleNotification(String notificationReason) { + Intent intent = + new Intent("android.bluetooth.notification.action.SEND_TOGGLE_NOTIFICATION"); intent.setComponent(resolveSystemService(intent)); - intent.putExtra("android.bluetooth.airplane.extra.NOTIFICATION_STATE", notificationState); + intent.putExtra( + "android.bluetooth.notification.extra.NOTIFICATION_REASON", notificationReason); mContext.startService(intent); return Unit.INSTANCE; } @@ -652,7 +654,6 @@ class BluetoothManagerService { mBinder = new BluetoothServiceBinder(this, mLooper, mContext, mUserManager); mHandler = new BluetoothHandler(mLooper); - // Observe BLE scan only mode settings change. registerForBleScanModeChange(); @@ -1041,7 +1042,6 @@ class BluetoothManagerService { return false; } - // TODO(b/262605980): enableBle/disableBle should be on handler thread updateBleAppCount(token, true, packageName); @@ -1295,17 +1295,17 @@ class BluetoothManagerService { @VisibleForTesting void initialize(UserHandle userHandle) { + mCurrentUserContext = + requireNonNull( + mContext.createContextAsUser(userHandle, 0), + "Current User Context cannot be null"); if (mUseNewAirplaneMode) { - mCurrentUserContext = - requireNonNull( - mContext.createContextAsUser(userHandle, 0), - "Current User Context cannot be null"); AirplaneModeListener.initialize( mLooper, mContentResolver, mState, this::onAirplaneModeChanged, - this::sendAirplaneModeNotification, + this::sendToggleNotification, this::isMediaProfileConnected, this::getCurrentUserContext, TimeSource.Monotonic.INSTANCE); @@ -1936,9 +1936,7 @@ class BluetoothManagerService { mBluetoothNotificationManager.createNotificationChannels(); } - if (mUseNewAirplaneMode) { - mCurrentUserContext = mContext.createContextAsUser(userTo, 0); - } + mCurrentUserContext = mContext.createContextAsUser(userTo, 0); /* disable and enable BT when detect a user switch */ if (mAdapter != null && mState.oneOf(STATE_ON)) { diff --git a/service/tests/src/com/android/server/bluetooth/BluetoothAirplaneModeListenerTest.java b/service/tests/src/com/android/server/bluetooth/BluetoothAirplaneModeListenerTest.java index d25ba428a7..1c60d8a5a8 100644 --- a/service/tests/src/com/android/server/bluetooth/BluetoothAirplaneModeListenerTest.java +++ b/service/tests/src/com/android/server/bluetooth/BluetoothAirplaneModeListenerTest.java @@ -241,7 +241,7 @@ public class BluetoothAirplaneModeListenerTest { mBluetoothAirplaneModeListener.handleAirplaneModeChange(true); - verify(mBluetoothManagerService).sendAirplaneModeNotification(eq(APM_WIFI_BT_NOTIFICATION)); + verify(mBluetoothManagerService).sendToggleNotification(eq(APM_WIFI_BT_NOTIFICATION)); } @Test @@ -287,7 +287,7 @@ public class BluetoothAirplaneModeListenerTest { mBluetoothAirplaneModeListener.handleAirplaneModeChange(true); - verify(mBluetoothManagerService).sendAirplaneModeNotification(eq(APM_BT_NOTIFICATION)); + verify(mBluetoothManagerService).sendToggleNotification(eq(APM_BT_NOTIFICATION)); } @Test diff --git a/system/BUILD.gn b/system/BUILD.gn index 02b92d245b..62ced34597 100644 --- a/system/BUILD.gn +++ b/system/BUILD.gn @@ -174,6 +174,10 @@ config("external_flatbuffers") { libs = [ "flatbuffers" ] } +config("external_fmtlib") { + configs = [ ":pkg_fmtlib" ] +} + # Package configurations to extract dependencies from env pkg_config("pkg_gtest") { pkg_deps = [ "gtest" ] @@ -203,6 +207,10 @@ pkg_config("pkg_tinyxml2") { pkg_deps = [ "tinyxml2" ] } +pkg_config("pkd_fmtlib") { + pkg_deps = [ "fmt" ] +} + # To include ChroemOS-specific libraries and build dependencies. if (target_os == "chromeos") { config("external_chromeos") { diff --git a/system/audio_a2dp_hw/Android.bp b/system/audio_a2dp_hw/Android.bp index d75554928d..63b486093a 100644 --- a/system/audio_a2dp_hw/Android.bp +++ b/system/audio_a2dp_hw/Android.bp @@ -38,6 +38,7 @@ cc_library { ], static_libs: [ "libbluetooth_gd", + "libbluetooth_log", "libosi", ], } @@ -52,6 +53,9 @@ cc_library_static { apex_available: [ "com.android.btservices", ], + static_libs: [ + "libbluetooth_log", + ], min_sdk_version: "29", } @@ -71,6 +75,7 @@ cc_test { ], static_libs: [ "audio.a2dp.default", + "libbluetooth_log", "libosi", ], min_sdk_version: "29", diff --git a/system/audio_hal_interface/Android.bp b/system/audio_hal_interface/Android.bp index 2d538e46c4..96d05bf2bc 100644 --- a/system/audio_hal_interface/Android.bp +++ b/system/audio_hal_interface/Android.bp @@ -26,6 +26,7 @@ cc_library_static { ], static_libs: [ "bluetooth_flags_c_lib", + "libbluetooth_log", "libbt-common", "libbt_shim_bridge", "libosi", @@ -108,6 +109,7 @@ cc_test { "libutils", ], static_libs: [ + "libbluetooth_log", "libbt-audio-hal-interface", "libbt-common", "libbt_shim_bridge", diff --git a/system/audio_hal_interface/aidl/a2dp_encoding_aidl.cc b/system/audio_hal_interface/aidl/a2dp_encoding_aidl.cc index 8ea0c32a98..a929d802b8 100644 --- a/system/audio_hal_interface/aidl/a2dp_encoding_aidl.cc +++ b/system/audio_hal_interface/aidl/a2dp_encoding_aidl.cc @@ -762,7 +762,7 @@ static btav_a2dp_codec_channel_mode_t convert_channel_mode( case ChannelMode::MONO: return BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; case ChannelMode::STEREO: - return BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; + return BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; default: LOG(ERROR) << "unknown channel mode"; break; 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 3168bea249..08033e996c 100644 --- a/system/audio_hal_interface/aidl/le_audio_software_aidl.cc +++ b/system/audio_hal_interface/aidl/le_audio_software_aidl.cc @@ -66,7 +66,8 @@ LeAudioTransport::LeAudioTransport(void (*flush)(void), total_bytes_processed_(0), data_position_({}), pcm_config_(std::move(pcm_config)), - start_request_state_(StartRequestState::IDLE){}; + start_request_state_(StartRequestState::IDLE), + dsa_mode_(DsaMode::DISABLED){}; BluetoothAudioCtrlAck LeAudioTransport::StartRequest(bool is_low_latency) { // Check if operation is pending already diff --git a/system/audio_hal_interface/fuzzer/Android.bp b/system/audio_hal_interface/fuzzer/Android.bp index 9cccfb60ca..fa21731b33 100644 --- a/system/audio_hal_interface/fuzzer/Android.bp +++ b/system/audio_hal_interface/fuzzer/Android.bp @@ -60,6 +60,7 @@ cc_defaults { "libbluetooth_core_rs", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbluetooth_rust_interop", "libbt-audio-hal-interface", "libbt-bta", diff --git a/system/audio_hal_interface/le_audio_software.cc b/system/audio_hal_interface/le_audio_software.cc index c53b6b6c92..35a85d4813 100644 --- a/system/audio_hal_interface/le_audio_software.cc +++ b/system/audio_hal_interface/le_audio_software.cc @@ -19,6 +19,8 @@ #include "le_audio_software.h" +#include <android_bluetooth_flags.h> + #include <unordered_map> #include <vector> @@ -868,8 +870,18 @@ bool LeAudioClientInterface::ReleaseSource( } void LeAudioClientInterface::SetAllowedDsaModes(DsaModes dsa_modes) { + if (!IS_FLAG_ENABLED(leaudio_dynamic_spatial_audio)) { + return; + } + if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::AIDL) { + if (aidl::le_audio::LeAudioSinkTransport::interface_unicast_ == nullptr || + aidl::le_audio::LeAudioSinkTransport::instance_unicast_ == nullptr) { + LOG(WARNING) << __func__ << ": LeAudioSourceTransport::interface is null"; + return; + } + std::vector<LatencyMode> latency_modes = {LatencyMode::FREE}; for (auto dsa_mode : dsa_modes) { switch (dsa_mode) { @@ -890,12 +902,8 @@ void LeAudioClientInterface::SetAllowedDsaModes(DsaModes dsa_modes) { break; } } - if (aidl::le_audio::LeAudioSourceTransport::interface) { - aidl::le_audio::LeAudioSourceTransport::interface->SetAllowedLatencyModes( - latency_modes); - } else { - LOG(WARNING) << "LeAudioSourceTransport::interface is null"; - } + aidl::le_audio::LeAudioSinkTransport::interface_unicast_ + ->SetAllowedLatencyModes(latency_modes); } } diff --git a/system/audio_hearing_aid_hw/Android.bp b/system/audio_hearing_aid_hw/Android.bp index 920bfa7a0b..8c7c865c74 100644 --- a/system/audio_hearing_aid_hw/Android.bp +++ b/system/audio_hearing_aid_hw/Android.bp @@ -34,7 +34,10 @@ cc_library { shared_libs: [ "liblog", ], - static_libs: ["libosi"], + static_libs: [ + "libbluetooth_log", + "libosi", + ], } // Audio A2DP library unit tests for target and host @@ -53,6 +56,7 @@ cc_test { ], static_libs: [ "audio.hearing_aid.default", + "libbluetooth_log", "libosi", ], min_sdk_version: "29", diff --git a/system/bta/Android.bp b/system/bta/Android.bp index e301c736f1..fcaae4029a 100644 --- a/system/bta/Android.bp +++ b/system/bta/Android.bp @@ -137,6 +137,7 @@ cc_library_static { "lib-bt-packets", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-audio-asrc", "libbt-bta-core", "libbt-platform-protos-lite", @@ -204,6 +205,7 @@ cc_library_static { "bluetooth_flags_c_lib", "lib-bt-packets", "libbase", + "libbluetooth_log", "libbt-audio-hal-interface", "libbt-platform-protos-lite", "libbt_shim_bridge", @@ -286,6 +288,7 @@ cc_test { "libbluetooth_crypto_toolbox", "libbluetooth_gd", "libbluetooth_hci_pdl", + "libbluetooth_log", "libbt-audio-hal-interface", "libbt-bta", "libbt-bta-core", @@ -351,6 +354,7 @@ cc_test { "libbluetooth_crypto_toolbox", "libbluetooth_gd", "libbluetooth_hci_pdl", + "libbluetooth_log", "libbt-audio-hal-interface", "libbt-bta", "libbt-bta-core", @@ -396,6 +400,7 @@ cc_test { "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-audio-hal-interface", "libbt-bta", "libbt-bta-core", @@ -450,6 +455,7 @@ cc_test { static_libs: [ "bluetooth_flags_c_lib", "libbluetooth-types", + "libbluetooth_log", "libbt-common", "libbt-platform-protos-lite", "libbt_shim_bridge", @@ -516,6 +522,7 @@ cc_test { "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt_shim_bridge", "libbt_shim_ffi", @@ -564,6 +571,7 @@ cc_test { "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt_shim_bridge", "libbt_shim_ffi", @@ -622,6 +630,7 @@ cc_test { "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt-platform-protos-lite", "libbt_shim_bridge", @@ -770,6 +779,7 @@ cc_test { "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt_shim_bridge", "libbt_shim_ffi", @@ -872,6 +882,7 @@ cc_test { "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-audio-asrc", "libbt-common", "libbt-platform-protos-lite", @@ -956,6 +967,7 @@ cc_test { "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-audio-hal-interface", "libbt-common", "libbt-platform-protos-lite", @@ -1035,6 +1047,7 @@ cc_test { "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt_shim_bridge", "libbt_shim_ffi", @@ -1100,6 +1113,7 @@ cc_test { ], static_libs: [ "libbluetooth-types", + "libbluetooth_log", "libbt-audio-hal-interface", "libbt-common", "libbt_shim_bridge", @@ -1165,6 +1179,7 @@ cc_test { "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt_shim_bridge", "libbt_shim_ffi", @@ -1232,6 +1247,7 @@ cc_test { "libbluetooth_crypto_toolbox", "libbluetooth_gd", "libbluetooth_hci_pdl", + "libbluetooth_log", "libbt-common", "libbt-platform-protos-lite", "libbt_shim_bridge", diff --git a/system/bta/BUILD.gn b/system/bta/BUILD.gn index 261b9a7dde..18187047ff 100644 --- a/system/bta/BUILD.gn +++ b/system/bta/BUILD.gn @@ -151,7 +151,8 @@ static_library("bta") { ] configs += [ - "//bt/system:target_defaults" + "//bt/system:target_defaults", + "//bt/system/log:log_defaults", ] deps = [ diff --git a/system/bta/ag/bta_ag_act.cc b/system/bta/ag/bta_ag_act.cc index fd47bcc4ce..a79e078e12 100644 --- a/system/bta/ag/bta_ag_act.cc +++ b/system/bta/ag/bta_ag_act.cc @@ -46,6 +46,7 @@ #include "stack/include/l2c_api.h" #include "stack/include/port_api.h" #include "stack/include/sdp_api.h" +#include "storage/config_keys.h" #include "types/raw_address.h" using namespace bluetooth::legacy::stack::sdp; @@ -486,7 +487,7 @@ void bta_ag_rfc_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { if (p_scb->conn_service == BTA_AG_HFP) { size_t version_value_size = sizeof(p_scb->peer_version); if (!btif_config_get_bin( - p_scb->peer_addr.ToString(), HFP_VERSION_CONFIG_KEY, + p_scb->peer_addr.ToString(), BTIF_STORAGE_KEY_HFP_VERSION, (uint8_t*)&p_scb->peer_version, &version_value_size)) { LOG_WARN("%s: Failed read cached peer HFP version for %s", __func__, ADDRESS_TO_LOGGABLE_CSTR(p_scb->peer_addr)); @@ -494,7 +495,7 @@ void bta_ag_rfc_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { } size_t sdp_features_size = sizeof(p_scb->peer_sdp_features); if (btif_config_get_bin( - p_scb->peer_addr.ToString(), HFP_SDP_FEATURES_CONFIG_KEY, + p_scb->peer_addr.ToString(), BTIF_STORAGE_KEY_HFP_SDP_FEATURES, (uint8_t*)&p_scb->peer_sdp_features, &sdp_features_size)) { bool sdp_wbs_support = p_scb->peer_sdp_features & BTA_AG_FEAT_WBS_SUPPORT; if (!p_scb->received_at_bac && sdp_wbs_support) { @@ -621,9 +622,9 @@ void bta_ag_rfc_acp_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { p_scb, (p_scb->reg_services & ~bta_ag_svc_mask[p_scb->conn_service])); size_t version_value_size = sizeof(hfp_version); - bool get_version = - btif_config_get_bin(p_scb->peer_addr.ToString(), HFP_VERSION_CONFIG_KEY, - (uint8_t*)&hfp_version, &version_value_size); + bool get_version = btif_config_get_bin( + p_scb->peer_addr.ToString(), BTIF_STORAGE_KEY_HFP_VERSION, + (uint8_t*)&hfp_version, &version_value_size); if (p_scb->conn_service == BTA_AG_HFP && get_version) { DEVICE_IOT_CONFIG_ADDR_SET_HEX_IF_GREATER(p_scb->peer_addr, diff --git a/system/bta/ag/bta_ag_sdp.cc b/system/bta/ag/bta_ag_sdp.cc index 1314cc4b9a..bbc6b71f6e 100644 --- a/system/bta/ag/bta_ag_sdp.cc +++ b/system/bta/ag/bta_ag_sdp.cc @@ -43,6 +43,7 @@ #include "stack/include/bt_uuid16.h" #include "stack/include/main_thread.h" #include "stack/include/sdp_api.h" +#include "storage/config_keys.h" #include "types/bluetooth/uuid.h" using namespace bluetooth::legacy::stack::sdp; @@ -390,7 +391,7 @@ bool bta_ag_sdp_find_attr(tBTA_AG_SCB* p_scb, tBTA_SERVICE_MASK service) { if (peer_version != p_scb->peer_version) { p_scb->peer_version = peer_version; if (btif_config_set_bin( - p_scb->peer_addr.ToString(), HFP_VERSION_CONFIG_KEY, + p_scb->peer_addr.ToString(), BTIF_STORAGE_KEY_HFP_VERSION, (const uint8_t*)&peer_version, sizeof(peer_version))) { } else { LOG_WARN("%s: Failed to store peer HFP version for %s", __func__, @@ -419,9 +420,10 @@ bool bta_ag_sdp_find_attr(tBTA_AG_SCB* p_scb, tBTA_SERVICE_MASK service) { } if (sdp_features != p_scb->peer_sdp_features) { p_scb->peer_sdp_features = sdp_features; - if (btif_config_set_bin( - p_scb->peer_addr.ToString(), HFP_SDP_FEATURES_CONFIG_KEY, - (const uint8_t*)&sdp_features, sizeof(sdp_features))) { + if (btif_config_set_bin(p_scb->peer_addr.ToString(), + BTIF_STORAGE_KEY_HFP_SDP_FEATURES, + (const uint8_t*)&sdp_features, + sizeof(sdp_features))) { } else { LOG_WARN("%s: Failed to store peer HFP SDP Features for %s", __func__, ADDRESS_TO_LOGGABLE_CSTR(p_scb->peer_addr)); diff --git a/system/bta/av/bta_av_aact.cc b/system/bta/av/bta_av_aact.cc index 993ed8b991..5b191024c8 100644 --- a/system/bta/av/bta_av_aact.cc +++ b/system/bta/av/bta_av_aact.cc @@ -57,6 +57,7 @@ #include "stack/include/btm_client_interface.h" #include "stack/include/btm_log_history.h" #include "stack/include/l2c_api.h" +#include "storage/config_keys.h" #include "types/hci_role.h" #include "types/raw_address.h" @@ -544,7 +545,7 @@ static void bta_av_a2dp_sdp_cback(bool found, tA2DP_Service* p_service, if (p_service->avdt_version != 0) { if (btif_config_set_bin(p_scb->PeerAddress().ToString(), - AVDTP_VERSION_CONFIG_KEY, + BTIF_STORAGE_KEY_AVDTP_VERSION, (const uint8_t*)&p_service->avdt_version, sizeof(p_service->avdt_version))) { } else { diff --git a/system/bta/av/bta_av_cfg.cc b/system/bta/av/bta_av_cfg.cc index 69a490ed90..c76d1ef4fc 100644 --- a/system/bta/av/bta_av_cfg.cc +++ b/system/bta/av/bta_av_cfg.cc @@ -44,7 +44,6 @@ const uint32_t bta_av_meta_caps_co_ids[] = {AVRC_CO_METADATA, AVRC_CO_BROADCOM}; #define BTA_AVK_RC_SUPF_CT \ (AVRC_SUPF_CT_CAT1 | AVRC_SUPF_CT_BROWSE | \ AVRC_SUPF_CT_COVER_ART_GET_IMAGE_PROP | AVRC_SUPF_CT_COVER_ART_GET_IMAGE) -#define BTA_AVK_RC_SUPF_CT_V15 (AVRC_SUPF_CT_CAT1 | AVRC_SUPF_CT_BROWSE) #define BTA_AVK_RC_SUPF_TG (AVRC_SUPF_TG_CAT2) @@ -140,10 +139,10 @@ extern const tBTA_AV_CFG bta_av_cfg = { const tBTA_AV_CFG* get_bta_avk_cfg() { static const tBTA_AV_CFG bta_avk_cfg = { - AVRC_CO_METADATA, /* AVRCP Company ID */ - BTA_AVK_RC_SUPF_CT_V15, /* AVRCP controller categories */ - BTA_AVK_RC_SUPF_TG, /* AVRCP target categories */ - 6, /* AVDTP audio channel max data queue size */ + AVRC_CO_METADATA, /* AVRCP Company ID */ + BTA_AVK_RC_SUPF_CT, /* AVRCP controller categories */ + BTA_AVK_RC_SUPF_TG, /* AVRCP target categories */ + 6, /* AVDTP audio channel max data queue size */ false, /* true, to accept AVRC 1.3 group nevigation command */ 2, /* company id count in p_meta_co_ids */ (uint8_t)(avrcp_absolute_volume_is_enabled() diff --git a/system/bta/av/bta_av_main.cc b/system/bta/av/bta_av_main.cc index b9fb850234..ccdb9b4e9a 100644 --- a/system/bta/av/bta_av_main.cc +++ b/system/bta/av/bta_av_main.cc @@ -47,6 +47,7 @@ #include "stack/include/bt_uuid16.h" #include "stack/include/hci_error_code.h" #include "stack/include/sdp_api.h" +#include "storage/config_keys.h" #include "types/hci_role.h" #include "types/raw_address.h" @@ -361,7 +362,8 @@ void tBTA_AV_SCB::OnConnected(const RawAddress& peer_address) { // Read and restore the AVDTP version from local storage uint16_t avdtp_version = 0; size_t version_value_size = sizeof(avdtp_version); - if (!btif_config_get_bin(peer_address_.ToString(), AVDTP_VERSION_CONFIG_KEY, + if (!btif_config_get_bin(peer_address_.ToString(), + BTIF_STORAGE_KEY_AVDTP_VERSION, (uint8_t*)&avdtp_version, &version_value_size)) { LOG_WARN("%s: Failed to read cached peer AVDTP version for %s", __func__, ADDRESS_TO_LOGGABLE_CSTR(peer_address_)); diff --git a/system/bta/csis/csis_client.cc b/system/bta/csis/csis_client.cc index a346c5a69e..9328de7ea9 100644 --- a/system/bta/csis/csis_client.cc +++ b/system/bta/csis/csis_client.cc @@ -233,16 +233,14 @@ class CsisClientImpl : public CsisClient { csis_group->SetUuid(uuid); } + int rank = bluetooth::csis::CSIS_RANK_INVALID; auto csis_instance = device->GetCsisInstanceByGroupId(group_id); - if (!csis_instance) { - LOG_ERROR(" device: %s, does not have the rank info for group (id: %d )", - ADDRESS_TO_LOGGABLE_CSTR(address), group_id); - return; + if (csis_instance) { + rank = csis_instance->GetRank(); } callbacks_->OnDeviceAvailable(device->addr, csis_group->GetGroupId(), - csis_group->GetDesiredSize(), - csis_instance->GetRank(), uuid); + csis_group->GetDesiredSize(), rank, uuid); } void Connect(const RawAddress& address) override { @@ -261,8 +259,6 @@ class CsisClientImpl : public CsisClient { void Disconnect(const RawAddress& addr) override { LOG_DEBUG("%s ", ADDRESS_TO_LOGGABLE_CSTR(addr)); - btif_storage_set_csis_autoconnect(addr, false); - auto device = FindDeviceByAddress(addr); if (device == nullptr) { LOG_WARN("Device not connected to profile %s", @@ -658,17 +654,26 @@ class CsisClientImpl : public CsisClient { return group_rank_map; } - void AddFromStorage(const RawAddress& addr, const std::vector<uint8_t>& in, - bool autoconnect) { + void StartOpportunisticConnect(const RawAddress& address) { + /* Oportunistic works only for direct connect, + * but in fact this is background connect + */ + LOG_INFO(": %s ", ADDRESS_TO_LOGGABLE_CSTR(address)); + BTA_GATTC_Open(gatt_if_, address, BTM_BLE_DIRECT_CONNECTION, true); + } + + void AddFromStorage(const RawAddress& addr, const std::vector<uint8_t>& in) { auto group_rank_map = DeserializeSets(addr, in); + LOG_DEBUG(" %s, number of groups %d", ADDRESS_TO_LOGGABLE_CSTR(addr), + static_cast<int>(csis_groups_.size())); + auto device = FindDeviceByAddress(addr); if (device == nullptr) { device = std::make_shared<CsisDevice>(addr, false); devices_.push_back(device); } - bool is_le_audio_device = false; for (const auto& csis_group : csis_groups_) { if (!csis_group->IsDeviceInTheGroup(device)) continue; @@ -682,21 +687,11 @@ class CsisClientImpl : public CsisClient { callbacks_->OnDeviceAvailable(device->addr, group_id, csis_group->GetDesiredSize(), rank, csis_group->GetUuid()); - - if (csis_group->GetUuid() == - bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE)) { - is_le_audio_device = true; - } } } - /* For now, if this is LeAudio device, CSIP is opportunistic profile. */ - bool is_opportunistic = is_le_audio_device; - - if (autoconnect) { - BTA_GATTC_Open(gatt_if_, addr, BTM_BLE_BKG_CONNECT_ALLOW_LIST, - is_opportunistic); - } + /* For bonded devices, CSIP can be always opportunistic service */ + StartOpportunisticConnect(addr); } void CleanUp() { @@ -915,11 +910,6 @@ class CsisClientImpl : public CsisClient { } } } - - if (device->first_connection) { - device->first_connection = false; - btif_storage_set_csis_autoconnect(device->addr, true); - } } void OnGattWriteCcc(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, @@ -2142,7 +2132,6 @@ class CsisClientImpl : public CsisClient { if (device->is_gatt_service_valid) { instance->OnEncrypted(device); } else { - device->first_connection = true; BTA_GATTC_ServiceSearchRequest(device->conn_id, &kCsisServiceUuid); } } @@ -2157,7 +2146,6 @@ class CsisClientImpl : public CsisClient { /* Invalidate service discovery results */ BtaGattQueue::Clean(device->conn_id); - device->first_connection = true; DeregisterNotifications(device); device->ClearSvcData(); BTA_GATTC_ServiceSearchRequest(device->conn_id, &kCsisServiceUuid); @@ -2409,14 +2397,13 @@ CsisClient* CsisClient::Get(void) { } void CsisClient::AddFromStorage(const RawAddress& addr, - const std::vector<uint8_t>& in, - bool autoconnect) { + const std::vector<uint8_t>& in) { if (!instance) { LOG_ERROR("Not initialized yet!"); return; } - instance->AddFromStorage(addr, in, autoconnect); + instance->AddFromStorage(addr, in); } bool CsisClient::GetForStorage(const RawAddress& addr, diff --git a/system/bta/csis/csis_client_test.cc b/system/bta/csis/csis_client_test.cc index 6391cfa930..d1d7c898b9 100644 --- a/system/bta/csis/csis_client_test.cc +++ b/system/bta/csis/csis_client_test.cc @@ -554,12 +554,8 @@ class CsisClientTest : public ::testing::Test { EXPECT_CALL(*callbacks, OnDeviceAvailable(address, _, _, _, _)) .Times(AtLeast(1)); - /* In testing only whe set info is empty, there is no CAP context. */ - bool is_opportunistic = (storage_buf.size() != 0); - EXPECT_CALL(gatt_interface, - Open(gatt_if, address, BTM_BLE_BKG_CONNECT_ALLOW_LIST, - is_opportunistic)) + Open(gatt_if, address, BTM_BLE_DIRECT_CONNECTION, true)) .WillOnce(Invoke([this, conn_id](tGATT_IF client_if, const RawAddress& remote_bda, bool is_direct, bool opportunistic) { @@ -568,7 +564,7 @@ class CsisClientTest : public ::testing::Test { })); DeviceGroups::AddFromStorage(address, storage_group_buf); - CsisClient::AddFromStorage(address, storage_buf, true); + CsisClient::AddFromStorage(address, storage_buf); } void InjectEncryptionEvent(const RawAddress& test_address, uint16_t conn_id) { @@ -1387,11 +1383,9 @@ TEST_F(CsisClientTest, test_storage_calls) { ASSERT_EQ(1, get_func_call_count("btif_storage_load_bonded_csis_devices")); ASSERT_EQ(0, get_func_call_count("btif_storage_update_csis_info")); - ASSERT_EQ(0, get_func_call_count("btif_storage_set_csis_autoconnect")); TestConnect(test_address); InjectConnectedEvent(test_address, 1); GetSearchCompleteEvent(1); - ASSERT_EQ(1, get_func_call_count("btif_storage_set_csis_autoconnect")); ASSERT_EQ(1, get_func_call_count("btif_storage_update_csis_info")); ASSERT_EQ(0, get_func_call_count("btif_storage_remove_csis_device")); diff --git a/system/bta/csis/csis_types.h b/system/bta/csis/csis_types.h index a1dd4dad4d..af0b8cf0c1 100644 --- a/system/bta/csis/csis_types.h +++ b/system/bta/csis/csis_types.h @@ -90,12 +90,6 @@ class GattServiceDevice { public: RawAddress addr; /* - * This is true only during first connection to profile, until we store the - * device. - */ - bool first_connection; - - /* * We are making active attempt to connect to this device, 'direct connect'. */ bool connecting_actively = false; @@ -105,7 +99,7 @@ class GattServiceDevice { bool is_gatt_service_valid = false; GattServiceDevice(const RawAddress& addr, bool first_connection) - : addr(addr), first_connection(first_connection) {} + : addr(addr) {} GattServiceDevice() : GattServiceDevice(RawAddress::kEmpty, false) {} diff --git a/system/bta/dm/bta_dm_disc.cc b/system/bta/dm/bta_dm_disc.cc index d2f3fec4b3..2874b491dc 100644 --- a/system/bta/dm/bta_dm_disc.cc +++ b/system/bta/dm/bta_dm_disc.cc @@ -57,6 +57,7 @@ #include "stack/include/hidh_api.h" #include "stack/include/sdp_status.h" #include "stack/sdp/sdpint.h" // is_sdp_pbap_pce_disabled +#include "storage/config_keys.h" #include "types/raw_address.h" #ifdef TARGET_FLOSS @@ -540,7 +541,7 @@ static void store_avrcp_profile_feature(tSDP_DISC_REC* sdp_rec) { } if (btif_config_set_bin(sdp_rec->remote_bd_addr.ToString().c_str(), - AV_REM_CTRL_FEATURES_CONFIG_KEY, + BTIF_STORAGE_KEY_AV_REM_CTRL_FEATURES, (const uint8_t*)&avrcp_features, sizeof(avrcp_features))) { LOG_INFO("Saving avrcp_features: 0x%x", avrcp_features); @@ -562,7 +563,7 @@ static void bta_dm_store_audio_profiles_version() { { .servclass_uuid = UUID_SERVCLASS_AV_REMOTE_CONTROL, .btprofile_uuid = UUID_SERVCLASS_AV_REMOTE_CONTROL, - .profile_key = AVRCP_CONTROLLER_VERSION_CONFIG_KEY, + .profile_key = BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION, .store_audio_profile_feature = store_avrcp_profile_feature, }, }}; diff --git a/system/bta/gatt/bta_gattc_act.cc b/system/bta/gatt/bta_gattc_act.cc index 258d81e332..2ea1c2ff58 100644 --- a/system/bta/gatt/bta_gattc_act.cc +++ b/system/bta/gatt/bta_gattc_act.cc @@ -358,12 +358,24 @@ void bta_gattc_open_error(tBTA_GATTC_CLCB* p_clcb, void bta_gattc_open_fail(tBTA_GATTC_CLCB* p_clcb, UNUSED_ATTR const tBTA_GATTC_DATA* p_data) { - LOG(WARNING) << __func__ << ": Cannot establish Connection. conn_id=" - << loghex(p_clcb->bta_conn_id) << ". Return GATT_ERROR(" - << +GATT_ERROR << ")"; + if (IS_FLAG_ENABLED(enumerate_gatt_errors) && + p_data->int_conn.reason == GATT_CONN_TIMEOUT) { + LOG(WARNING) << __func__ + << ": Connection timed out after 30 seconds. conn_id=" + << loghex(p_clcb->bta_conn_id) + << ". Return GATT_CONNECTION_TIMEOUT(" + << +GATT_CONNECTION_TIMEOUT << ")"; + bta_gattc_send_open_cback(p_clcb->p_rcb, GATT_CONNECTION_TIMEOUT, + p_clcb->bda, p_clcb->bta_conn_id, + p_clcb->transport, 0); + } else { + LOG(WARNING) << __func__ << ": Cannot establish Connection. conn_id=" + << loghex(p_clcb->bta_conn_id) << ". Return GATT_ERROR(" + << +GATT_ERROR << ")"; + bta_gattc_send_open_cback(p_clcb->p_rcb, GATT_ERROR, p_clcb->bda, + p_clcb->bta_conn_id, p_clcb->transport, 0); + } - bta_gattc_send_open_cback(p_clcb->p_rcb, GATT_ERROR, p_clcb->bda, - p_clcb->bta_conn_id, p_clcb->transport, 0); /* open failure, remove clcb */ bta_gattc_clcb_dealloc(p_clcb); } diff --git a/system/bta/gatt/bta_gattc_cache.cc b/system/bta/gatt/bta_gattc_cache.cc index 4c0755f2b0..92e58441f9 100644 --- a/system/bta/gatt/bta_gattc_cache.cc +++ b/system/bta/gatt/bta_gattc_cache.cc @@ -867,7 +867,7 @@ static void bta_gattc_read_ext_prop_desc_cmpl( // Just one Characteristic Extended Properties value at a time in Read // Response LOG(WARNING) << __func__ << " Read Response should be just 2 bytes!"; - bta_gattc_reset_discover_st(p_clcb->p_srcb, GATT_ERROR); + bta_gattc_reset_discover_st(p_clcb->p_srcb, GATT_INVALID_PDU); return; } diff --git a/system/bta/include/bta_csis_api.h b/system/bta/include/bta_csis_api.h index 8f23582852..e56d5cc0f5 100644 --- a/system/bta/include/bta_csis_api.h +++ b/system/bta/include/bta_csis_api.h @@ -35,7 +35,7 @@ class CsisClient { static void Initialize(bluetooth::csis::CsisClientCallbacks* callbacks, base::Closure initCb); static void AddFromStorage(const RawAddress& addr, - const std::vector<uint8_t>& in, bool autoconnect); + const std::vector<uint8_t>& in); static bool GetForStorage(const RawAddress& addr, std::vector<uint8_t>& out); static void CleanUp(); static CsisClient* Get(); diff --git a/system/bta/include/bta_hfp_api.h b/system/bta/include/bta_hfp_api.h index 22ea4a3927..fe86e2de47 100644 --- a/system/bta/include/bta_hfp_api.h +++ b/system/bta/include/bta_hfp_api.h @@ -30,9 +30,6 @@ #define HSP_VERSION_1_0 0x0100 #define HSP_VERSION_1_2 0x0102 -#define HFP_VERSION_CONFIG_KEY "HfpVersion" -#define HFP_SDP_FEATURES_CONFIG_KEY "HfpSdpFeatures" - int get_default_hfp_version(); #endif /* BTA_HFP_API_H */ diff --git a/system/bta/include/bta_hh_api.h b/system/bta/include/bta_hh_api.h index 9dcf3f344f..c017075097 100644 --- a/system/bta/include/bta_hh_api.h +++ b/system/bta/include/bta_hh_api.h @@ -27,6 +27,7 @@ #include "macros.h" #include "stack/include/bt_hdr.h" #include "stack/include/hiddefs.h" +#include "stack/include/l2c_api.h" #include "types/raw_address.h" /***************************************************************************** diff --git a/system/bta/jv/bta_jv_api.cc b/system/bta/jv/bta_jv_api.cc index df391c189a..0bb295e804 100644 --- a/system/bta/jv/bta_jv_api.cc +++ b/system/bta/jv/bta_jv_api.cc @@ -63,13 +63,12 @@ bool bta_jv_enabled = false; * ******************************************************************************/ tBTA_JV_STATUS BTA_JvEnable(tBTA_JV_DM_CBACK* p_cback) { + LOG_VERBOSE(""); if (!p_cback || bta_jv_enabled) { LOG(ERROR) << __func__ << ": failure"; return BTA_JV_FAILURE; } - VLOG(2) << __func__; - memset(&bta_jv_cb, 0, sizeof(tBTA_JV_CB)); /* set handle to invalid value by default */ for (int i = 0; i < BTA_JV_PM_MAX_NUM; i++) { @@ -116,7 +115,7 @@ void BTA_JvDisable(void) { * ******************************************************************************/ void BTA_JvGetChannelId(int conn_type, uint32_t id, int32_t channel) { - VLOG(2) << __func__ << ": conn_type=" << conn_type; + LOG_VERBOSE("conn_type:%d, id:%u, channel:%u", conn_type, id, channel); if (conn_type != BTA_JV_CONN_TYPE_RFCOMM && conn_type != BTA_JV_CONN_TYPE_L2CAP && @@ -143,7 +142,7 @@ void BTA_JvGetChannelId(int conn_type, uint32_t id, int32_t channel) { * ******************************************************************************/ tBTA_JV_STATUS BTA_JvFreeChannel(uint16_t channel, int conn_type) { - VLOG(2) << __func__; + LOG_VERBOSE("channel:%u, conn_type:%d", channel, conn_type); do_in_main_thread(FROM_HERE, Bind(&bta_jv_free_scn, conn_type, channel)); return BTA_JV_SUCCESS; @@ -165,7 +164,8 @@ tBTA_JV_STATUS BTA_JvFreeChannel(uint16_t channel, int conn_type) { tBTA_JV_STATUS BTA_JvStartDiscovery(const RawAddress& bd_addr, uint16_t num_uuid, const Uuid* p_uuid_list, uint32_t rfcomm_slot_id) { - VLOG(2) << __func__; + LOG_VERBOSE("bd_addr:%s, rfcomm_slot_id:%u, num_uuid:%u", + ADDRESS_TO_LOGGABLE_CSTR(bd_addr), rfcomm_slot_id, num_uuid); Uuid* uuid_list_copy = new Uuid[num_uuid]; memcpy(uuid_list_copy, p_uuid_list, num_uuid * sizeof(Uuid)); @@ -189,7 +189,7 @@ tBTA_JV_STATUS BTA_JvStartDiscovery(const RawAddress& bd_addr, * ******************************************************************************/ tBTA_JV_STATUS BTA_JvCreateRecordByUser(uint32_t rfcomm_slot_id) { - VLOG(2) << __func__; + LOG_VERBOSE("rfcomm_slot_id: %u", rfcomm_slot_id); do_in_main_thread(FROM_HERE, Bind(&bta_jv_create_record, rfcomm_slot_id)); return BTA_JV_SUCCESS; @@ -206,7 +206,7 @@ tBTA_JV_STATUS BTA_JvCreateRecordByUser(uint32_t rfcomm_slot_id) { * ******************************************************************************/ tBTA_JV_STATUS BTA_JvDeleteRecord(uint32_t handle) { - VLOG(2) << __func__; + LOG_VERBOSE("handle:%u", handle); do_in_main_thread(FROM_HERE, Bind(&bta_jv_delete_record, handle)); return BTA_JV_SUCCESS; @@ -231,7 +231,11 @@ void BTA_JvL2capConnect(int conn_type, tBTA_SEC sec_mask, tBTA_JV_ROLE role, const RawAddress& peer_bd_addr, tBTA_JV_L2CAP_CBACK* p_cback, uint32_t l2cap_socket_id) { - VLOG(2) << __func__; + LOG_VERBOSE( + "conn_type:%d, role:%u, remote_psm:%u, peer_bd_addr:%s, " + "l2cap_socket_id:%u", + conn_type, role, remote_psm, ADDRESS_TO_LOGGABLE_CSTR(peer_bd_addr), + l2cap_socket_id); CHECK(p_cback); do_in_main_thread(FROM_HERE, @@ -251,7 +255,7 @@ void BTA_JvL2capConnect(int conn_type, tBTA_SEC sec_mask, tBTA_JV_ROLE role, * ******************************************************************************/ tBTA_JV_STATUS BTA_JvL2capClose(uint32_t handle) { - VLOG(2) << __func__; + LOG_VERBOSE("handle:%u", handle); if (handle >= BTA_JV_MAX_L2C_CONN || !bta_jv_cb.l2c_cb[handle].p_cback) return BTA_JV_FAILURE; @@ -281,7 +285,8 @@ void BTA_JvL2capStartServer(int conn_type, tBTA_SEC sec_mask, tBTA_JV_ROLE role, std::unique_ptr<tL2CAP_CFG_INFO> cfg, tBTA_JV_L2CAP_CBACK* p_cback, uint32_t l2cap_socket_id) { - VLOG(2) << __func__; + LOG_VERBOSE("conn_type:%d, role:%u, local_psm:%u, l2cap_socket_id:%u", + conn_type, role, local_psm, l2cap_socket_id); CHECK(p_cback); do_in_main_thread(FROM_HERE, @@ -303,7 +308,7 @@ void BTA_JvL2capStartServer(int conn_type, tBTA_SEC sec_mask, tBTA_JV_ROLE role, ******************************************************************************/ tBTA_JV_STATUS BTA_JvL2capStopServer(uint16_t local_psm, uint32_t l2cap_socket_id) { - VLOG(2) << __func__; + LOG_VERBOSE("local_psm:%u, l2cap_socket_id:%u", local_psm, l2cap_socket_id); do_in_main_thread( FROM_HERE, Bind(&bta_jv_l2cap_stop_server, local_psm, l2cap_socket_id)); @@ -324,7 +329,7 @@ tBTA_JV_STATUS BTA_JvL2capStopServer(uint16_t local_psm, ******************************************************************************/ tBTA_JV_STATUS BTA_JvL2capRead(uint32_t handle, uint32_t req_id, uint8_t* p_data, uint16_t len) { - VLOG(2) << __func__; + LOG_VERBOSE("handle:%u, req_id:%u, len:%u", handle, req_id, len); if (handle >= BTA_JV_MAX_L2C_CONN || !bta_jv_cb.l2c_cb[handle].p_cback) return BTA_JV_FAILURE; @@ -359,7 +364,7 @@ tBTA_JV_STATUS BTA_JvL2capRead(uint32_t handle, uint32_t req_id, tBTA_JV_STATUS BTA_JvL2capReady(uint32_t handle, uint32_t* p_data_size) { tBTA_JV_STATUS status = BTA_JV_FAILURE; - VLOG(2) << __func__ << ": handle=" << handle; + LOG_VERBOSE("handle:%u", handle); if (p_data_size && handle < BTA_JV_MAX_L2C_CONN && bta_jv_cb.l2c_cb[handle].p_cback) { *p_data_size = 0; @@ -388,7 +393,7 @@ tBTA_JV_STATUS BTA_JvL2capReady(uint32_t handle, uint32_t* p_data_size) { ******************************************************************************/ tBTA_JV_STATUS BTA_JvL2capWrite(uint32_t handle, uint32_t req_id, BT_HDR* msg, uint32_t user_id) { - VLOG(2) << __func__; + LOG_VERBOSE("handle:%u, user_id:%u", handle, user_id); if (handle >= BTA_JV_MAX_L2C_CONN || !bta_jv_cb.l2c_cb[handle].p_cback) { osi_free(msg); @@ -421,7 +426,8 @@ tBTA_JV_STATUS BTA_JvRfcommConnect(tBTA_SEC sec_mask, tBTA_JV_ROLE role, const RawAddress& peer_bd_addr, tBTA_JV_RFCOMM_CBACK* p_cback, uint32_t rfcomm_slot_id) { - VLOG(2) << __func__; + LOG_VERBOSE("remote_scn:%u, peer_bd_addr:%s, rfcomm_slot_id:%u", remote_scn, + ADDRESS_TO_LOGGABLE_CSTR(peer_bd_addr), rfcomm_slot_id); if (!p_cback) return BTA_JV_FAILURE; /* Nothing to do */ @@ -445,7 +451,7 @@ tBTA_JV_STATUS BTA_JvRfcommClose(uint32_t handle, uint32_t rfcomm_slot_id) { uint32_t hi = ((handle & BTA_JV_RFC_HDL_MASK) & ~BTA_JV_RFCOMM_MASK) - 1; uint32_t si = BTA_JV_RFC_HDL_TO_SIDX(handle); - VLOG(2) << __func__; + LOG_VERBOSE("handle:%u, rfcomm_slot_id:%u", handle, rfcomm_slot_id); if (hi >= BTA_JV_MAX_RFC_CONN || !bta_jv_cb.rfc_cb[hi].p_cback || si >= BTA_JV_MAX_RFC_SR_SESSION || !bta_jv_cb.rfc_cb[hi].rfc_hdl[si]) @@ -475,7 +481,7 @@ tBTA_JV_STATUS BTA_JvRfcommStartServer(tBTA_SEC sec_mask, tBTA_JV_ROLE role, uint8_t local_scn, uint8_t max_session, tBTA_JV_RFCOMM_CBACK* p_cback, uint32_t rfcomm_slot_id) { - VLOG(2) << __func__; + LOG_VERBOSE("local_scn:%u, rfcomm_slot_id:%u", local_scn, rfcomm_slot_id); if (p_cback == NULL) return BTA_JV_FAILURE; /* Nothing to do */ @@ -505,7 +511,7 @@ tBTA_JV_STATUS BTA_JvRfcommStartServer(tBTA_SEC sec_mask, tBTA_JV_ROLE role, ******************************************************************************/ tBTA_JV_STATUS BTA_JvRfcommStopServer(uint32_t handle, uint32_t rfcomm_slot_id) { - VLOG(2) << __func__; + LOG_VERBOSE("handle:%u, rfcomm_slot_id:%u", handle, rfcomm_slot_id); do_in_main_thread(FROM_HERE, Bind(&bta_jv_rfcomm_stop_server, handle, rfcomm_slot_id)); @@ -516,10 +522,9 @@ tBTA_JV_STATUS BTA_JvRfcommStopServer(uint32_t handle, * * Function BTA_JvRfcommGetPortHdl * - * Description This function fetches the rfcomm port handle + * Description This function fetches the rfcomm port handle * - * Returns BTA_JV_SUCCESS, if the request is being processed. - * BTA_JV_FAILURE, otherwise. + * Returns * ******************************************************************************/ uint16_t BTA_JvRfcommGetPortHdl(uint32_t handle) { @@ -547,16 +552,13 @@ tBTA_JV_STATUS BTA_JvRfcommWrite(uint32_t handle, uint32_t req_id) { uint32_t hi = ((handle & BTA_JV_RFC_HDL_MASK) & ~BTA_JV_RFCOMM_MASK) - 1; uint32_t si = BTA_JV_RFC_HDL_TO_SIDX(handle); - VLOG(2) << __func__; - - VLOG(2) << __func__ << "handle=" << loghex(handle) << ", hi=" << hi - << ", si=" << si; + LOG_VERBOSE("handle:%u, req_id:%u, hi:%u, si:%u", handle, req_id, hi, si); if (hi >= BTA_JV_MAX_RFC_CONN || !bta_jv_cb.rfc_cb[hi].p_cback || si >= BTA_JV_MAX_RFC_SR_SESSION || !bta_jv_cb.rfc_cb[hi].rfc_hdl[si]) { return BTA_JV_FAILURE; } - VLOG(2) << "write ok"; + LOG_VERBOSE("write ok"); tBTA_JV_RFC_CB* p_cb = &bta_jv_cb.rfc_cb[hi]; do_in_main_thread(FROM_HERE, Bind(&bta_jv_rfcomm_write, handle, req_id, p_cb, @@ -589,7 +591,7 @@ tBTA_JV_STATUS BTA_JvRfcommWrite(uint32_t handle, uint32_t req_id) { ******************************************************************************/ tBTA_JV_STATUS BTA_JvSetPmProfile(uint32_t handle, tBTA_JV_PM_ID app_id, tBTA_JV_CONN_STATE init_st) { - VLOG(2) << __func__ << " handle=" << loghex(handle) << ", app_id:" << app_id; + LOG_VERBOSE("handle:%u, app_id:%u, init_st:%u", handle, app_id, handle); do_in_main_thread(FROM_HERE, Bind(&bta_jv_set_pm_profile, handle, app_id, init_st)); diff --git a/system/bta/le_audio/device_groups.h b/system/bta/le_audio/device_groups.h index 0013232674..7d6954101c 100644 --- a/system/bta/le_audio/device_groups.h +++ b/system/bta/le_audio/device_groups.h @@ -327,14 +327,23 @@ class LeAudioDeviceGroup { int direction = types::kLeAudioDirectionBoth) const; DsaModes GetAllowedDsaModes() { - DsaModes dsa_modes = {}; + if (!IS_FLAG_ENABLED(leaudio_dynamic_spatial_audio)) { + return {DsaMode::DISABLED}; + } + + DsaModes dsa_modes{}; + std::set<DsaMode> dsa_mode_set{}; + for (auto leAudioDevice : leAudioDevices_) { if (leAudioDevice.expired()) continue; - dsa_modes.insert(dsa_modes.end(), - leAudioDevice.lock()->GetDsaModes().begin(), - leAudioDevice.lock()->GetDsaModes().end()); + auto device_dsa_modes = leAudioDevice.lock()->GetDsaModes(); + + dsa_mode_set.insert(device_dsa_modes.begin(), device_dsa_modes.end()); } + + dsa_modes.assign(dsa_mode_set.begin(), dsa_mode_set.end()); + return dsa_modes; } diff --git a/system/bta/sys/bta_sys.h b/system/bta/sys/bta_sys.h index 8ebbf96c41..2bf38c2350 100644 --- a/system/bta/sys/bta_sys.h +++ b/system/bta/sys/bta_sys.h @@ -229,9 +229,6 @@ typedef struct { /***************************************************************************** * Function declarations ****************************************************************************/ -void bta_set_forward_hw_failures(bool value); -void BTA_sys_signal_hw_error(); - void bta_sys_init(void); void bta_sys_register(uint8_t id, const tBTA_SYS_REG* p_reg); void bta_sys_deregister(uint8_t id); diff --git a/system/bta/sys/bta_sys_int.h b/system/bta/sys/bta_sys_int.h index f2ceed4294..eb0f7863e5 100644 --- a/system/bta/sys/bta_sys_int.h +++ b/system/bta/sys/bta_sys_int.h @@ -48,7 +48,6 @@ typedef struct { typedef struct { tBTA_SYS_REG* reg[BTA_ID_MAX]; /* registration structures */ bool is_reg[BTA_ID_MAX]; /* registration structures */ - bool forward_hw_failures; uint16_t sys_features; /* Bitmask of sys features */ tBTA_SYS_CONN_CBACK* prm_cb; /* role management callback registered by DM */ diff --git a/system/bta/sys/bta_sys_main.cc b/system/bta/sys/bta_sys_main.cc index 64da55ad3f..50c2f8a9bb 100644 --- a/system/bta/sys/bta_sys_main.cc +++ b/system/bta/sys/bta_sys_main.cc @@ -39,8 +39,6 @@ #include "stack/include/bt_hdr.h" #include "stack/include/main_thread.h" -void BTIF_dm_on_hw_error(); - /* system manager control block definition */ tBTA_SYS_CB bta_sys_cb; @@ -58,16 +56,6 @@ void bta_sys_init(void) { memset(&bta_sys_cb, 0, sizeof(tBTA_SYS_CB)); } -void bta_set_forward_hw_failures(bool value) { - bta_sys_cb.forward_hw_failures = value; -} - -void BTA_sys_signal_hw_error() { - if (bta_sys_cb.forward_hw_failures) { - BTIF_dm_on_hw_error(); - } -} - /******************************************************************************* * * Function bta_sys_event diff --git a/system/btcore/Android.bp b/system/btcore/Android.bp index 02e25de69e..41ff38329d 100644 --- a/system/btcore/Android.bp +++ b/system/btcore/Android.bp @@ -55,7 +55,10 @@ cc_library_static { cflags: ["-D_GNU_SOURCE"], }, }, - static_libs: ["libbt_shim_bridge"], + static_libs: [ + "libbluetooth_log", + "libbt_shim_bridge", + ], } cc_library_static { @@ -66,7 +69,10 @@ cc_library_static { ], defaults: ["libbtcore_defaults"], min_sdk_version: "Tiramisu", - static_libs: ["libbt_shim_bridge"], + static_libs: [ + "libbluetooth_log", + "libbt_shim_bridge", + ], } cc_library_headers { @@ -102,6 +108,7 @@ cc_test { ], static_libs: [ "libbluetooth-types", + "libbluetooth_log", "libbtcore", "libchrome", "libosi", diff --git a/system/btcore/fuzzer/Android.bp b/system/btcore/fuzzer/Android.bp index 34305eeb23..b83a5558a1 100644 --- a/system/btcore/fuzzer/Android.bp +++ b/system/btcore/fuzzer/Android.bp @@ -37,6 +37,7 @@ cc_defaults { "libbluetooth-protos", "libbluetooth-types", "libbluetooth_crypto_toolbox", + "libbluetooth_log", "libbluetooth_rust_interop", "libbt-common", "libbt_shim_bridge", diff --git a/system/btif/Android.bp b/system/btif/Android.bp index 7a23fc5b1f..bc64535b14 100644 --- a/system/btif/Android.bp +++ b/system/btif/Android.bp @@ -59,6 +59,7 @@ cc_library_static { ], srcs: ["src/btif_jni_task.cc"], static_libs: [ + "libbluetooth_log", "libbt_shim_bridge", "libosi", ], @@ -154,6 +155,7 @@ cc_library_static { "libaudio-a2dp-hw-utils", "libbluetooth-types", "libbluetooth_hci_pdl", + "libbluetooth_log", "libbt-audio-hal-interface", "libbt-platform-protos-lite", "libbt-stack", @@ -239,6 +241,7 @@ cc_library_static { "libaudio-a2dp-hw-utils", "libbluetooth_crypto_toolbox", "libbluetooth_hci_pdl", + "libbluetooth_log", "libbt-audio-hal-interface", "libbt-jni-thread", "libbt-platform-protos-lite", @@ -302,6 +305,7 @@ cc_test { "libbluetooth-types", "libbluetooth_core_rs", "libbluetooth_crypto_toolbox", + "libbluetooth_log", "libbt-audio-asrc", "libbt-audio-hal-interface", "libbt-bta", @@ -380,6 +384,7 @@ cc_test { static_libs: [ "libbluetooth-types", "libbluetooth_gd", + "libbluetooth_log", "libbt_shim_bridge", "libbt_shim_ffi", "libchrome", @@ -416,6 +421,7 @@ cc_test { ], static_libs: [ "libbluetooth-types", + "libbluetooth_log", "libbt_shim_bridge", "libbt_shim_ffi", "libchrome", @@ -461,6 +467,7 @@ cc_test { "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt-platform-protos-lite", "libbt_shim_bridge", @@ -511,6 +518,7 @@ cc_test { static_libs: [ "libbluetooth-types", "libbluetooth_crypto_toolbox", + "libbluetooth_log", "libbt_shim_bridge", "libc++fs", "libchrome", @@ -549,6 +557,7 @@ cc_test { ], static_libs: [ "libbluetooth-types", + "libbluetooth_log", "libbt-platform-protos-lite", "libbt_shim_bridge", "libbt_shim_ffi", @@ -633,6 +642,7 @@ cc_test { "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-audio-hal-interface", "libbt-common", "libbt-jni-thread", @@ -754,6 +764,7 @@ cc_test { "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-audio-hal-interface", "libbt-common", "libbt-jni-thread", diff --git a/system/btif/BUILD.gn b/system/btif/BUILD.gn index c14c1dc371..ac5d5dbd58 100644 --- a/system/btif/BUILD.gn +++ b/system/btif/BUILD.gn @@ -120,6 +120,7 @@ static_library("btif") { configs += [ "//bt/system:target_defaults", + "//bt/system/log:log_defaults", "//bt/system:external_tinyxml2", ] } diff --git a/system/btif/co/bta_hh_co.cc b/system/btif/co/bta_hh_co.cc index bc8c7e3473..4c2ece6577 100644 --- a/system/btif/co/bta_hh_co.cc +++ b/system/btif/co/bta_hh_co.cc @@ -38,6 +38,7 @@ #include "osi/include/allocator.h" #include "osi/include/compat.h" #include "osi/include/osi.h" +#include "storage/config_keys.h" #include "types/raw_address.h" const char* dev_path = "/dev/uhid"; @@ -759,17 +760,20 @@ void bta_hh_le_co_rpt_info(const RawAddress& remote_bda, std::string addrstr = remote_bda.ToString(); const char* bdstr = addrstr.c_str(); - size_t len = btif_config_get_bin_length(bdstr, "HidReport"); + size_t len = btif_config_get_bin_length(bdstr, BTIF_STORAGE_KEY_HID_REPORT); if (len >= sizeof(tBTA_HH_RPT_CACHE_ENTRY) && len <= sizeof(sReportCache)) { - btif_config_get_bin(bdstr, "HidReport", (uint8_t*)sReportCache, &len); + btif_config_get_bin(bdstr, BTIF_STORAGE_KEY_HID_REPORT, + (uint8_t*)sReportCache, &len); idx = len / sizeof(tBTA_HH_RPT_CACHE_ENTRY); } if (idx < BTA_HH_NV_LOAD_MAX) { memcpy(&sReportCache[idx++], p_entry, sizeof(tBTA_HH_RPT_CACHE_ENTRY)); - btif_config_set_bin(bdstr, "HidReport", (const uint8_t*)sReportCache, + btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_HID_REPORT, + (const uint8_t*)sReportCache, idx * sizeof(tBTA_HH_RPT_CACHE_ENTRY)); - btif_config_set_int(bdstr, "HidReportVersion", BTA_HH_CACHE_REPORT_VERSION); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_REPORT_VERSION, + BTA_HH_CACHE_REPORT_VERSION); LOG_VERBOSE("%s() - Saving report; dev=%s, idx=%d", __func__, ADDRESS_TO_LOGGABLE_CSTR(remote_bda), idx); } @@ -797,14 +801,16 @@ tBTA_HH_RPT_CACHE_ENTRY* bta_hh_le_co_cache_load(const RawAddress& remote_bda, std::string addrstr = remote_bda.ToString(); const char* bdstr = addrstr.c_str(); - size_t len = btif_config_get_bin_length(bdstr, "HidReport"); + size_t len = btif_config_get_bin_length(bdstr, BTIF_STORAGE_KEY_HID_REPORT); if (!p_num_rpt || len < sizeof(tBTA_HH_RPT_CACHE_ENTRY)) return NULL; if (len > sizeof(sReportCache)) len = sizeof(sReportCache); - btif_config_get_bin(bdstr, "HidReport", (uint8_t*)sReportCache, &len); + btif_config_get_bin(bdstr, BTIF_STORAGE_KEY_HID_REPORT, + (uint8_t*)sReportCache, &len); int cache_version = -1; - btif_config_get_int(bdstr, "HidReportVersion", &cache_version); + btif_config_get_int(bdstr, BTIF_STORAGE_KEY_HID_REPORT_VERSION, + &cache_version); if (cache_version != BTA_HH_CACHE_REPORT_VERSION) { bta_hh_le_co_reset_rpt_cache(remote_bda, app_id); @@ -835,8 +841,8 @@ void bta_hh_le_co_reset_rpt_cache(const RawAddress& remote_bda, std::string addrstr = remote_bda.ToString(); const char* bdstr = addrstr.c_str(); - btif_config_remove(bdstr, "HidReport"); - btif_config_remove(bdstr, "HidReportVersion"); + btif_config_remove(bdstr, BTIF_STORAGE_KEY_HID_REPORT); + btif_config_remove(bdstr, BTIF_STORAGE_KEY_HID_REPORT_VERSION); LOG_VERBOSE("%s() - Reset cache for bda %s", __func__, ADDRESS_TO_LOGGABLE_CSTR(remote_bda)); } diff --git a/system/btif/include/btif_common.h b/system/btif/include/btif_common.h index 04e88b56ba..c4a55b3356 100644 --- a/system/btif/include/btif_common.h +++ b/system/btif/include/btif_common.h @@ -46,13 +46,6 @@ } \ } while (0) -/* Calculate start of event enumeration; id is top 8 bits of event */ -#define BTIF_SIG_START(id) ((id) << 8) - -/* For upstream the MSB bit is always SET */ -#define BTIF_SIG_CB_BIT (0x8000) -#define BTIF_SIG_CB_START(id) (((id) << 8) | BTIF_SIG_CB_BIT) - /* * A memcpy(3) wrapper when copying memory that might not be aligned. * @@ -70,14 +63,6 @@ #define maybe_non_aligned_memcpy(_a, _b, _c) \ memcpy((void*)(_a), (void*)(_b), (_c)) -/* BTIF sub-systems */ -#define BTIF_CORE 0 -#define BTIF_DM 1 -#define BTIF_HFP 2 -#define BTIF_AV 3 -#define BTIF_PAN 4 -#define BTIF_HF_CLIENT 5 - #define HAL_CBACK(P_CB, P_CBACK, ...) \ do { \ if ((P_CB) && (P_CB)->P_CBACK) { \ @@ -88,45 +73,6 @@ } \ } while (0) -/** - * BTIF events for requests that require context switch to btif task - * on downstreams path - */ -enum { - BTIF_DM_API_START = BTIF_SIG_START(BTIF_DM), - BTIF_DM_ENABLE_SERVICE, - BTIF_DM_DISABLE_SERVICE, - /* add here */ - - BTIF_HFP_API_START = BTIF_SIG_START(BTIF_HFP), - /* add here */ - - BTIF_AV_API_START = BTIF_SIG_START(BTIF_AV), - /* add here */ -}; - -/** - * BTIF events for callbacks that require context switch to btif task - * on upstream path - Typically these would be non-BTA events - * that are generated by the BTIF layer. - */ -enum { - BTIF_CORE_CB_START = BTIF_SIG_CB_START(BTIF_CORE), - /* add here */ - - BTIF_HFP_CB_START = BTIF_SIG_CB_START(BTIF_HFP), - BTIF_HFP_CB_AUDIO_CONNECTING, /* HF AUDIO connect has been sent to BTA - successfully */ - - BTIF_PAN_CB_START = BTIF_SIG_CB_START(BTIF_PAN), - BTIF_PAN_CB_DISCONNECTING, /* PAN Disconnect has been sent to BTA successfully - */ - - BTIF_HF_CLIENT_CLIENT_CB_START = BTIF_SIG_CB_START(BTIF_HF_CLIENT), - BTIF_HF_CLIENT_CB_AUDIO_CONNECTING, /* AUDIO connect has been sent to BTA - successfully */ -}; - /******************************************************************************* * Type definitions for callback functions ******************************************************************************/ diff --git a/system/btif/include/btif_config.h b/system/btif/include/btif_config.h index 7bb0659bbd..f7e1cf462c 100644 --- a/system/btif/include/btif_config.h +++ b/system/btif/include/btif_config.h @@ -31,20 +31,6 @@ static const char BTIF_CONFIG_MODULE[] = "btif_config_module"; -static const std::string BT_CONFIG_KEY_SDP_DI_MANUFACTURER = - "SdpDiManufacturer"; -static const std::string BT_CONFIG_KEY_SDP_DI_MODEL = "SdpDiModel"; -static const std::string BT_CONFIG_KEY_SDP_DI_HW_VERSION = - "SdpDiHardwareVersion"; -static const std::string BT_CONFIG_KEY_SDP_DI_VENDOR_ID_SRC = - "SdpDiVendorIdSource"; - -static const std::string BT_CONFIG_KEY_REMOTE_VER_MFCT = "Manufacturer"; -static const std::string BT_CONFIG_KEY_REMOTE_VER_VER = "LmpVer"; -static const std::string BT_CONFIG_KEY_REMOTE_VER_SUBVER = "LmpSubVer"; -static const std::string BT_CONFIG_KEY_PBAP_PCE_VERSION = "PbapPceVersion"; -static const std::string BT_CONFIG_KEY_DIS_MODEL_NUM = "ModelName"; - bool btif_config_exist(const std::string& section, const std::string& key); bool btif_config_get_int(const std::string& section, const std::string& key, int* value); diff --git a/system/btif/include/btif_storage.h b/system/btif/include/btif_storage.h index dbf8d26488..394cd5b5b7 100644 --- a/system/btif/include/btif_storage.h +++ b/system/btif/include/btif_storage.h @@ -39,8 +39,6 @@ (p_prop)->val = (p_v); \ } while (0) -#define BTIF_STORAGE_PATH_REMOTE_SERVICE "Service" - #define STORAGE_BDADDR_STRING_SZ (18) /* 00:11:22:33:44:55 */ #define STORAGE_UUID_STRING_SIZE \ (36 + 1) /* 00001200-0000-1000-8000-00805f9b34fb; */ @@ -393,8 +391,6 @@ void btif_storage_add_groups(const RawAddress& addr); void btif_storage_load_bonded_groups(void); void btif_storage_remove_groups(const RawAddress& address); -void btif_storage_set_csis_autoconnect(const RawAddress& addr, - bool autoconnect); void btif_storage_update_csis_info(const RawAddress& addr); void btif_storage_load_bonded_csis_devices(); void btif_storage_remove_csis_device(const RawAddress& address); diff --git a/system/btif/src/bluetooth.cc b/system/btif/src/bluetooth.cc index 7a01ecea1d..e18f5b628b 100644 --- a/system/btif/src/bluetooth.cc +++ b/system/btif/src/bluetooth.cc @@ -109,6 +109,7 @@ #include "stack/include/hidh_api.h" #include "stack/include/main_thread.h" #include "stack/include/pan_api.h" +#include "storage/config_keys.h" #include "types/raw_address.h" using bluetooth::csis::CsisClientInterface; @@ -826,7 +827,8 @@ static int get_remote_pbap_pce_version(const RawAddress* bd_addr) { // Read and restore the PCE version from local storage uint16_t pce_version = 0; size_t version_value_size = sizeof(pce_version); - if (!btif_config_get_bin(bd_addr->ToString(), BT_CONFIG_KEY_PBAP_PCE_VERSION, + if (!btif_config_get_bin(bd_addr->ToString(), + BTIF_STORAGE_KEY_PBAP_PCE_VERSION, (uint8_t*)&pce_version, &version_value_size)) { LOG_WARN("Failed to read cached peer PCE version for %s", ADDRESS_TO_LOGGABLE_CSTR(*bd_addr)); diff --git a/system/btif/src/btif_a2dp_control.cc b/system/btif/src/btif_a2dp_control.cc index 0707135259..8ed0ee5b1f 100644 --- a/system/btif/src/btif_a2dp_control.cc +++ b/system/btif/src/btif_a2dp_control.cc @@ -26,13 +26,11 @@ #include <stdint.h> #include "audio_a2dp_hw/include/audio_a2dp_hw.h" -#include "btif_a2dp.h" #include "btif_a2dp_sink.h" #include "btif_a2dp_source.h" #include "btif_av.h" #include "btif_av_co.h" #include "btif_hf.h" -#include "osi/include/osi.h" #include "types/raw_address.h" #include "udrv/include/uipc.h" @@ -318,8 +316,7 @@ static void btif_a2dp_recv_ctrl_data(void) { } } -static void btif_a2dp_ctrl_cb(UNUSED_ATTR tUIPC_CH_ID ch_id, - tUIPC_EVENT event) { +static void btif_a2dp_ctrl_cb(tUIPC_CH_ID /* ch_id */, tUIPC_EVENT event) { // Don't log UIPC_RX_DATA_READY_EVT by default, because it // could be very chatty when audio is streaming. if (event == UIPC_RX_DATA_READY_EVT) { @@ -352,8 +349,7 @@ static void btif_a2dp_ctrl_cb(UNUSED_ATTR tUIPC_CH_ID ch_id, } } -static void btif_a2dp_data_cb(UNUSED_ATTR tUIPC_CH_ID ch_id, - tUIPC_EVENT event) { +static void btif_a2dp_data_cb(tUIPC_CH_ID /* ch_id */, tUIPC_EVENT event) { LOG_WARN("%s: BTIF MEDIA (A2DP-DATA) EVENT %s", __func__, dump_uipc_event(event)); diff --git a/system/btif/src/btif_a2dp_sink.cc b/system/btif/src/btif_a2dp_sink.cc index 1027f30ca2..e89b01f95a 100644 --- a/system/btif/src/btif_a2dp_sink.cc +++ b/system/btif/src/btif_a2dp_sink.cc @@ -34,12 +34,10 @@ #include "btif/include/btif_util.h" // CASE_RETURN_STR #include "common/message_loop_thread.h" #include "include/check.h" -#include "internal_include/bt_target.h" +#include "os/log.h" #include "osi/include/alarm.h" #include "osi/include/allocator.h" #include "osi/include/fixed_queue.h" -#include "osi/include/log.h" -#include "osi/include/osi.h" // UNUSED_ATTR #include "stack/include/bt_hdr.h" #include "types/raw_address.h" @@ -158,7 +156,7 @@ static void btif_a2dp_sink_clear_track_event_req(); static void btif_a2dp_sink_on_start_event(); static void btif_a2dp_sink_on_suspend_event(); -UNUSED_ATTR static const char* dump_media_event(uint16_t event) { +static const char* dump_media_event(uint16_t event) { switch (event) { CASE_RETURN_STR(BTIF_MEDIA_SINK_DECODER_UPDATE) CASE_RETURN_STR(BTIF_MEDIA_SINK_CLEAR_TRACK) @@ -425,7 +423,7 @@ void btif_a2dp_sink_on_idle() { btif_a2dp_sink_clear_track_event_req(); } -void btif_a2dp_sink_on_stopped(UNUSED_ATTR tBTA_AV_SUSPEND* p_av_suspend) { +void btif_a2dp_sink_on_stopped(tBTA_AV_SUSPEND* /* p_av_suspend */) { LOG_INFO("%s", __func__); BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID))); @@ -437,7 +435,7 @@ void btif_a2dp_sink_on_stopped(UNUSED_ATTR tBTA_AV_SUSPEND* p_av_suspend) { btif_a2dp_sink_audio_handle_stop_decoding(); } -void btif_a2dp_sink_on_suspended(UNUSED_ATTR tBTA_AV_SUSPEND* p_av_suspend) { +void btif_a2dp_sink_on_suspended(tBTA_AV_SUSPEND* /* p_av_suspend */) { LOG_INFO("%s", __func__); BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID))); @@ -486,7 +484,7 @@ static void btif_a2dp_sink_audio_handle_stop_decoding() { } } -static void btif_decode_alarm_cb(UNUSED_ATTR void* context) { +static void btif_decode_alarm_cb(void* /* context */) { LockGuard lock(g_mutex); btif_a2dp_sink_cb.worker_thread.DoInThread( FROM_HERE, base::BindOnce(btif_a2dp_sink_avk_handle_timer)); @@ -711,7 +709,7 @@ void btif_a2dp_sink_audio_rx_flush_req() { FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); } -void btif_a2dp_sink_debug_dump(UNUSED_ATTR int fd) { +void btif_a2dp_sink_debug_dump(int /* fd */) { // Nothing to do } diff --git a/system/btif/src/btif_config.cc b/system/btif/src/btif_config.cc index a489caceb1..9f304f8848 100644 --- a/system/btif/src/btif_config.cc +++ b/system/btif/src/btif_config.cc @@ -41,6 +41,7 @@ #include "main/shim/shim.h" #include "os/log.h" #include "raw_address.h" +#include "storage/config_keys.h" #define TEMPORARY_SECTION_CAPACITY 10000 @@ -50,10 +51,6 @@ #define TIME_STRING_LENGTH sizeof("YYYY-MM-DD HH:MM:SS") #define DISABLED "disabled" -#define BT_CONFIG_METRICS_SECTION "Metrics" -#define BT_CONFIG_METRICS_SALT_256BIT "Salt256Bit" -#define BT_CONFIG_METRICS_ID_KEY "MetricsId" - using bluetooth::bluetooth_keystore::BluetoothKeystoreInterface; using bluetooth::common::AddressObfuscator; using bluetooth::common::MetricIdAllocator; @@ -84,9 +81,9 @@ static char btif_config_time_created[TIME_STRING_LENGTH]; static void read_or_set_metrics_salt() { AddressObfuscator::Octet32 metrics_salt = {}; size_t metrics_salt_length = metrics_salt.size(); - if (!btif_config_get_bin(BT_CONFIG_METRICS_SECTION, - BT_CONFIG_METRICS_SALT_256BIT, metrics_salt.data(), - &metrics_salt_length)) { + if (!btif_config_get_bin(BTIF_STORAGE_SECTION_METRICS, + BTIF_STORAGE_KEY_METRICS_SALT_256BIT, + metrics_salt.data(), &metrics_salt_length)) { LOG(WARNING) << __func__ << ": Failed to read metrics salt from config"; // Invalidate salt metrics_salt.fill(0); @@ -102,9 +99,9 @@ static void read_or_set_metrics_salt() { if (RAND_bytes(metrics_salt.data(), metrics_salt.size()) != 1) { LOG(FATAL) << __func__ << "Failed to generate salt for metrics"; } - if (!btif_config_set_bin(BT_CONFIG_METRICS_SECTION, - BT_CONFIG_METRICS_SALT_256BIT, metrics_salt.data(), - metrics_salt.size())) { + if (!btif_config_set_bin(BTIF_STORAGE_SECTION_METRICS, + BTIF_STORAGE_KEY_METRICS_SALT_256BIT, + metrics_salt.data(), metrics_salt.size())) { LOG(FATAL) << __func__ << "Failed to write metrics salt to config"; } } @@ -127,10 +124,10 @@ static void init_metric_id_allocator() { auto addr_str = mac_address.ToString(); // if the section name is a mac address bool is_valid_id_found = false; - if (btif_config_exist(addr_str, BT_CONFIG_METRICS_ID_KEY)) { + if (btif_config_exist(addr_str, BTIF_STORAGE_KEY_METRICS_ID_KEY)) { // there is one metric id under this mac_address int id = 0; - btif_config_get_int(addr_str, BT_CONFIG_METRICS_ID_KEY, &id); + btif_config_get_int(addr_str, BTIF_STORAGE_KEY_METRICS_ID_KEY, &id); if (is_valid_id_from_metric_id_allocator(id)) { paired_device_map[mac_address] = id; is_valid_id_found = true; @@ -144,12 +141,13 @@ static void init_metric_id_allocator() { // Initialize MetricIdAllocator MetricIdAllocator::Callback save_device_callback = [](const RawAddress& address, const int id) { - return btif_config_set_int(address.ToString(), BT_CONFIG_METRICS_ID_KEY, - id); + return btif_config_set_int(address.ToString(), + BTIF_STORAGE_KEY_METRICS_ID_KEY, id); }; MetricIdAllocator::Callback forget_device_callback = [](const RawAddress& address, const int id) { - return btif_config_remove(address.ToString(), BT_CONFIG_METRICS_ID_KEY); + return btif_config_remove(address.ToString(), + BTIF_STORAGE_KEY_METRICS_ID_KEY); }; if (!init_metric_id_allocator(paired_device_map, std::move(save_device_callback), @@ -203,7 +201,9 @@ bool btif_get_device_clockoffset(const RawAddress& bda, int* p_clock_offset) { std::string addrstr = bda.ToString(); const char* bd_addr_str = addrstr.c_str(); - if (!btif_config_get_int(bd_addr_str, "ClockOffset", p_clock_offset)) return false; + if (!btif_config_get_int(bd_addr_str, BTIF_STORAGE_KEY_CLOCK_OFFSET, + p_clock_offset)) + return false; LOG_DEBUG("%s: Device [%s] clock_offset %d", __func__, bd_addr_str, *p_clock_offset); @@ -215,7 +215,9 @@ bool btif_set_device_clockoffset(const RawAddress& bda, int clock_offset) { std::string addrstr = bda.ToString(); const char* bd_addr_str = addrstr.c_str(); - if (!btif_config_set_int(bd_addr_str, "ClockOffset", clock_offset)) return false; + if (!btif_config_set_int(bd_addr_str, BTIF_STORAGE_KEY_CLOCK_OFFSET, + clock_offset)) + return false; LOG_DEBUG("%s: Device [%s] clock_offset %d", __func__, bd_addr_str, clock_offset); diff --git a/system/btif/src/btif_config_cache.cc b/system/btif/src/btif_config_cache.cc index ad18a5bb0c..c8f03cda71 100644 --- a/system/btif/src/btif_config_cache.cc +++ b/system/btif/src/btif_config_cache.cc @@ -22,16 +22,19 @@ #include <unordered_set> #include <vector> +#include "storage/config_keys.h" #include "types/raw_address.h" namespace { const std::unordered_set<std::string> kLinkKeyTypes = { - "LinkKey", "LE_KEY_PENC", "LE_KEY_PID", - "LE_KEY_PCSRK", "LE_KEY_LENC", "LE_KEY_LCSRK"}; + BTIF_STORAGE_KEY_LINK_KEY, BTIF_STORAGE_KEY_LE_KEY_PENC, + BTIF_STORAGE_KEY_LE_KEY_PID, BTIF_STORAGE_KEY_LE_KEY_PCSRK, + BTIF_STORAGE_KEY_LE_KEY_LENC, BTIF_STORAGE_KEY_LE_KEY_LCSRK}; -const std::unordered_set<std::string> kLocalSectionNames = {"Info", "Metrics", - "Adapter"}; +const std::unordered_set<std::string> kLocalSectionNames = { + BTIF_STORAGE_SECTION_INFO, BTIF_STORAGE_SECTION_METRICS, + BTIF_STORAGE_SECTION_ADAPTER}; bool is_link_key(const std::string& key) { return kLinkKeyTypes.find(key) != kLinkKeyTypes.end(); diff --git a/system/btif/src/btif_core.cc b/system/btif/src/btif_core.cc index f1f9539b10..8fcfe455a5 100644 --- a/system/btif/src/btif_core.cc +++ b/system/btif/src/btif_core.cc @@ -61,6 +61,7 @@ #include "stack/include/bt_types.h" #include "stack/include/btm_api.h" #include "stack/include/btm_ble_api.h" +#include "storage/config_keys.h" #include "types/bluetooth/uuid.h" #include "types/raw_address.h" @@ -186,13 +187,15 @@ void btif_enable_bluetooth_evt() { char val[PROPERTY_VALUE_MAX] = ""; int val_size = PROPERTY_VALUE_MAX; - if (!btif_config_get_str("Adapter", "Address", val, &val_size) || + if (!btif_config_get_str(BTIF_STORAGE_SECTION_ADAPTER, + BTIF_STORAGE_KEY_ADDRESS, val, &val_size) || strcmp(bdstr.c_str(), val) != 0) { // We failed to get an address or the one in the config file does not match // the address given by the controller interface. Update the config cache - LOG_INFO("%s: Storing '%s' into the config file", __func__, - ADDRESS_TO_LOGGABLE_CSTR(local_bd_addr)); - btif_config_set_str("Adapter", "Address", bdstr.c_str()); + LOG_INFO("Storing '%s' into the config file", + ADDRESS_TO_LOGGABLE_CSTR(local_bd_addr)); + btif_config_set_str(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_ADDRESS, + bdstr.c_str()); // fire HAL callback for property change bt_property_t prop; @@ -249,20 +252,6 @@ bt_status_t btif_cleanup_bluetooth() { /******************************************************************************* * - * Function btif_dut_mode_cback - * - * Description Callback invoked on completion of vendor specific test mode - * command - * - * Returns None - * - ******************************************************************************/ -static void btif_dut_mode_cback(UNUSED_ATTR tBTM_VSC_CMPL* p) { - /* For now nothing to be done. */ -} - -/******************************************************************************* - * * Function btif_dut_mode_configure * * Description Configure Test Mode - 'enable' to 1 puts the device in test @@ -290,7 +279,8 @@ void btif_dut_mode_configure(uint8_t enable) { ******************************************************************************/ void btif_dut_mode_send(uint16_t opcode, uint8_t* buf, uint8_t len) { LOG_VERBOSE("%s", __func__); - BTM_VendorSpecificCommand(opcode, len, buf, btif_dut_mode_cback); + /* For now nothing to be done. */ + BTM_VendorSpecificCommand(opcode, len, buf, [](tBTM_VSC_CMPL*) {}); } /***************************************************************************** diff --git a/system/btif/src/btif_dm.cc b/system/btif/src/btif_dm.cc index 598b43ff2b..427760564a 100644 --- a/system/btif/src/btif_dm.cc +++ b/system/btif/src/btif_dm.cc @@ -51,7 +51,6 @@ #include <mutex> #include <optional> -#include <android_bluetooth_flags.h> #include "advertise_data_parser.h" #include "bta/dm/bta_dm_disc.h" #include "bta/include/bta_api.h" @@ -76,7 +75,6 @@ #include "os/log.h" #include "os/logging/log_adapter.h" #include "osi/include/allocator.h" -#include "osi/include/osi.h" #include "osi/include/properties.h" #include "osi/include/stack_power_telemetry.h" #include "stack/btm/btm_dev.h" @@ -95,6 +93,7 @@ #include "stack/include/btm_sec_api_types.h" #include "stack/include/smp_api.h" #include "stack/sdp/sdpint.h" +#include "storage/config_keys.h" #include "types/raw_address.h" #ifdef __ANDROID__ @@ -824,8 +823,8 @@ static void btif_dm_cb_create_bond(const RawAddress bd_addr, std::string addrstr = bd_addr.ToString(); const char* bdstr = addrstr.c_str(); if (transport == BT_TRANSPORT_LE) { - if (!btif_config_get_int(bdstr, "DevType", &device_type)) { - btif_config_set_int(bdstr, "DevType", BT_DEVICE_TYPE_BLE); + if (!btif_config_get_int(bdstr, BTIF_STORAGE_KEY_DEV_TYPE, &device_type)) { + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_DEV_TYPE, BT_DEVICE_TYPE_BLE); } if (btif_storage_get_remote_addr_type(&bd_addr, &addr_type) != BT_STATUS_SUCCESS) { @@ -839,7 +838,7 @@ static void btif_dm_cb_create_bond(const RawAddress bd_addr, btif_storage_set_remote_addr_type(&bd_addr, addr_type); } } - if ((btif_config_get_int(bdstr, "DevType", &device_type) && + if ((btif_config_get_int(bdstr, BTIF_STORAGE_KEY_DEV_TYPE, &device_type) && (btif_storage_get_remote_addr_type(&bd_addr, &addr_type) == BT_STATUS_SUCCESS) && (device_type & BT_DEVICE_TYPE_BLE) == BT_DEVICE_TYPE_BLE) || @@ -2164,13 +2163,6 @@ void BTIF_dm_report_inquiry_status_change(tBTM_INQUIRY_STATE status) { } } -void BTIF_dm_on_hw_error() { - LOG_ERROR("Received H/W Error"); - usleep(100000); /* 100milliseconds */ - /* Killing the process to force a restart as part of fault tolerance */ - kill(getpid(), SIGKILL); -} - void BTIF_dm_enable() { BD_NAME bdname; bt_status_t status; @@ -3168,9 +3160,8 @@ void btif_dm_proc_io_req(tBTM_AUTH_REQ* p_auth_req, bool is_orig) { LOG_VERBOSE("updated p_auth_req=%d", *p_auth_req); } -void btif_dm_proc_io_rsp(UNUSED_ATTR const RawAddress& bd_addr, - tBTM_IO_CAP io_cap, UNUSED_ATTR tBTM_OOB_DATA oob_data, - tBTM_AUTH_REQ auth_req) { +void btif_dm_proc_io_rsp(const RawAddress& /* bd_addr */, tBTM_IO_CAP io_cap, + tBTM_OOB_DATA /* oob_data */, tBTM_AUTH_REQ auth_req) { if (auth_req & BTA_AUTH_BONDS) { LOG_DEBUG("auth_req:%d", auth_req); pairing_cb.auth_req = auth_req; @@ -4153,7 +4144,9 @@ bool btif_get_device_type(const RawAddress& bda, int* p_device_type) { std::string addrstr = bda.ToString(); const char* bd_addr_str = addrstr.c_str(); - if (!btif_config_get_int(bd_addr_str, "DevType", p_device_type)) return false; + if (!btif_config_get_int(bd_addr_str, BTIF_STORAGE_KEY_DEV_TYPE, + p_device_type)) + return false; tBT_DEVICE_TYPE device_type = static_cast<tBT_DEVICE_TYPE>(*p_device_type); LOG_DEBUG("bd_addr:%s device_type:%s", ADDRESS_TO_LOGGABLE_CSTR(bda), DeviceTypeText(device_type).c_str()); @@ -4168,7 +4161,8 @@ bool btif_get_address_type(const RawAddress& bda, tBLE_ADDR_TYPE* p_addr_type) { const char* bd_addr_str = addrstr.c_str(); int val = 0; - if (!btif_config_get_int(bd_addr_str, "AddrType", &val)) return false; + if (!btif_config_get_int(bd_addr_str, BTIF_STORAGE_KEY_ADDR_TYPE, &val)) + return false; *p_addr_type = static_cast<tBLE_ADDR_TYPE>(val); LOG_DEBUG("bd_addr:%s[%s]", ADDRESS_TO_LOGGABLE_CSTR(bda), AddressTypeText(*p_addr_type).c_str()); diff --git a/system/btif/src/btif_gatt_client.cc b/system/btif/src/btif_gatt_client.cc index 74819d7549..6796db048a 100644 --- a/system/btif/src/btif_gatt_client.cc +++ b/system/btif/src/btif_gatt_client.cc @@ -50,6 +50,7 @@ #include "stack/include/acl_api.h" #include "stack/include/acl_api_types.h" #include "stack/include/main_thread.h" +#include "storage/config_keys.h" #include "types/ble_address_with_type.h" #include "types/bluetooth/uuid.h" #include "types/bt_transport.h" @@ -651,7 +652,8 @@ static bt_status_t btif_gattc_read_phy( static int btif_gattc_get_device_type(const RawAddress& bd_addr) { int device_type = 0; - if (btif_config_get_int(bd_addr.ToString().c_str(), "DevType", &device_type)) + if (btif_config_get_int(bd_addr.ToString().c_str(), BTIF_STORAGE_KEY_DEV_TYPE, + &device_type)) return device_type; return 0; } diff --git a/system/btif/src/btif_gatt_test.cc b/system/btif/src/btif_gatt_test.cc index d423c6a665..ce5446310a 100644 --- a/system/btif/src/btif_gatt_test.cc +++ b/system/btif/src/btif_gatt_test.cc @@ -27,7 +27,6 @@ #include "gatt_api.h" #include "internal_include/bte_appl.h" #include "os/log.h" -#include "osi/include/osi.h" #include "stack/include/btm_ble_sec_api.h" #include "types/ble_address_with_type.h" #include "types/bluetooth/uuid.h" @@ -91,7 +90,7 @@ static void btif_test_command_complete_cback(uint16_t conn_id, tGATTC_OPTYPE op, } } -static void btif_test_discovery_result_cback(UNUSED_ATTR uint16_t conn_id, +static void btif_test_discovery_result_cback(uint16_t /* conn_id */, tGATT_DISC_TYPE disc_type, tGATT_DISC_RES* p_data) { LOG_INFO("------ GATT Discovery result %-22s -------", disc_name[disc_type]); @@ -145,9 +144,9 @@ static void btif_test_discovery_result_cback(UNUSED_ATTR uint16_t conn_id, LOG_INFO("-----------------------------------------------------------"); } -static void btif_test_discovery_complete_cback( - UNUSED_ATTR uint16_t conn_id, UNUSED_ATTR tGATT_DISC_TYPE disc_type, - tGATT_STATUS status) { +static void btif_test_discovery_complete_cback(uint16_t /* conn_id */, + tGATT_DISC_TYPE /* disc_type */, + tGATT_STATUS status) { LOG_INFO("%s: status=%d", __func__, status); } diff --git a/system/btif/src/btif_gatt_util.cc b/system/btif/src/btif_gatt_util.cc index e1e61c8334..a054bc8fc1 100644 --- a/system/btif/src/btif_gatt_util.cc +++ b/system/btif/src/btif_gatt_util.cc @@ -33,7 +33,6 @@ #include "os/log.h" #include "os/system_properties.h" #include "osi/include/allocator.h" -#include "osi/include/osi.h" #include "stack/btm/btm_sec.h" #include "stack/include/acl_api.h" #include "types/ble_address_with_type.h" @@ -63,8 +62,8 @@ static bool btif_gatt_is_link_encrypted(const RawAddress& bd_addr) { BTM_IsEncrypted(bd_addr, BT_TRANSPORT_LE); } -static void btif_gatt_set_encryption_cb(UNUSED_ATTR const RawAddress& bd_addr, - UNUSED_ATTR tBT_TRANSPORT transport, +static void btif_gatt_set_encryption_cb(const RawAddress& /* bd_addr */, + tBT_TRANSPORT /* transport */, tBTA_STATUS result) { if (result != BTA_SUCCESS && result != BTA_BUSY) { LOG_WARN("%s() - Encryption failed (%d)", __func__, result); diff --git a/system/btif/src/btif_hf_client.cc b/system/btif/src/btif_hf_client.cc index 16b3ed7776..c46f85e5c9 100644 --- a/system/btif/src/btif_hf_client.cc +++ b/system/btif/src/btif_hf_client.cc @@ -55,7 +55,6 @@ #include "btif_common.h" #include "btif_profile_queue.h" #include "btif_util.h" -#include "osi/include/osi.h" #include "osi/include/properties.h" #include "stack/btm/btm_sco_hfp_hal.h" #include "stack/include/bt_uuid16.h" @@ -154,6 +153,7 @@ static btif_hf_client_cb_arr_t btif_hf_client_cb_arr; * Returns void * ******************************************************************************/ +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("%s", __func__); RawAddress* bd_addr = (RawAddress*)p_param; @@ -469,8 +469,7 @@ static bt_status_t volume_control(const RawAddress* bd_addr, * Returns bt_status_t * ******************************************************************************/ -static bt_status_t dial(UNUSED_ATTR const RawAddress* bd_addr, - const char* number) { +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)) return BT_STATUS_FAIL; @@ -602,7 +601,7 @@ static bt_status_t handle_call_action(const RawAddress* bd_addr, * Returns bt_status_t * ******************************************************************************/ -static bt_status_t query_current_calls(UNUSED_ATTR const RawAddress* bd_addr) { +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)) return BT_STATUS_FAIL; diff --git a/system/btif/src/btif_hh.cc b/system/btif/src/btif_hh.cc index 80be79a974..732899fd38 100644 --- a/system/btif/src/btif_hh.cc +++ b/system/btif/src/btif_hh.cc @@ -45,7 +45,6 @@ #include "osi/include/allocator.h" #include "stack/include/bt_hdr.h" #include "stack/include/hidh_api.h" -#include "stack/include/l2c_api.h" #include "types/raw_address.h" #define COD_HID_KEYBOARD 0x0540 @@ -1537,7 +1536,7 @@ static bt_status_t set_info(RawAddress* bd_addr, bthh_hid_info_t hid_info) { * ******************************************************************************/ static bt_status_t get_protocol(RawAddress* bd_addr, - UNUSED_ATTR bthh_protocol_mode_t protocolMode) { + bthh_protocol_mode_t /* protocolMode */) { CHECK_BTHH_INIT(); VLOG(1) << __func__ << " BTHH: addr = " << ADDRESS_TO_LOGGABLE_STR(*bd_addr); diff --git a/system/btif/src/btif_pan.cc b/system/btif/src/btif_pan.cc index 426ae4ac05..7ed00ae2f8 100644 --- a/system/btif/src/btif_pan.cc +++ b/system/btif/src/btif_pan.cc @@ -50,7 +50,6 @@ #include "os/log.h" #include "osi/include/allocator.h" #include "osi/include/compat.h" -#include "osi/include/osi.h" #include "stack/include/bt_hdr.h" #include "stack/include/main_thread.h" #include "stack/include/pan_api.h" @@ -211,6 +210,7 @@ static bt_status_t btpan_connect(const RawAddress* bd_addr, int local_role, return BT_STATUS_SUCCESS; } +constexpr uint16_t BTIF_PAN_CB_DISCONNECTING = 0x8401; static void btif_in_pan_generic_evt(uint16_t event, char* p_param) { LOG_VERBOSE("%s: event=%d", __func__, event); switch (event) { @@ -391,7 +391,7 @@ int btpan_tap_open() { int btpan_tap_send(int tap_fd, const RawAddress& src, const RawAddress& dst, uint16_t proto, const char* buf, uint16_t len, - UNUSED_ATTR bool ext, UNUSED_ATTR bool forward) { + bool /* ext */, bool /* forward */) { if (tap_fd != INVALID_FD) { tETH_HDR eth_hdr; eth_hdr.h_dest = dst; diff --git a/system/btif/src/btif_profile_storage.cc b/system/btif/src/btif_profile_storage.cc index 568b827b7d..b151ddf209 100644 --- a/system/btif/src/btif_profile_storage.cc +++ b/system/btif/src/btif_profile_storage.cc @@ -42,6 +42,7 @@ #include "btif_storage.h" #include "stack/include/bt_uuid16.h" #include "stack/include/main_thread.h" +#include "storage/config_keys.h" #include "types/bluetooth/uuid.h" #include "types/raw_address.h" @@ -53,22 +54,6 @@ using bluetooth::groups::DeviceGroups; /******************************************************************************* * Constants & Macros ******************************************************************************/ -#define BTIF_STORAGE_PATH_REMOTE_DEVCLASS "DevClass" - -#define BTIF_STORAGE_CSIS_AUTOCONNECT "CsisAutoconnect" -#define BTIF_STORAGE_CSIS_SET_INFO_BIN "CsisSetInfoBin" -#define BTIF_STORAGE_LEAUDIO_AUTOCONNECT "LeAudioAutoconnect" -#define BTIF_STORAGE_LEAUDIO_HANDLES_BIN "LeAudioHandlesBin" -#define BTIF_STORAGE_LEAUDIO_SINK_PACS_BIN "SinkPacsBin" -#define BTIF_STORAGE_LEAUDIO_SOURCE_PACS_BIN "SourcePacsBin" -#define BTIF_STORAGE_LEAUDIO_ASES_BIN "AsesBin" -#define BTIF_STORAGE_LEAUDIO_SINK_AUDIOLOCATION "SinkAudioLocation" -#define BTIF_STORAGE_LEAUDIO_SOURCE_AUDIOLOCATION "SourceAudioLocation" -#define BTIF_STORAGE_LEAUDIO_SINK_SUPPORTED_CONTEXT_TYPE \ - "SinkSupportedContextType" -#define BTIF_STORAGE_LEAUDIO_SOURCE_SUPPORTED_CONTEXT_TYPE \ - "SourceSupportedContextType" -#define BTIF_STORAGE_DEVICE_GROUP_BIN "DeviceGroupBin" #define STORAGE_HID_ATRR_MASK_SIZE (4) #define STORAGE_HID_SUB_CLASS_SIZE (2) @@ -112,16 +97,20 @@ bt_status_t btif_storage_add_hid_device_info( uint16_t dl_len, uint8_t* dsc_list) { LOG_VERBOSE("btif_storage_add_hid_device_info:"); std::string bdstr = remote_bd_addr->ToString(); - btif_config_set_int(bdstr, "HidAttrMask", attr_mask); - btif_config_set_int(bdstr, "HidSubClass", sub_class); - btif_config_set_int(bdstr, "HidAppId", app_id); - btif_config_set_int(bdstr, "HidVendorId", vendor_id); - btif_config_set_int(bdstr, "HidProductId", product_id); - btif_config_set_int(bdstr, "HidVersion", version); - btif_config_set_int(bdstr, "HidCountryCode", ctry_code); - btif_config_set_int(bdstr, "HidSSRMaxLatency", ssr_max_latency); - btif_config_set_int(bdstr, "HidSSRMinTimeout", ssr_min_tout); - if (dl_len > 0) btif_config_set_bin(bdstr, "HidDescriptor", dsc_list, dl_len); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_ATTR_MASK, attr_mask); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_SUB_CLASS, sub_class); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_APP_ID, app_id); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_VENDOR_ID, vendor_id); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_PRODUCT_ID, product_id); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_VERSION, version); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_COUNTRY_CODE, ctry_code); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_SSR_MAX_LATENCY, + ssr_max_latency); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_SSR_MIN_TIMEOUT, + ssr_min_tout); + if (dl_len > 0) + btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_HID_DESCRIPTOR, dsc_list, + dl_len); return BT_STATUS_SUCCESS; } @@ -142,7 +131,8 @@ bt_status_t btif_storage_load_bonded_hid_info(void) { LOG_VERBOSE("Remote device:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr)); int value; - if (!btif_config_get_int(name, "HidAttrMask", &value)) continue; + if (!btif_config_get_int(name, BTIF_STORAGE_KEY_HID_ATTR_MASK, &value)) + continue; uint16_t attr_mask = (uint16_t)value; if (btif_in_fetch_bonded_device(name) != BT_STATUS_SUCCESS) { @@ -153,37 +143,38 @@ bt_status_t btif_storage_load_bonded_hid_info(void) { tBTA_HH_DEV_DSCP_INFO dscp_info; memset(&dscp_info, 0, sizeof(dscp_info)); - btif_config_get_int(name, "HidSubClass", &value); + btif_config_get_int(name, BTIF_STORAGE_KEY_HID_SUB_CLASS, &value); uint8_t sub_class = (uint8_t)value; - btif_config_get_int(name, "HidAppId", &value); + btif_config_get_int(name, BTIF_STORAGE_KEY_HID_APP_ID, &value); uint8_t app_id = (uint8_t)value; - btif_config_get_int(name, "HidVendorId", &value); + btif_config_get_int(name, BTIF_STORAGE_KEY_HID_VENDOR_ID, &value); dscp_info.vendor_id = (uint16_t)value; - btif_config_get_int(name, "HidProductId", &value); + btif_config_get_int(name, BTIF_STORAGE_KEY_HID_PRODUCT_ID, &value); dscp_info.product_id = (uint16_t)value; - btif_config_get_int(name, "HidVersion", &value); + btif_config_get_int(name, BTIF_STORAGE_KEY_HID_VERSION, &value); dscp_info.version = (uint16_t)value; - btif_config_get_int(name, "HidCountryCode", &value); + btif_config_get_int(name, BTIF_STORAGE_KEY_HID_COUNTRY_CODE, &value); dscp_info.ctry_code = (uint8_t)value; value = 0; - btif_config_get_int(name, "HidSSRMaxLatency", &value); + btif_config_get_int(name, BTIF_STORAGE_KEY_HID_SSR_MAX_LATENCY, &value); dscp_info.ssr_max_latency = (uint16_t)value; value = 0; - btif_config_get_int(name, "HidSSRMinTimeout", &value); + btif_config_get_int(name, BTIF_STORAGE_KEY_HID_SSR_MIN_TIMEOUT, &value); dscp_info.ssr_min_tout = (uint16_t)value; - size_t len = btif_config_get_bin_length(name, "HidDescriptor"); + size_t len = + btif_config_get_bin_length(name, BTIF_STORAGE_KEY_HID_DESCRIPTOR); if (len > 0) { dscp_info.descriptor.dl_len = (uint16_t)len; dscp_info.descriptor.dsc_list = (uint8_t*)alloca(len); - btif_config_get_bin(name, "HidDescriptor", + btif_config_get_bin(name, BTIF_STORAGE_KEY_HID_DESCRIPTOR, (uint8_t*)dscp_info.descriptor.dsc_list, &len); } @@ -210,18 +201,18 @@ bt_status_t btif_storage_load_bonded_hid_info(void) { bt_status_t btif_storage_remove_hid_info(const RawAddress& remote_bd_addr) { std::string bdstr = remote_bd_addr.ToString(); - btif_config_remove(bdstr, "HidAttrMask"); - btif_config_remove(bdstr, "HidSubClass"); - btif_config_remove(bdstr, "HidAppId"); - btif_config_remove(bdstr, "HidVendorId"); - btif_config_remove(bdstr, "HidProductId"); - btif_config_remove(bdstr, "HidVersion"); - btif_config_remove(bdstr, "HidCountryCode"); - btif_config_remove(bdstr, "HidSSRMaxLatency"); - btif_config_remove(bdstr, "HidSSRMinTimeout"); - btif_config_remove(bdstr, "HidDescriptor"); - btif_config_remove(bdstr, "HidReport"); - btif_config_remove(bdstr, "HidReportVersion"); + btif_config_remove(bdstr, BTIF_STORAGE_KEY_HID_ATTR_MASK); + btif_config_remove(bdstr, BTIF_STORAGE_KEY_HID_SUB_CLASS); + btif_config_remove(bdstr, BTIF_STORAGE_KEY_HID_APP_ID); + btif_config_remove(bdstr, BTIF_STORAGE_KEY_HID_VENDOR_ID); + btif_config_remove(bdstr, BTIF_STORAGE_KEY_HID_PRODUCT_ID); + btif_config_remove(bdstr, BTIF_STORAGE_KEY_HID_VERSION); + btif_config_remove(bdstr, BTIF_STORAGE_KEY_HID_COUNTRY_CODE); + btif_config_remove(bdstr, BTIF_STORAGE_KEY_HID_SSR_MAX_LATENCY); + btif_config_remove(bdstr, BTIF_STORAGE_KEY_HID_SSR_MIN_TIMEOUT); + btif_config_remove(bdstr, BTIF_STORAGE_KEY_HID_DESCRIPTOR); + btif_config_remove(bdstr, BTIF_STORAGE_KEY_HID_REPORT); + btif_config_remove(bdstr, BTIF_STORAGE_KEY_HID_REPORT_VERSION); return BT_STATUS_SUCCESS; } @@ -230,7 +221,7 @@ static bool btif_device_supports_profile(const std::string& device, const Uuid& profile) { int size = STORAGE_UUID_STRING_SIZE * BT_MAX_NUM_UUIDS; char uuid_str[size]; - if (btif_config_get_str(device, BTIF_STORAGE_PATH_REMOTE_SERVICE, uuid_str, + if (btif_config_get_str(device, BTIF_STORAGE_KEY_REMOTE_SERVICE, uuid_str, &size)) { Uuid p_uuid[BT_MAX_NUM_UUIDS]; size_t num_uuids = @@ -297,8 +288,7 @@ std::vector<RawAddress> btif_storage_get_wake_capable_classic_hid_devices( constexpr int kHidMask = COD_HID_MAJOR; constexpr int kKeyboardMouseMask = COD_HID_COMBO & ~COD_HID_MAJOR; int cod_value; - if (!btif_config_get_int(name, BTIF_STORAGE_PATH_REMOTE_DEVCLASS, - &cod_value) || + if (!btif_config_get_int(name, BTIF_STORAGE_KEY_DEV_CLASS, &cod_value) || (cod_value & kHidMask) != kHidMask || (cod_value & kKeyboardMouseMask) == 0) { continue; @@ -312,23 +302,6 @@ std::vector<RawAddress> btif_storage_get_wake_capable_classic_hid_devices( return hid_addresses; } -constexpr char HEARING_AID_READ_PSM_HANDLE[] = "HearingAidReadPsmHandle"; -constexpr char HEARING_AID_CAPABILITIES[] = "HearingAidCapabilities"; -constexpr char HEARING_AID_CODECS[] = "HearingAidCodecs"; -constexpr char HEARING_AID_AUDIO_CONTROL_POINT[] = - "HearingAidAudioControlPoint"; -constexpr char HEARING_AID_VOLUME_HANDLE[] = "HearingAidVolumeHandle"; -constexpr char HEARING_AID_AUDIO_STATUS_HANDLE[] = - "HearingAidAudioStatusHandle"; -constexpr char HEARING_AID_AUDIO_STATUS_CCC_HANDLE[] = - "HearingAidAudioStatusCccHandle"; -constexpr char HEARING_AID_SERVICE_CHANGED_CCC_HANDLE[] = - "HearingAidServiceChangedCccHandle"; -constexpr char HEARING_AID_SYNC_ID[] = "HearingAidSyncId"; -constexpr char HEARING_AID_RENDER_DELAY[] = "HearingAidRenderDelay"; -constexpr char HEARING_AID_PREPARATION_DELAY[] = "HearingAidPreparationDelay"; -constexpr char HEARING_AID_IS_ACCEPTLISTED[] = "HearingAidIsAcceptlisted"; - void btif_storage_add_hearing_aid(const HearingDevice& dev_info) { do_in_jni_thread( FROM_HERE, @@ -337,28 +310,39 @@ void btif_storage_add_hearing_aid(const HearingDevice& dev_info) { std::string bdstr = dev_info.address.ToString(); VLOG(2) << "saving hearing aid device: " << ADDRESS_TO_LOGGABLE_STR(dev_info.address); - btif_config_set_int(bdstr, HEARING_AID_SERVICE_CHANGED_CCC_HANDLE, - dev_info.service_changed_ccc_handle); - btif_config_set_int(bdstr, HEARING_AID_READ_PSM_HANDLE, + btif_config_set_int( + bdstr, BTIF_STORAGE_KEY_HEARING_AID_SERVICE_CHANGED_CCC_HANDLE, + dev_info.service_changed_ccc_handle); + btif_config_set_int(bdstr, + BTIF_STORAGE_KEY_HEARING_AID_READ_PSM_HANDLE, dev_info.read_psm_handle); - btif_config_set_int(bdstr, HEARING_AID_CAPABILITIES, + btif_config_set_int(bdstr, + BTIF_STORAGE_KEY_HEARING_AID_CAPABILITIES, dev_info.capabilities); - btif_config_set_int(bdstr, HEARING_AID_CODECS, dev_info.codecs); - btif_config_set_int(bdstr, HEARING_AID_AUDIO_CONTROL_POINT, - dev_info.audio_control_point_handle); - btif_config_set_int(bdstr, HEARING_AID_VOLUME_HANDLE, + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HEARING_AID_CODECS, + dev_info.codecs); + btif_config_set_int( + bdstr, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_CONTROL_POINT, + dev_info.audio_control_point_handle); + btif_config_set_int(bdstr, + BTIF_STORAGE_KEY_HEARING_AID_VOLUME_HANDLE, dev_info.volume_handle); - btif_config_set_int(bdstr, HEARING_AID_AUDIO_STATUS_HANDLE, - dev_info.audio_status_handle); - btif_config_set_int(bdstr, HEARING_AID_AUDIO_STATUS_CCC_HANDLE, - dev_info.audio_status_ccc_handle); - btif_config_set_uint64(bdstr, HEARING_AID_SYNC_ID, + btif_config_set_int( + bdstr, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_STATUS_HANDLE, + dev_info.audio_status_handle); + btif_config_set_int( + bdstr, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_STATUS_CCC_HANDLE, + dev_info.audio_status_ccc_handle); + btif_config_set_uint64(bdstr, BTIF_STORAGE_KEY_HEARING_AID_SYNC_ID, dev_info.hi_sync_id); - btif_config_set_int(bdstr, HEARING_AID_RENDER_DELAY, + btif_config_set_int(bdstr, + BTIF_STORAGE_KEY_HEARING_AID_RENDER_DELAY, dev_info.render_delay); - btif_config_set_int(bdstr, HEARING_AID_PREPARATION_DELAY, + btif_config_set_int(bdstr, + BTIF_STORAGE_KEY_HEARING_AID_PREPARATION_DELAY, dev_info.preparation_delay); - btif_config_set_int(bdstr, HEARING_AID_IS_ACCEPTLISTED, true); + btif_config_set_int( + bdstr, BTIF_STORAGE_KEY_HEARING_AID_IS_ACCEPTLISTED, true); }, dev_info)); } @@ -371,7 +355,7 @@ void btif_storage_load_bonded_hearing_aids() { int size = STORAGE_UUID_STRING_SIZE * BT_MAX_NUM_UUIDS; char uuid_str[size]; bool isHearingaidDevice = false; - if (btif_config_get_str(name, BTIF_STORAGE_PATH_REMOTE_SERVICE, uuid_str, + if (btif_config_get_str(name, BTIF_STORAGE_KEY_REMOTE_SERVICE, uuid_str, &size)) { Uuid p_uuid[BT_MAX_NUM_UUIDS]; size_t num_uuids = @@ -396,52 +380,64 @@ void btif_storage_load_bonded_hearing_aids() { int value; uint8_t capabilities = 0; - if (btif_config_get_int(name, HEARING_AID_CAPABILITIES, &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_CAPABILITIES, + &value)) capabilities = value; uint16_t codecs = 0; - if (btif_config_get_int(name, HEARING_AID_CODECS, &value)) codecs = value; + if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_CODECS, &value)) + codecs = value; uint16_t audio_control_point_handle = 0; - if (btif_config_get_int(name, HEARING_AID_AUDIO_CONTROL_POINT, &value)) + if (btif_config_get_int( + name, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_CONTROL_POINT, &value)) audio_control_point_handle = value; uint16_t audio_status_handle = 0; - if (btif_config_get_int(name, HEARING_AID_AUDIO_STATUS_HANDLE, &value)) + if (btif_config_get_int( + name, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_STATUS_HANDLE, &value)) audio_status_handle = value; uint16_t audio_status_ccc_handle = 0; - if (btif_config_get_int(name, HEARING_AID_AUDIO_STATUS_CCC_HANDLE, &value)) + if (btif_config_get_int( + name, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_STATUS_CCC_HANDLE, &value)) audio_status_ccc_handle = value; uint16_t service_changed_ccc_handle = 0; - if (btif_config_get_int(name, HEARING_AID_SERVICE_CHANGED_CCC_HANDLE, - &value)) + if (btif_config_get_int( + name, BTIF_STORAGE_KEY_HEARING_AID_SERVICE_CHANGED_CCC_HANDLE, + &value)) service_changed_ccc_handle = value; uint16_t volume_handle = 0; - if (btif_config_get_int(name, HEARING_AID_VOLUME_HANDLE, &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_VOLUME_HANDLE, + &value)) volume_handle = value; uint16_t read_psm_handle = 0; - if (btif_config_get_int(name, HEARING_AID_READ_PSM_HANDLE, &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_READ_PSM_HANDLE, + &value)) read_psm_handle = value; uint64_t lvalue; uint64_t hi_sync_id = 0; - if (btif_config_get_uint64(name, HEARING_AID_SYNC_ID, &lvalue)) + if (btif_config_get_uint64(name, BTIF_STORAGE_KEY_HEARING_AID_SYNC_ID, + &lvalue)) hi_sync_id = lvalue; uint16_t render_delay = 0; - if (btif_config_get_int(name, HEARING_AID_RENDER_DELAY, &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_RENDER_DELAY, + &value)) render_delay = value; uint16_t preparation_delay = 0; - if (btif_config_get_int(name, HEARING_AID_PREPARATION_DELAY, &value)) + if (btif_config_get_int( + name, BTIF_STORAGE_KEY_HEARING_AID_PREPARATION_DELAY, &value)) preparation_delay = value; bool is_acceptlisted = false; - if (btif_config_get_int(name, HEARING_AID_IS_ACCEPTLISTED, &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_HEARING_AID_IS_ACCEPTLISTED, + &value)) is_acceptlisted = value; // add extracted information to BTA Hearing Aid @@ -460,18 +456,20 @@ void btif_storage_load_bonded_hearing_aids() { /** Deletes the bonded hearing aid device info from NVRAM */ void btif_storage_remove_hearing_aid(const RawAddress& address) { std::string addrstr = address.ToString(); - btif_config_remove(addrstr, HEARING_AID_READ_PSM_HANDLE); - btif_config_remove(addrstr, HEARING_AID_CAPABILITIES); - btif_config_remove(addrstr, HEARING_AID_CODECS); - btif_config_remove(addrstr, HEARING_AID_AUDIO_CONTROL_POINT); - btif_config_remove(addrstr, HEARING_AID_VOLUME_HANDLE); - btif_config_remove(addrstr, HEARING_AID_AUDIO_STATUS_HANDLE); - btif_config_remove(addrstr, HEARING_AID_AUDIO_STATUS_CCC_HANDLE); - btif_config_remove(addrstr, HEARING_AID_SERVICE_CHANGED_CCC_HANDLE); - btif_config_remove(addrstr, HEARING_AID_SYNC_ID); - btif_config_remove(addrstr, HEARING_AID_RENDER_DELAY); - btif_config_remove(addrstr, HEARING_AID_PREPARATION_DELAY); - btif_config_remove(addrstr, HEARING_AID_IS_ACCEPTLISTED); + btif_config_remove(addrstr, BTIF_STORAGE_KEY_HEARING_AID_READ_PSM_HANDLE); + btif_config_remove(addrstr, BTIF_STORAGE_KEY_HEARING_AID_CAPABILITIES); + btif_config_remove(addrstr, BTIF_STORAGE_KEY_HEARING_AID_CODECS); + btif_config_remove(addrstr, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_CONTROL_POINT); + btif_config_remove(addrstr, BTIF_STORAGE_KEY_HEARING_AID_VOLUME_HANDLE); + btif_config_remove(addrstr, BTIF_STORAGE_KEY_HEARING_AID_AUDIO_STATUS_HANDLE); + btif_config_remove(addrstr, + BTIF_STORAGE_KEY_HEARING_AID_AUDIO_STATUS_CCC_HANDLE); + btif_config_remove(addrstr, + BTIF_STORAGE_KEY_HEARING_AID_SERVICE_CHANGED_CCC_HANDLE); + btif_config_remove(addrstr, BTIF_STORAGE_KEY_HEARING_AID_SYNC_ID); + btif_config_remove(addrstr, BTIF_STORAGE_KEY_HEARING_AID_RENDER_DELAY); + btif_config_remove(addrstr, BTIF_STORAGE_KEY_HEARING_AID_PREPARATION_DELAY); + btif_config_remove(addrstr, BTIF_STORAGE_KEY_HEARING_AID_IS_ACCEPTLISTED); } /** Set/Unset the hearing aid device HEARING_AID_IS_ACCEPTLISTED flag. */ @@ -479,7 +477,8 @@ void btif_storage_set_hearing_aid_acceptlist(const RawAddress& address, bool add_to_acceptlist) { std::string addrstr = address.ToString(); - btif_config_set_int(addrstr, HEARING_AID_IS_ACCEPTLISTED, add_to_acceptlist); + btif_config_set_int(addrstr, BTIF_STORAGE_KEY_HEARING_AID_IS_ACCEPTLISTED, + add_to_acceptlist); } /** Get the hearing aid device properties. */ @@ -489,32 +488,37 @@ bool btif_storage_get_hearing_aid_prop( std::string addrstr = address.ToString(); int value; - if (btif_config_get_int(addrstr, HEARING_AID_CAPABILITIES, &value)) { + if (btif_config_get_int(addrstr, BTIF_STORAGE_KEY_HEARING_AID_CAPABILITIES, + &value)) { *capabilities = value; } else { return false; } - if (btif_config_get_int(addrstr, HEARING_AID_CODECS, &value)) { + if (btif_config_get_int(addrstr, BTIF_STORAGE_KEY_HEARING_AID_CODECS, + &value)) { *codecs = value; } else { return false; } - if (btif_config_get_int(addrstr, HEARING_AID_RENDER_DELAY, &value)) { + if (btif_config_get_int(addrstr, BTIF_STORAGE_KEY_HEARING_AID_RENDER_DELAY, + &value)) { *render_delay = value; } else { return false; } - if (btif_config_get_int(addrstr, HEARING_AID_PREPARATION_DELAY, &value)) { + if (btif_config_get_int( + addrstr, BTIF_STORAGE_KEY_HEARING_AID_PREPARATION_DELAY, &value)) { *preparation_delay = value; } else { return false; } uint64_t lvalue; - if (btif_config_get_uint64(addrstr, HEARING_AID_SYNC_ID, &lvalue)) { + if (btif_config_get_uint64(addrstr, BTIF_STORAGE_KEY_HEARING_AID_SYNC_ID, + &lvalue)) { *hi_sync_id = lvalue; } else { return false; @@ -532,7 +536,8 @@ void btif_storage_set_leaudio_autoconnect(const RawAddress& addr, VLOG(2) << "saving le audio device: " << ADDRESS_TO_LOGGABLE_CSTR(addr); btif_config_set_int( - bdstr, BTIF_STORAGE_LEAUDIO_AUTOCONNECT, + bdstr, + BTIF_STORAGE_KEY_LEAUDIO_AUTOCONNECT, autoconnect); }, addr, autoconnect)); @@ -548,7 +553,7 @@ void btif_storage_leaudio_update_handles_bin(const RawAddress& addr) { Bind( [](const RawAddress& bd_addr, std::vector<uint8_t> handles) { auto bdstr = bd_addr.ToString(); - btif_config_set_bin(bdstr, BTIF_STORAGE_LEAUDIO_HANDLES_BIN, + btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_LEAUDIO_HANDLES_BIN, handles.data(), handles.size()); }, addr, std::move(handles))); @@ -565,7 +570,7 @@ void btif_storage_leaudio_update_pacs_bin(const RawAddress& addr) { Bind( [](const RawAddress& bd_addr, std::vector<uint8_t> sink_pacs) { auto bdstr = bd_addr.ToString(); - btif_config_set_bin(bdstr, BTIF_STORAGE_LEAUDIO_SINK_PACS_BIN, + btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_LEAUDIO_SINK_PACS_BIN, sink_pacs.data(), sink_pacs.size()); }, addr, std::move(sink_pacs))); @@ -578,7 +583,8 @@ void btif_storage_leaudio_update_pacs_bin(const RawAddress& addr) { Bind( [](const RawAddress& bd_addr, std::vector<uint8_t> source_pacs) { auto bdstr = bd_addr.ToString(); - btif_config_set_bin(bdstr, BTIF_STORAGE_LEAUDIO_SOURCE_PACS_BIN, + btif_config_set_bin(bdstr, + BTIF_STORAGE_KEY_LEAUDIO_SOURCE_PACS_BIN, source_pacs.data(), source_pacs.size()); }, addr, std::move(source_pacs))); @@ -595,7 +601,7 @@ void btif_storage_leaudio_update_ase_bin(const RawAddress& addr) { Bind( [](const RawAddress& bd_addr, std::vector<uint8_t> ases) { auto bdstr = bd_addr.ToString(); - btif_config_set_bin(bdstr, BTIF_STORAGE_LEAUDIO_ASES_BIN, + btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_LEAUDIO_ASES_BIN, ases.data(), ases.size()); }, addr, std::move(ases))); @@ -613,10 +619,11 @@ void btif_storage_set_leaudio_audio_location(const RawAddress& addr, std::string bdstr = addr.ToString(); LOG_DEBUG("saving le audio device: %s", ADDRESS_TO_LOGGABLE_CSTR(addr)); - btif_config_set_int(bdstr, BTIF_STORAGE_LEAUDIO_SINK_AUDIOLOCATION, + btif_config_set_int(bdstr, + BTIF_STORAGE_KEY_LEAUDIO_SINK_AUDIOLOCATION, sink_location); btif_config_set_int(bdstr, - BTIF_STORAGE_LEAUDIO_SOURCE_AUDIOLOCATION, + BTIF_STORAGE_KEY_LEAUDIO_SOURCE_AUDIOLOCATION, source_location); }, addr, sink_location, source_location)); @@ -635,10 +642,10 @@ void btif_storage_set_leaudio_supported_context_types( LOG_DEBUG("saving le audio device: %s", ADDRESS_TO_LOGGABLE_CSTR(addr)); btif_config_set_int( - bdstr, BTIF_STORAGE_LEAUDIO_SINK_SUPPORTED_CONTEXT_TYPE, + bdstr, BTIF_STORAGE_KEY_LEAUDIO_SINK_SUPPORTED_CONTEXT_TYPE, sink_supported_context_type); btif_config_set_int( - bdstr, BTIF_STORAGE_LEAUDIO_SOURCE_SUPPORTED_CONTEXT_TYPE, + bdstr, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_SUPPORTED_CONTEXT_TYPE, source_supported_context_type); }, addr, sink_supported_context_type, source_supported_context_type)); @@ -652,7 +659,7 @@ void btif_storage_load_bonded_leaudio() { int size = STORAGE_UUID_STRING_SIZE * BT_MAX_NUM_UUIDS; char uuid_str[size]; bool isLeAudioDevice = false; - if (btif_config_get_str(name, BTIF_STORAGE_PATH_REMOTE_SERVICE, uuid_str, + if (btif_config_get_str(name, BTIF_STORAGE_KEY_REMOTE_SERVICE, uuid_str, &size)) { Uuid p_uuid[BT_MAX_NUM_UUIDS]; size_t num_uuids = @@ -672,58 +679,59 @@ void btif_storage_load_bonded_leaudio() { int value; bool autoconnect = false; - if (btif_config_get_int(name, BTIF_STORAGE_LEAUDIO_AUTOCONNECT, &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_AUTOCONNECT, &value)) autoconnect = !!value; int sink_audio_location = 0; - if (btif_config_get_int(name, BTIF_STORAGE_LEAUDIO_SINK_AUDIOLOCATION, + if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_SINK_AUDIOLOCATION, &value)) sink_audio_location = value; int source_audio_location = 0; - if (btif_config_get_int(name, BTIF_STORAGE_LEAUDIO_SOURCE_AUDIOLOCATION, + if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_AUDIOLOCATION, &value)) source_audio_location = value; int sink_supported_context_type = 0; if (btif_config_get_int( - name, BTIF_STORAGE_LEAUDIO_SINK_SUPPORTED_CONTEXT_TYPE, &value)) + name, BTIF_STORAGE_KEY_LEAUDIO_SINK_SUPPORTED_CONTEXT_TYPE, &value)) sink_supported_context_type = value; int source_supported_context_type = 0; if (btif_config_get_int( - name, BTIF_STORAGE_LEAUDIO_SOURCE_SUPPORTED_CONTEXT_TYPE, &value)) + name, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_SUPPORTED_CONTEXT_TYPE, + &value)) source_supported_context_type = value; size_t buffer_size = - btif_config_get_bin_length(name, BTIF_STORAGE_LEAUDIO_HANDLES_BIN); + btif_config_get_bin_length(name, BTIF_STORAGE_KEY_LEAUDIO_HANDLES_BIN); std::vector<uint8_t> handles(buffer_size); if (buffer_size > 0) { - btif_config_get_bin(name, BTIF_STORAGE_LEAUDIO_HANDLES_BIN, + btif_config_get_bin(name, BTIF_STORAGE_KEY_LEAUDIO_HANDLES_BIN, handles.data(), &buffer_size); } - buffer_size = - btif_config_get_bin_length(name, BTIF_STORAGE_LEAUDIO_SINK_PACS_BIN); + buffer_size = btif_config_get_bin_length( + name, BTIF_STORAGE_KEY_LEAUDIO_SINK_PACS_BIN); std::vector<uint8_t> sink_pacs(buffer_size); if (buffer_size > 0) { - btif_config_get_bin(name, BTIF_STORAGE_LEAUDIO_SINK_PACS_BIN, + btif_config_get_bin(name, BTIF_STORAGE_KEY_LEAUDIO_SINK_PACS_BIN, sink_pacs.data(), &buffer_size); } - buffer_size = - btif_config_get_bin_length(name, BTIF_STORAGE_LEAUDIO_SOURCE_PACS_BIN); + buffer_size = btif_config_get_bin_length( + name, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_PACS_BIN); std::vector<uint8_t> source_pacs(buffer_size); if (buffer_size > 0) { - btif_config_get_bin(name, BTIF_STORAGE_LEAUDIO_SOURCE_PACS_BIN, + btif_config_get_bin(name, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_PACS_BIN, source_pacs.data(), &buffer_size); } buffer_size = - btif_config_get_bin_length(name, BTIF_STORAGE_LEAUDIO_ASES_BIN); + btif_config_get_bin_length(name, BTIF_STORAGE_KEY_LEAUDIO_ASES_BIN); std::vector<uint8_t> ases(buffer_size); if (buffer_size > 0) { - btif_config_get_bin(name, BTIF_STORAGE_LEAUDIO_ASES_BIN, ases.data(), + btif_config_get_bin(name, BTIF_STORAGE_KEY_LEAUDIO_ASES_BIN, ases.data(), &buffer_size); } @@ -739,22 +747,17 @@ void btif_storage_load_bonded_leaudio() { void btif_storage_leaudio_clear_service_data(const RawAddress& address) { auto bdstr = address.ToString(); - btif_config_remove(bdstr, BTIF_STORAGE_LEAUDIO_HANDLES_BIN); - btif_config_remove(bdstr, BTIF_STORAGE_LEAUDIO_SINK_PACS_BIN); - btif_config_remove(bdstr, BTIF_STORAGE_LEAUDIO_ASES_BIN); + btif_config_remove(bdstr, BTIF_STORAGE_KEY_LEAUDIO_HANDLES_BIN); + btif_config_remove(bdstr, BTIF_STORAGE_KEY_LEAUDIO_SINK_PACS_BIN); + btif_config_remove(bdstr, BTIF_STORAGE_KEY_LEAUDIO_ASES_BIN); } /** Remove the Le Audio device from storage */ void btif_storage_remove_leaudio(const RawAddress& address) { std::string addrstr = address.ToString(); - btif_config_set_int(addrstr, BTIF_STORAGE_LEAUDIO_AUTOCONNECT, false); + btif_config_set_int(addrstr, BTIF_STORAGE_KEY_LEAUDIO_AUTOCONNECT, false); } -constexpr char HAS_IS_ACCEPTLISTED[] = "LeAudioHasIsAcceptlisted"; -constexpr char HAS_FEATURES[] = "LeAudioHasFlags"; -constexpr char HAS_ACTIVE_PRESET[] = "LeAudioHasActivePreset"; -constexpr char HAS_SERIALIZED_PRESETS[] = "LeAudioHasSerializedPresets"; - void btif_storage_add_leaudio_has_device(const RawAddress& address, std::vector<uint8_t> presets_bin, uint8_t features, @@ -766,12 +769,17 @@ void btif_storage_add_leaudio_has_device(const RawAddress& address, uint8_t features, uint8_t active_preset) { const std::string& name = address.ToString(); - btif_config_set_int(name, HAS_FEATURES, features); - btif_config_set_int(name, HAS_ACTIVE_PRESET, active_preset); - btif_config_set_bin(name, HAS_SERIALIZED_PRESETS, + btif_config_set_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_FLAGS, + features); + btif_config_set_int(name, + BTIF_STORAGE_KEY_LEAUDIO_HAS_ACTIVE_PRESET, + active_preset); + btif_config_set_bin(name, + BTIF_STORAGE_KEY_LEAUDIO_HAS_SERIALIZED_PRESETS, presets_bin.data(), presets_bin.size()); - btif_config_set_int(name, HAS_IS_ACCEPTLISTED, true); + btif_config_set_int( + name, BTIF_STORAGE_KEY_LEAUDIO_HAS_IS_ACCEPTLISTED, true); }, address, std::move(presets_bin), features, active_preset)); } @@ -783,8 +791,9 @@ void btif_storage_set_leaudio_has_active_preset(const RawAddress& address, [](const RawAddress& address, uint8_t active_preset) { const std::string& name = address.ToString(); - btif_config_set_int(name, HAS_ACTIVE_PRESET, - active_preset); + btif_config_set_int( + name, BTIF_STORAGE_KEY_LEAUDIO_HAS_ACTIVE_PRESET, + active_preset); }, address, active_preset)); } @@ -794,7 +803,8 @@ bool btif_storage_get_leaudio_has_features(const RawAddress& address, std::string name = address.ToString(); int value; - if (!btif_config_get_int(name, HAS_FEATURES, &value)) return false; + if (!btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_FLAGS, &value)) + return false; features = value; return true; @@ -807,7 +817,9 @@ void btif_storage_set_leaudio_has_features(const RawAddress& address, [](const RawAddress& address, uint8_t features) { const std::string& name = address.ToString(); - btif_config_set_int(name, HAS_FEATURES, features); + btif_config_set_int(name, + BTIF_STORAGE_KEY_LEAUDIO_HAS_FLAGS, + features); }, address, features)); } @@ -816,18 +828,21 @@ void btif_storage_load_bonded_leaudio_has_devices() { for (const auto& bd_addr : btif_config_get_paired_devices()) { const std::string& name = bd_addr.ToString(); - if (!btif_config_exist(name, HAS_IS_ACCEPTLISTED) && - !btif_config_exist(name, HAS_FEATURES)) + if (!btif_config_exist(name, + BTIF_STORAGE_KEY_LEAUDIO_HAS_IS_ACCEPTLISTED) && + !btif_config_exist(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_FLAGS)) continue; #ifndef TARGET_FLOSS int value; uint16_t is_acceptlisted = 0; - if (btif_config_get_int(name, HAS_IS_ACCEPTLISTED, &value)) + if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_IS_ACCEPTLISTED, + &value)) is_acceptlisted = value; uint8_t features = 0; - if (btif_config_get_int(name, HAS_FEATURES, &value)) features = value; + if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_FLAGS, &value)) + features = value; do_in_main_thread(FROM_HERE, Bind(&le_audio::has::HasClient::AddFromStorage, bd_addr, features, is_acceptlisted)); @@ -839,17 +854,18 @@ void btif_storage_load_bonded_leaudio_has_devices() { void btif_storage_remove_leaudio_has(const RawAddress& address) { std::string addrstr = address.ToString(); - btif_config_remove(addrstr, HAS_IS_ACCEPTLISTED); - btif_config_remove(addrstr, HAS_FEATURES); - btif_config_remove(addrstr, HAS_ACTIVE_PRESET); - btif_config_remove(addrstr, HAS_SERIALIZED_PRESETS); + btif_config_remove(addrstr, BTIF_STORAGE_KEY_LEAUDIO_HAS_IS_ACCEPTLISTED); + btif_config_remove(addrstr, BTIF_STORAGE_KEY_LEAUDIO_HAS_FLAGS); + btif_config_remove(addrstr, BTIF_STORAGE_KEY_LEAUDIO_HAS_ACTIVE_PRESET); + btif_config_remove(addrstr, BTIF_STORAGE_KEY_LEAUDIO_HAS_SERIALIZED_PRESETS); } void btif_storage_set_leaudio_has_acceptlist(const RawAddress& address, bool add_to_acceptlist) { std::string addrstr = address.ToString(); - btif_config_set_int(addrstr, HAS_IS_ACCEPTLISTED, add_to_acceptlist); + btif_config_set_int(addrstr, BTIF_STORAGE_KEY_LEAUDIO_HAS_IS_ACCEPTLISTED, + add_to_acceptlist); } void btif_storage_set_leaudio_has_presets(const RawAddress& address, @@ -860,7 +876,8 @@ void btif_storage_set_leaudio_has_presets(const RawAddress& address, [](const RawAddress& address, std::vector<uint8_t> presets_bin) { const std::string& name = address.ToString(); - btif_config_set_bin(name, HAS_SERIALIZED_PRESETS, + btif_config_set_bin(name, + BTIF_STORAGE_KEY_LEAUDIO_HAS_SERIALIZED_PRESETS, presets_bin.data(), presets_bin.size()); }, address, std::move(presets_bin))); @@ -872,13 +889,17 @@ bool btif_storage_get_leaudio_has_presets(const RawAddress& address, std::string name = address.ToString(); int value; - if (!btif_config_get_int(name, HAS_ACTIVE_PRESET, &value)) return false; + if (!btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_HAS_ACTIVE_PRESET, + &value)) + return false; active_preset = value; - auto bin_sz = btif_config_get_bin_length(name, HAS_SERIALIZED_PRESETS); + auto bin_sz = btif_config_get_bin_length( + name, BTIF_STORAGE_KEY_LEAUDIO_HAS_SERIALIZED_PRESETS); presets_bin.resize(bin_sz); - if (!btif_config_get_bin(name, HAS_SERIALIZED_PRESETS, presets_bin.data(), - &bin_sz)) + if (!btif_config_get_bin(name, + BTIF_STORAGE_KEY_LEAUDIO_HAS_SERIALIZED_PRESETS, + presets_bin.data(), &bin_sz)) return false; return true; @@ -895,7 +916,7 @@ void btif_storage_add_groups(const RawAddress& addr) { Bind( [](const RawAddress& bd_addr, std::vector<uint8_t> group_info) { auto bdstr = bd_addr.ToString(); - btif_config_set_bin(bdstr, BTIF_STORAGE_DEVICE_GROUP_BIN, + btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_DEVICE_GROUP_BIN, group_info.data(), group_info.size()); }, addr, std::move(group_info))); @@ -904,7 +925,7 @@ void btif_storage_add_groups(const RawAddress& addr) { /** Deletes the bonded Le Audio device grouping info from the NVRAM */ void btif_storage_remove_groups(const RawAddress& address) { std::string addrstr = address.ToString(); - btif_config_remove(addrstr, BTIF_STORAGE_DEVICE_GROUP_BIN); + btif_config_remove(addrstr, BTIF_STORAGE_KEY_DEVICE_GROUP_BIN); } /** Loads information about bonded group devices */ @@ -912,13 +933,13 @@ void btif_storage_load_bonded_groups(void) { for (const auto& bd_addr : btif_config_get_paired_devices()) { auto name = bd_addr.ToString(); size_t buffer_size = - btif_config_get_bin_length(name, BTIF_STORAGE_DEVICE_GROUP_BIN); + btif_config_get_bin_length(name, BTIF_STORAGE_KEY_DEVICE_GROUP_BIN); if (buffer_size == 0) continue; LOG_VERBOSE("Grouped device:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr)); std::vector<uint8_t> in(buffer_size); - if (btif_config_get_bin(name, BTIF_STORAGE_DEVICE_GROUP_BIN, in.data(), + if (btif_config_get_bin(name, BTIF_STORAGE_KEY_DEVICE_GROUP_BIN, in.data(), &buffer_size)) { do_in_main_thread(FROM_HERE, Bind(&DeviceGroups::AddFromStorage, bd_addr, std::move(in))); @@ -938,20 +959,6 @@ void btif_storage_load_bonded_volume_control_devices(void) { } } -void btif_storage_set_csis_autoconnect(const RawAddress& addr, - bool autoconnect) { - do_in_jni_thread(FROM_HERE, Bind( - [](const RawAddress& addr, bool autoconnect) { - std::string bdstr = addr.ToString(); - VLOG(2) << "Storing CSIS device: " - << ADDRESS_TO_LOGGABLE_CSTR(addr); - btif_config_set_int( - bdstr, BTIF_STORAGE_CSIS_AUTOCONNECT, - autoconnect); - }, - addr, autoconnect)); -} - /** Stores information about the bonded CSIS device */ void btif_storage_update_csis_info(const RawAddress& addr) { std::vector<uint8_t> set_info; @@ -963,7 +970,7 @@ void btif_storage_update_csis_info(const RawAddress& addr) { Bind( [](const RawAddress& bd_addr, std::vector<uint8_t> set_info) { auto bdstr = bd_addr.ToString(); - btif_config_set_bin(bdstr, BTIF_STORAGE_CSIS_SET_INFO_BIN, + btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_CSIS_SET_INFO_BIN, set_info.data(), set_info.size()); }, addr, std::move(set_info))); @@ -976,29 +983,24 @@ void btif_storage_load_bonded_csis_devices(void) { LOG_VERBOSE("Loading CSIS device:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr)); - int value; - bool autoconnect = false; - if (btif_config_get_int(name, BTIF_STORAGE_CSIS_AUTOCONNECT, &value)) - autoconnect = !!value; - size_t buffer_size = - btif_config_get_bin_length(name, BTIF_STORAGE_CSIS_SET_INFO_BIN); + btif_config_get_bin_length(name, BTIF_STORAGE_KEY_CSIS_SET_INFO_BIN); std::vector<uint8_t> in(buffer_size); if (buffer_size != 0) - btif_config_get_bin(name, BTIF_STORAGE_CSIS_SET_INFO_BIN, in.data(), + btif_config_get_bin(name, BTIF_STORAGE_KEY_CSIS_SET_INFO_BIN, in.data(), &buffer_size); - if (buffer_size != 0 || autoconnect) - do_in_main_thread(FROM_HERE, Bind(&CsisClient::AddFromStorage, bd_addr, - std::move(in), autoconnect)); + if (buffer_size != 0) + do_in_main_thread( + FROM_HERE, Bind(&CsisClient::AddFromStorage, bd_addr, std::move(in))); } } /** Removes information about the bonded CSIS device */ void btif_storage_remove_csis_device(const RawAddress& address) { std::string addrstr = address.ToString(); - btif_config_remove(addrstr, BTIF_STORAGE_CSIS_AUTOCONNECT); - btif_config_remove(addrstr, BTIF_STORAGE_CSIS_SET_INFO_BIN); + btif_config_remove(addrstr, BTIF_STORAGE_KEY_CSIS_AUTOCONNECT); + btif_config_remove(addrstr, BTIF_STORAGE_KEY_CSIS_SET_INFO_BIN); } /******************************************************************************* @@ -1016,7 +1018,8 @@ bt_status_t btif_storage_load_hidd(void) { LOG_VERBOSE("Remote device:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr)); int value; if (btif_in_fetch_bonded_device(name) == BT_STATUS_SUCCESS) { - if (btif_config_get_int(name, "HidDeviceCabled", &value)) { + if (btif_config_get_int(name, BTIF_STORAGE_KEY_HID_DEVICE_CABLED, + &value)) { BTA_HdAddDevice(bd_addr); break; } @@ -1042,11 +1045,12 @@ bt_status_t btif_storage_set_hidd(const RawAddress& remote_bd_addr) { auto name = bd_addr.ToString(); if (bd_addr == remote_bd_addr) continue; if (btif_in_fetch_bonded_device(name) == BT_STATUS_SUCCESS) { - btif_config_remove(name, "HidDeviceCabled"); + btif_config_remove(name, BTIF_STORAGE_KEY_HID_DEVICE_CABLED); } } - btif_config_set_int(remote_device_address_string, "HidDeviceCabled", 1); + btif_config_set_int(remote_device_address_string, + BTIF_STORAGE_KEY_HID_DEVICE_CABLED, 1); return BT_STATUS_SUCCESS; } @@ -1060,7 +1064,8 @@ bt_status_t btif_storage_set_hidd(const RawAddress& remote_bd_addr) { * ******************************************************************************/ bt_status_t btif_storage_remove_hidd(RawAddress* remote_bd_addr) { - btif_config_remove(remote_bd_addr->ToString(), "HidDeviceCabled"); + btif_config_remove(remote_bd_addr->ToString(), + BTIF_STORAGE_KEY_HID_DEVICE_CABLED); return BT_STATUS_SUCCESS; } @@ -1078,7 +1083,7 @@ void btif_storage_set_pce_profile_version(const RawAddress& remote_bd_addr, LOG_VERBOSE("peer_pce_version : 0x%x", peer_pce_version); if (btif_config_set_bin( - remote_bd_addr.ToString(), BT_CONFIG_KEY_PBAP_PCE_VERSION, + remote_bd_addr.ToString(), BTIF_STORAGE_KEY_PBAP_PCE_VERSION, (const uint8_t*)&peer_pce_version, sizeof(peer_pce_version))) { } else { LOG_WARN("Failed to store peer_pce_version for %s", @@ -1102,7 +1107,7 @@ bool btif_storage_is_pce_version_102(const RawAddress& remote_bd_addr) { uint16_t pce_version = 0; size_t version_value_size = sizeof(pce_version); if (!btif_config_get_bin(remote_bd_addr.ToString(), - BT_CONFIG_KEY_PBAP_PCE_VERSION, + BTIF_STORAGE_KEY_PBAP_PCE_VERSION, (uint8_t*)&pce_version, &version_value_size)) { LOG_VERBOSE("Failed to read cached peer PCE version for %s", ADDRESS_TO_LOGGABLE_CSTR(remote_bd_addr)); diff --git a/system/btif/src/btif_rc.cc b/system/btif/src/btif_rc.cc index 62b29e5128..20f4ddac94 100644 --- a/system/btif/src/btif_rc.cc +++ b/system/btif/src/btif_rc.cc @@ -50,7 +50,6 @@ #include "osi/include/alarm.h" #include "osi/include/allocator.h" #include "osi/include/list.h" -#include "osi/include/osi.h" // UNUSED_ATTR #include "osi/include/properties.h" #include "stack/include/avrc_api.h" #include "stack/include/avrc_defs.h" @@ -5821,7 +5820,7 @@ static void passthru_cmd_timeout_handler(btif_rc_device_cb_t* p_dev, * Returns None * **************************************************************************/ -static void btif_rc_transaction_timeout_handler(UNUSED_ATTR uint16_t event, +static void btif_rc_transaction_timeout_handler(uint16_t /* event */, char* data) { rc_transaction_context_t* p_context = (rc_transaction_context_t*)data; if (p_context == nullptr) { diff --git a/system/btif/src/btif_sock_rfc.cc b/system/btif/src/btif_sock_rfc.cc index 3690fa470f..e5746dc3bc 100644 --- a/system/btif/src/btif_sock_rfc.cc +++ b/system/btif/src/btif_sock_rfc.cc @@ -36,7 +36,6 @@ #include "btif/include/btif_sock_util.h" #include "include/check.h" #include "include/hardware/bt_sock.h" -#include "internal_include/bt_target.h" #include "os/log.h" #include "osi/include/allocator.h" #include "osi/include/compat.h" @@ -364,7 +363,8 @@ bt_status_t btsock_rfc_connect(const RawAddress* bd_addr, rfc_slot_t* slot = alloc_rfc_slot(bd_addr, NULL, *service_uuid, channel, flags, false); if (!slot) { - LOG_ERROR("%s unable to allocate RFCOMM slot.", __func__); + LOG_ERROR("unable to allocate RFCOMM slot. bd_addr:%s", + ADDRESS_TO_LOGGABLE_CSTR(*bd_addr)); return BT_STATUS_FAIL; } @@ -373,17 +373,22 @@ bt_status_t btsock_rfc_connect(const RawAddress* bd_addr, BTA_JvRfcommConnect(slot->security, slot->role, slot->scn, slot->addr, rfcomm_cback, slot->id); if (ret != BTA_JV_SUCCESS) { - LOG_ERROR("%s unable to initiate RFCOMM connection: %d", __func__, ret); + LOG_ERROR( + "unable to initiate RFCOMM connection. status:%d, scn:%d, bd_addr:%s", + ret, slot->scn, ADDRESS_TO_LOGGABLE_CSTR(slot->addr)); cleanup_rfc_slot(slot); return BT_STATUS_FAIL; } if (!send_app_scn(slot)) { - LOG_ERROR("%s unable to send channel number.", __func__); + LOG_ERROR("send_app_scn() failed, closing slot->id:%u", slot->id); cleanup_rfc_slot(slot); return BT_STATUS_FAIL; } } else { + LOG_INFO("service_uuid:%s, bd_addr:%s, slot_id:%u", + service_uuid->ToString().c_str(), + ADDRESS_TO_LOGGABLE_CSTR(*bd_addr), slot->id); if (!is_requesting_sdp()) { BTA_JvStartDiscovery(*bd_addr, 1, service_uuid, slot->id); slot->f.pending_sdp_request = false; @@ -471,9 +476,11 @@ static void cleanup_rfc_slot(rfc_slot_t* slot) { static bool send_app_scn(rfc_slot_t* slot) { if (slot->scn_notified) { - // already send, just return success. + // already sent, just return success. return true; } + LOG_DEBUG("Sending scn for slot %u. bd_addr:%s", slot->id, + ADDRESS_TO_LOGGABLE_CSTR(slot->addr)); slot->scn_notified = true; return sock_send_all(slot->fd, (const uint8_t*)&slot->scn, sizeof(slot->scn)) == sizeof(slot->scn); @@ -540,6 +547,7 @@ static void on_srv_rfc_listen_started(tBTA_JV_RFCOMM_START* p_start, static uint32_t on_srv_rfc_connect(tBTA_JV_RFCOMM_SRV_OPEN* p_open, uint32_t id) { + LOG_VERBOSE("id:%u", id); std::unique_lock<std::recursive_mutex> lock(slot_lock); rfc_slot_t* accept_rs; rfc_slot_t* srv_rs = find_rfc_slot_by_id(id); @@ -576,6 +584,7 @@ static uint32_t on_srv_rfc_connect(tBTA_JV_RFCOMM_SRV_OPEN* p_open, } static void on_cli_rfc_connect(tBTA_JV_RFCOMM_OPEN* p_open, uint32_t id) { + LOG_VERBOSE("id:%u", id); std::unique_lock<std::recursive_mutex> lock(slot_lock); rfc_slot_t* slot = find_rfc_slot_by_id(id); if (!slot) { @@ -614,6 +623,7 @@ static void on_cli_rfc_connect(tBTA_JV_RFCOMM_OPEN* p_open, uint32_t id) { static void on_rfc_close(UNUSED_ATTR tBTA_JV_RFCOMM_CLOSE* p_close, uint32_t id) { + LOG_VERBOSE("id:%u", id); std::unique_lock<std::recursive_mutex> lock(slot_lock); // rfc_handle already closed when receiving rfcomm close event from stack. @@ -672,6 +682,7 @@ static void on_rfc_outgoing_congest(tBTA_JV_RFCOMM_CONG* p, uint32_t id) { static uint32_t rfcomm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t rfcomm_slot_id) { uint32_t id = 0; + LOG_INFO("handling event:%d id:%u", event, rfcomm_slot_id); switch (event) { case BTA_JV_RFCOMM_START_EVT: @@ -720,6 +731,7 @@ static uint32_t rfcomm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, } static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id) { + LOG_INFO("handling event:%d, id:%u", event, id); switch (event) { case BTA_JV_GET_SCN_EVT: { std::unique_lock<std::recursive_mutex> lock(slot_lock); @@ -739,7 +751,7 @@ static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id) { rs->scn = p_data->scn; // Send channel ID to java layer if (!send_app_scn(rs)) { - LOG_DEBUG("send_app_scn() failed, closing rs->id:%d", rs->id); + LOG_WARN("send_app_scn() failed, closing rs->id:%d", rs->id); cleanup_rfc_slot(rs); break; } @@ -849,6 +861,7 @@ static void handle_discovery_comp(tBTA_JV_STATUS status, int scn, uint32_t id) { slot->f.doing_sdp_request = false; if (!send_app_scn(slot)) { + LOG_WARN("send_app_scn() failed, closing slot->id %u", slot->id); cleanup_rfc_slot(slot); return; } diff --git a/system/btif/src/btif_sock_sco.cc b/system/btif/src/btif_sock_sco.cc index 0c5168468d..a847323e77 100644 --- a/system/btif/src/btif_sock_sco.cc +++ b/system/btif/src/btif_sock_sco.cc @@ -30,7 +30,7 @@ #include "os/log.h" #include "osi/include/allocator.h" #include "osi/include/list.h" -#include "osi/include/osi.h" // UNUSED_ATTR +#include "osi/include/osi.h" // INVALID_FD #include "osi/include/socket.h" #include "osi/include/thread.h" #include "stack/include/btm_api.h" @@ -98,7 +98,7 @@ bt_status_t btsock_sco_cleanup(void) { return BT_STATUS_SUCCESS; } -bt_status_t btsock_sco_listen(int* sock_fd, UNUSED_ATTR int flags) { +bt_status_t btsock_sco_listen(int* sock_fd, int /* flags */) { CHECK(sock_fd != NULL); std::unique_lock<std::mutex> lock(sco_lock); @@ -113,7 +113,7 @@ bt_status_t btsock_sco_listen(int* sock_fd, UNUSED_ATTR int flags) { } bt_status_t btsock_sco_connect(const RawAddress* bd_addr, int* sock_fd, - UNUSED_ATTR int flags) { + int /* flags */) { CHECK(bd_addr != NULL); CHECK(sock_fd != NULL); @@ -305,7 +305,7 @@ static void disconnect_completed_cb(uint16_t sco_handle) { list_remove(sco_sockets, sco_socket); } -static void socket_read_ready_cb(UNUSED_ATTR socket_t* socket, void* context) { +static void socket_read_ready_cb(socket_t* /* socket */, void* context) { std::unique_lock<std::mutex> lock(sco_lock); sco_socket_t* sco_socket = (sco_socket_t*)context; diff --git a/system/btif/src/btif_storage.cc b/system/btif/src/btif_storage.cc index d9d12329ac..8e7b42323a 100644 --- a/system/btif/src/btif_storage.cc +++ b/system/btif/src/btif_storage.cc @@ -52,9 +52,13 @@ #include "osi/include/allocator.h" #include "stack/include/bt_octets.h" #include "stack/include/bt_uuid16.h" +#include "storage/config_keys.h" #include "types/bluetooth/uuid.h" #include "types/raw_address.h" +/* This is a local property to add a device found */ +#define BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP 0xFF + using base::Bind; using bluetooth::Uuid; @@ -62,48 +66,6 @@ using bluetooth::Uuid; * Constants & Macros ******************************************************************************/ -// TODO(armansito): Find a better way than using a hardcoded path. -#define BTIF_STORAGE_PATH_BLUEDROID "/data/misc/bluedroid" - -#define BTIF_STORAGE_SECTION_ADAPTER "Adapter" - -#define BTIF_STORAGE_KEY_LE_LOCAL_KEY_IR "LE_LOCAL_KEY_IR" -#define BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK "LE_LOCAL_KEY_IRK" -#define BTIF_STORAGE_KEY_LE_LOCAL_KEY_DHK "LE_LOCAL_KEY_DHK" -#define BTIF_STORAGE_KEY_LE_LOCAL_KEY_ER "LE_LOCAL_KEY_ER" - -#define BTIF_STORAGE_KEY_TIMESTAMP "Timestamp" -#define BTIF_STORAGE_KEY_DEV_CLASS "DevClass" -#define BTIF_STORAGE_KEY_DEV_TYPE "DevType" -#define BTIF_STORAGE_KEY_NAME "Name" -#define BTIF_STORAGE_KEY_APPEARANCE "Appearance" -#define BTIF_STORAGE_KEY_ADDR_TYPE "AddrType" -#define BTIF_STORAGE_KEY_ALIASE "Aliase" -#define BTIF_STORAGE_KEY_SCANMODE "ScanMode" -#define BTIF_STORAGE_KEY_LOCAL_IO_CAPS "LocalIOCaps" -#define BTIF_STORAGE_KEY_DISC_TIMEOUT "DiscoveryTimeout" -#define BTIF_STORAGE_KEY_GATT_CLIENT_SUPPORTED "GattClientSupportedFeatures" -#define BTIF_STORAGE_KEY_GATT_CLIENT_DB_HASH "GattClientDatabaseHash" -#define BTIF_STORAGE_KEY_GATT_SERVER_SUPPORTED "GattServerSupportedFeatures" -#define BTIF_STORAGE_KEY_LINK_KEY "LinkKey" -#define BTIF_STORAGE_KEY_LINK_KEY_TYPE "LinkKeyType" -#define BTIF_STORAGE_KEY_PIN_LENGTH "PinLength" -#define BTIF_STORAGE_KEY_LE_KEY_PENC "LE_KEY_PENC" -#define BTIF_STORAGE_KEY_LE_KEY_PID "LE_KEY_PID" -#define BTIF_STORAGE_KEY_LE_KEY_PCSRK "LE_KEY_PCSRK" -#define BTIF_STORAGE_KEY_LE_KEY_LENC "LE_KEY_LENC" -#define BTIF_STORAGE_KEY_LE_KEY_LCSRK "LE_KEY_LCSRK" -#define BTIF_STORAGE_KEY_LE_KEY_LID "LE_KEY_LID" -#define BTIF_STORAGE_KEY_VENDOR_ID_SOURCE "VendorIdSource" -#define BTIF_STORAGE_KEY_VENDOR_ID "VendorId" -#define BTIF_STORAGE_KEY_PRODUCT_ID "ProductId" -#define BTIF_STORAGE_KEY_VERSION "ProductVersion" -#define BTIF_STORAGE_KEY_RESTRICTED "Restricted" -#define BTIF_STORAGE_KEY_ADDR_TYPE "AddrType" - -/* This is a local property to add a device found */ -#define BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP 0xFF - struct BtifStorageKey { uint8_t type; const std::string& name; @@ -190,7 +152,7 @@ static bool prop2cfg(const RawAddress* remote_bd_addr, bt_property_t* prop) { case BT_PROPERTY_REMOTE_FRIENDLY_NAME: strncpy(value, (char*)prop->val, prop->len); value[prop->len] = '\0'; - btif_config_set_str(bdstr, BTIF_STORAGE_KEY_ALIASE, value); + btif_config_set_str(bdstr, BTIF_STORAGE_KEY_ALIAS, value); break; case BT_PROPERTY_ADAPTER_SCAN_MODE: btif_config_set_int(BTIF_STORAGE_SECTION_ADAPTER, @@ -216,7 +178,7 @@ static bool prop2cfg(const RawAddress* remote_bd_addr, bt_property_t* prop) { for (size_t i = 0; i < cnt; i++) { val += (reinterpret_cast<Uuid*>(prop->val) + i)->ToString() + " "; } - btif_config_set_str(bdstr, BTIF_STORAGE_PATH_REMOTE_SERVICE, val); + btif_config_set_str(bdstr, BTIF_STORAGE_KEY_REMOTE_SERVICE, val); break; } case BT_PROPERTY_REMOTE_VERSION_INFO: { @@ -224,10 +186,11 @@ static bool prop2cfg(const RawAddress* remote_bd_addr, bt_property_t* prop) { if (!info) return false; - btif_config_set_int(bdstr, BT_CONFIG_KEY_REMOTE_VER_MFCT, + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_MFCT, info->manufacturer); - btif_config_set_int(bdstr, BT_CONFIG_KEY_REMOTE_VER_VER, info->version); - btif_config_set_int(bdstr, BT_CONFIG_KEY_REMOTE_VER_SUBVER, + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_VER, + info->version); + btif_config_set_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_SUBVER, info->sub_ver); } break; case BT_PROPERTY_APPEARANCE: { @@ -247,7 +210,7 @@ static bool prop2cfg(const RawAddress* remote_bd_addr, bt_property_t* prop) { case BT_PROPERTY_REMOTE_MODEL_NUM: { strncpy(value, (char*)prop->val, prop->len); value[prop->len] = '\0'; - btif_config_set_str(bdstr, BT_CONFIG_KEY_DIS_MODEL_NUM, value); + btif_config_set_str(bdstr, BTIF_STORAGE_KEY_DIS_MODEL_NUM, value); } break; default: LOG_ERROR("Unknown prop type:%d", prop->type); @@ -293,8 +256,8 @@ static bool cfg2prop(const RawAddress* remote_bd_addr, bt_property_t* prop) { } case BT_PROPERTY_REMOTE_FRIENDLY_NAME: { int len = prop->len; - ret = btif_config_get_str(bdstr, BTIF_STORAGE_KEY_ALIASE, - (char*)prop->val, &len); + ret = btif_config_get_str(bdstr, BTIF_STORAGE_KEY_ALIAS, (char*)prop->val, + &len); if (ret && len && len <= prop->len) prop->len = len - 1; else { @@ -334,7 +297,7 @@ static bool cfg2prop(const RawAddress* remote_bd_addr, bt_property_t* prop) { case BT_PROPERTY_UUIDS: { char value[1280]; int size = sizeof(value); - if (btif_config_get_str(bdstr, BTIF_STORAGE_PATH_REMOTE_SERVICE, value, + if (btif_config_get_str(bdstr, BTIF_STORAGE_KEY_REMOTE_SERVICE, value, &size)) { Uuid* p_uuid = reinterpret_cast<Uuid*>(prop->val); size_t num_uuids = @@ -351,15 +314,15 @@ static bool cfg2prop(const RawAddress* remote_bd_addr, bt_property_t* prop) { bt_remote_version_t* info = (bt_remote_version_t*)prop->val; if (prop->len >= (int)sizeof(bt_remote_version_t)) { - ret = btif_config_get_int(bdstr, BT_CONFIG_KEY_REMOTE_VER_MFCT, + ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_MFCT, &info->manufacturer); if (ret) - ret = btif_config_get_int(bdstr, BT_CONFIG_KEY_REMOTE_VER_VER, + ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_VER, &info->version); if (ret) - ret = btif_config_get_int(bdstr, BT_CONFIG_KEY_REMOTE_VER_SUBVER, + ret = btif_config_get_int(bdstr, BTIF_STORAGE_KEY_REMOTE_VER_SUBVER, &info->sub_ver); } } break; @@ -399,7 +362,7 @@ static bool cfg2prop(const RawAddress* remote_bd_addr, bt_property_t* prop) { case BT_PROPERTY_REMOTE_MODEL_NUM: { int len = prop->len; - ret = btif_config_get_str(bdstr, BT_CONFIG_KEY_DIS_MODEL_NUM, + ret = btif_config_get_str(bdstr, BTIF_STORAGE_KEY_DIS_MODEL_NUM, (char*)prop->val, &len); if (ret && len && len <= prop->len) prop->len = len - 1; diff --git a/system/btif/src/stack_manager.cc b/system/btif/src/stack_manager.cc index 368b67b36f..8fdc1e691a 100644 --- a/system/btif/src/stack_manager.cc +++ b/system/btif/src/stack_manager.cc @@ -33,7 +33,6 @@ #include "include/check.h" #include "main/shim/shim.h" #include "os/log.h" -#include "osi/include/osi.h" #include "stack/include/acl_api.h" #include "stack/include/btm_client_interface.h" #include "stack/include/main_thread.h" @@ -317,7 +316,6 @@ static void event_start_up_stack(bluetooth::core::CoreInterface* interface, BTA_dm_init(); bta_dm_enable(btif_dm_sec_evt, btif_dm_acl_evt); - bta_set_forward_hw_failures(true); btm_acl_device_down(); CHECK(module_start_up(get_local_module(GD_CONTROLLER_MODULE))); BTM_reset_complete(); @@ -366,7 +364,6 @@ static void event_shut_down_stack(ProfileStopCallback stopProfiles) { hack_future = local_hack_future; bta_sys_disable(); - bta_set_forward_hw_failures(false); BTA_dm_on_hw_off(); module_shut_down(get_local_module(BTIF_CONFIG_MODULE)); @@ -431,7 +428,7 @@ cleanup:; promise.set_value(); } -static void event_signal_stack_up(UNUSED_ATTR void* context) { +static void event_signal_stack_up(void* /* context */) { // Notify BTIF connect queue that we've brought up the stack. It's // now time to dispatch all the pending profile connect requests. btif_queue_connect_next(); @@ -439,7 +436,7 @@ static void event_signal_stack_up(UNUSED_ATTR void* context) { BT_STATE_ON); } -static void event_signal_stack_down(UNUSED_ATTR void* context) { +static void event_signal_stack_down(void* /* context */) { GetInterfaceToProfiles()->events->invoke_adapter_state_changed_cb( BT_STATE_OFF); future_ready(stack_manager_get_hack_future(), FUTURE_SUCCESS); diff --git a/system/btif/test/btif_config_cache_test.cc b/system/btif/test/btif_config_cache_test.cc index 903031d619..d1a44dcdf2 100644 --- a/system/btif/test/btif_config_cache_test.cc +++ b/system/btif/test/btif_config_cache_test.cc @@ -22,6 +22,7 @@ #include <filesystem> #include "stack/include/bt_octets.h" +#include "storage/config_keys.h" namespace { @@ -35,7 +36,7 @@ const std::string kBtAddr5 = "11:AA:22:BB:33:CD"; const std::string kBtLocalAddr = "12:34:56:78:90:AB"; const std::string kBtInfo = "Info"; const std::string kBtMetrics = "Metrics"; -const std::string kBtAdapter = "Adapter"; +const std::string kBtAdapter = BTIF_STORAGE_SECTION_ADAPTER; const std::string kBtAddrInvalid1 = "AB:CD:EF:12:34"; const std::string kBtAddrInvalid2 = "AB:CD:EF:12:34:56:78"; const std::string kBtAddrInvalid3 = "ABCDEF123456"; @@ -67,27 +68,32 @@ TEST(BtifConfigCacheTest, test_setup_btif_config_cache) { test_btif_config_cache.SetString(kBtMetrics, "Salt256Bit", "92a331174d20f2bb"); // Adapter Section - test_btif_config_cache.SetString(kBtAdapter, "Address", kBtLocalAddr); + test_btif_config_cache.SetString(kBtAdapter, BTIF_STORAGE_KEY_ADDRESS, + kBtLocalAddr); EXPECT_TRUE(test_btif_config_cache.HasSection(kBtAdapter)); // bt_device_1 - test_btif_config_cache.SetString(kBtAddr1, "Name", "Headset_1"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr1, "Name")); + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_NAME, + "Headset_1"); + EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr1, BTIF_STORAGE_KEY_NAME)); test_btif_config_cache.SetInt(kBtAddr1, "Property_Int", 1); EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr1, "Property_Int")); // bt_device_2 - test_btif_config_cache.SetString(kBtAddr2, "Name", "Headset_2"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr2, "Name")); + test_btif_config_cache.SetString(kBtAddr2, BTIF_STORAGE_KEY_NAME, + "Headset_2"); + EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr2, BTIF_STORAGE_KEY_NAME)); // bt_device_3 - test_btif_config_cache.SetString(kBtAddr3, "Name", "Headset_3"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr3, "Name")); + test_btif_config_cache.SetString(kBtAddr3, BTIF_STORAGE_KEY_NAME, + "Headset_3"); + EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr3, BTIF_STORAGE_KEY_NAME)); // bt_device_4 - test_btif_config_cache.SetString(kBtAddr4, "Name", "Headset_4"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr4, "Name")); + test_btif_config_cache.SetString(kBtAddr4, BTIF_STORAGE_KEY_NAME, + "Headset_4"); + EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr4, BTIF_STORAGE_KEY_NAME)); // out out the capacty of unpair devices cache, the bt_device_1 be ruled out EXPECT_FALSE(test_btif_config_cache.HasSection(kBtAddr1)); @@ -104,57 +110,72 @@ TEST(BtifConfigCacheTest, test_set_up_config_cache_with_invalid_section) { BtifConfigCache test_btif_config_cache(kCapacity); // kBtAddrInvalid1 - test_btif_config_cache.SetString(kBtAddrInvalid1, "Name", "Headset_1"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddrInvalid1, "Name")); + test_btif_config_cache.SetString(kBtAddrInvalid1, BTIF_STORAGE_KEY_NAME, + "Headset_1"); + EXPECT_TRUE( + test_btif_config_cache.HasKey(kBtAddrInvalid1, BTIF_STORAGE_KEY_NAME)); EXPECT_TRUE(test_btif_config_cache.HasUnpairedSection(kBtAddrInvalid1)); // get the LinkKey - test_btif_config_cache.SetString(kBtAddrInvalid1, "LinkKey", + test_btif_config_cache.SetString(kBtAddrInvalid1, BTIF_STORAGE_KEY_LINK_KEY, "1122334455667788"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddrInvalid1, "LinkKey")); + EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddrInvalid1, + BTIF_STORAGE_KEY_LINK_KEY)); EXPECT_TRUE(test_btif_config_cache.HasUnpairedSection(kBtAddrInvalid1)); EXPECT_FALSE(test_btif_config_cache.HasPersistentSection(kBtAddrInvalid1)); // kBtAddrInvalid2 - test_btif_config_cache.SetString(kBtAddrInvalid2, "Name", "Headset_1"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddrInvalid2, "Name")); + test_btif_config_cache.SetString(kBtAddrInvalid2, BTIF_STORAGE_KEY_NAME, + "Headset_1"); + EXPECT_TRUE( + test_btif_config_cache.HasKey(kBtAddrInvalid2, BTIF_STORAGE_KEY_NAME)); EXPECT_TRUE(test_btif_config_cache.HasUnpairedSection(kBtAddrInvalid2)); // get the LinkKey - test_btif_config_cache.SetString(kBtAddrInvalid2, "LinkKey", + test_btif_config_cache.SetString(kBtAddrInvalid2, BTIF_STORAGE_KEY_LINK_KEY, "1122334455667788"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddrInvalid2, "LinkKey")); + EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddrInvalid2, + BTIF_STORAGE_KEY_LINK_KEY)); EXPECT_TRUE(test_btif_config_cache.HasUnpairedSection(kBtAddrInvalid2)); EXPECT_FALSE(test_btif_config_cache.HasPersistentSection(kBtAddrInvalid2)); // kBtAddrInvalid3 - test_btif_config_cache.SetString(kBtAddrInvalid3, "Name", "Headset_1"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddrInvalid3, "Name")); + test_btif_config_cache.SetString(kBtAddrInvalid3, BTIF_STORAGE_KEY_NAME, + "Headset_1"); + EXPECT_TRUE( + test_btif_config_cache.HasKey(kBtAddrInvalid3, BTIF_STORAGE_KEY_NAME)); EXPECT_TRUE(test_btif_config_cache.HasUnpairedSection(kBtAddrInvalid3)); // get the LinkKey - test_btif_config_cache.SetString(kBtAddrInvalid3, "LinkKey", + test_btif_config_cache.SetString(kBtAddrInvalid3, BTIF_STORAGE_KEY_LINK_KEY, "1122334455667788"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddrInvalid3, "LinkKey")); + EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddrInvalid3, + BTIF_STORAGE_KEY_LINK_KEY)); EXPECT_TRUE(test_btif_config_cache.HasUnpairedSection(kBtAddrInvalid3)); EXPECT_FALSE(test_btif_config_cache.HasPersistentSection(kBtAddrInvalid3)); // kBtAddrInvalid4 - test_btif_config_cache.SetString(kBtAddrInvalid4, "Name", "Headset_1"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddrInvalid4, "Name")); + test_btif_config_cache.SetString(kBtAddrInvalid4, BTIF_STORAGE_KEY_NAME, + "Headset_1"); + EXPECT_TRUE( + test_btif_config_cache.HasKey(kBtAddrInvalid4, BTIF_STORAGE_KEY_NAME)); EXPECT_TRUE(test_btif_config_cache.HasUnpairedSection(kBtAddrInvalid4)); // get the LinkKey - test_btif_config_cache.SetString(kBtAddrInvalid4, "LinkKey", + test_btif_config_cache.SetString(kBtAddrInvalid4, BTIF_STORAGE_KEY_LINK_KEY, "1122334455667788"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddrInvalid4, "LinkKey")); + EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddrInvalid4, + BTIF_STORAGE_KEY_LINK_KEY)); EXPECT_TRUE(test_btif_config_cache.HasUnpairedSection(kBtAddrInvalid4)); EXPECT_FALSE(test_btif_config_cache.HasPersistentSection(kBtAddrInvalid4)); // kBtSectionInvalid1 - test_btif_config_cache.SetString(kBtSectionInvalid1, "Name", "Headset_1"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtSectionInvalid1, "Name")); + test_btif_config_cache.SetString(kBtSectionInvalid1, BTIF_STORAGE_KEY_NAME, + "Headset_1"); + EXPECT_TRUE( + test_btif_config_cache.HasKey(kBtSectionInvalid1, BTIF_STORAGE_KEY_NAME)); EXPECT_TRUE(test_btif_config_cache.HasUnpairedSection(kBtSectionInvalid1)); // get the LinkKey - test_btif_config_cache.SetString(kBtSectionInvalid1, "LinkKey", - "1122334455667788"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtSectionInvalid1, "LinkKey")); + test_btif_config_cache.SetString( + kBtSectionInvalid1, BTIF_STORAGE_KEY_LINK_KEY, "1122334455667788"); + EXPECT_TRUE(test_btif_config_cache.HasKey(kBtSectionInvalid1, + BTIF_STORAGE_KEY_LINK_KEY)); EXPECT_TRUE(test_btif_config_cache.HasUnpairedSection(kBtSectionInvalid1)); EXPECT_FALSE(test_btif_config_cache.HasPersistentSection(kBtSectionInvalid1)); } @@ -170,9 +191,10 @@ TEST(BtifConfigCacheTest, test_set_up_config_cache_with_invalid_section) { TEST(BtifConfigCacheTest, test_get_set_key_value_test) { BtifConfigCache test_btif_config_cache(kCapacity); // test in unpaired cache - test_btif_config_cache.SetString(kBtAddr1, "Name", "Headset_1"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr1, "Name")); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, "Name"), + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_NAME, + "Headset_1"); + EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr1, BTIF_STORAGE_KEY_NAME)); + EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, BTIF_STORAGE_KEY_NAME), Optional(StrEq("Headset_1"))); test_btif_config_cache.SetInt(kBtAddr1, "Property_Int", 65536); @@ -191,21 +213,24 @@ TEST(BtifConfigCacheTest, test_get_set_key_value_test) { Optional(IsTrue())); // empty value - test_btif_config_cache.SetString(kBtAddr1, "Name", ""); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr1, "Name")); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, "Name"), + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_NAME, ""); + EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr1, BTIF_STORAGE_KEY_NAME)); + EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, BTIF_STORAGE_KEY_NAME), Optional(StrEq(""))); // get the LinkKey - test_btif_config_cache.SetString(kBtAddr1, "LinkKey", "1122334455667788"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr1, "LinkKey")); + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_LINK_KEY, + "1122334455667788"); + EXPECT_TRUE( + test_btif_config_cache.HasKey(kBtAddr1, BTIF_STORAGE_KEY_LINK_KEY)); EXPECT_FALSE(test_btif_config_cache.HasUnpairedSection(kBtAddr1)); EXPECT_TRUE(test_btif_config_cache.HasPersistentSection(kBtAddr1)); // test in unpaired cache - test_btif_config_cache.SetString(kBtAddr1, "Name", "Headset_1"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr1, "Name")); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, "Name"), + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_NAME, + "Headset_1"); + EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr1, BTIF_STORAGE_KEY_NAME)); + EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, BTIF_STORAGE_KEY_NAME), Optional(StrEq("Headset_1"))); test_btif_config_cache.SetInt(kBtAddr1, "Property_Int", 65536); @@ -224,40 +249,47 @@ TEST(BtifConfigCacheTest, test_get_set_key_value_test) { Optional(IsTrue())); // empty section is disallowed - EXPECT_DEATH({ test_btif_config_cache.SetString("", "name", "Headset_1"); }, - "Empty section not allowed"); + EXPECT_DEATH( + { + test_btif_config_cache.SetString("", BTIF_STORAGE_KEY_NAME, + "Headset_1"); + }, + "Empty section not allowed"); // empty key is disallowed EXPECT_DEATH({ test_btif_config_cache.SetString(kBtAddr1, "", "Headset_1"); }, "Empty key not allowed"); EXPECT_FALSE(test_btif_config_cache.HasKey(kBtAddr1, "")); // empty value is allowed - test_btif_config_cache.SetString(kBtAddr1, "Name", ""); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr1, "Name")); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, "Name"), + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_NAME, ""); + EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr1, BTIF_STORAGE_KEY_NAME)); + EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, BTIF_STORAGE_KEY_NAME), Optional(StrEq(""))); } /* Test to set values in the same key * Receiving the same key with different values in a section, the new incoming * value will be updated but the key will not be added repeatedly. test this - * feature in both unpaired devic cache and paired device list cache + * feature in both unpaired device cache and paired device list cache */ TEST(BtifConfigCacheTest, test_set_values_in_the_same_key) { BtifConfigCache test_btif_config_cache(kCapacity); - // add new a key "Name" - test_btif_config_cache.SetString(kBtAddr1, "Name", "Headset_1"); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, "Name"), + // add new a key BTIF_STORAGE_KEY_NAME + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_NAME, + "Headset_1"); + EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, BTIF_STORAGE_KEY_NAME), Optional(StrEq("Headset_1"))); EXPECT_TRUE(test_btif_config_cache.HasUnpairedSection(kBtAddr1)); - // add the same key "Name" with different value - test_btif_config_cache.SetString(kBtAddr1, "Name", "Headset_1A"); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, "Name"), + // add the same key BTIF_STORAGE_KEY_NAME with different value + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_NAME, + "Headset_1A"); + EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, BTIF_STORAGE_KEY_NAME), Optional(StrEq("Headset_1A"))); - // add the same key "Name" with different value - test_btif_config_cache.SetString(kBtAddr1, "Name", "Headset_2A"); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, "Name"), + // add the same key BTIF_STORAGE_KEY_NAME with different value + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_NAME, + "Headset_2A"); + EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, BTIF_STORAGE_KEY_NAME), Optional(StrEq("Headset_2A"))); EXPECT_TRUE(test_btif_config_cache.HasUnpairedSection(kBtAddr1)); @@ -276,19 +308,23 @@ TEST(BtifConfigCacheTest, test_set_values_in_the_same_key) { Optional(Eq(uint64_t(4294967296)))); // get the LinkKey and set values in the same key in paired device list - test_btif_config_cache.SetString(kBtAddr1, "LinkKey", "1122334455667788"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr1, "LinkKey")); + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_LINK_KEY, + "1122334455667788"); + EXPECT_TRUE( + test_btif_config_cache.HasKey(kBtAddr1, BTIF_STORAGE_KEY_LINK_KEY)); EXPECT_FALSE(test_btif_config_cache.HasUnpairedSection(kBtAddr1)); EXPECT_TRUE(test_btif_config_cache.HasPersistentSection(kBtAddr1)); - // add the same key "Name" with the different value - test_btif_config_cache.SetString(kBtAddr1, "Name", "Headset_1A"); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, "Name"), + // add the same key BTIF_STORAGE_KEY_NAME with the different value + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_NAME, + "Headset_1A"); + EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, BTIF_STORAGE_KEY_NAME), Optional(StrEq("Headset_1A"))); - // add the same key "Name" with the value different - test_btif_config_cache.SetString(kBtAddr1, "Name", "Headset_2A"); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, "Name"), + // add the same key BTIF_STORAGE_KEY_NAME with the value different + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_NAME, + "Headset_2A"); + EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, BTIF_STORAGE_KEY_NAME), Optional(StrEq("Headset_2A"))); test_btif_config_cache.SetInt(kBtAddr1, "Property_Int", 64); @@ -305,30 +341,34 @@ TEST(BtifConfigCacheTest, test_set_values_in_the_same_key) { /* Stress test to pair with device then unpair device * 1. paired with device by adding a "LinKey" to device and check the device be * moved into paired devices list - * 2. unpaired with the device by removing the "LinkKey" and check the device be - * moved back to unpaired devices cache + * 2. unpaired with the device by removing the BTIF_STORAGE_KEY_LINK_KEY and + * check the device be moved back to unpaired devices cache * 3. loop for 30 times */ TEST(BtifConfigCacheTest, test_pair_unpair_device_stress_test) { BtifConfigCache test_btif_config_cache(kCapacity); // pair with Headset_1 11:22:33:44:55:66 - test_btif_config_cache.SetString(kBtAddr1, "Name", "Headset_1"); + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_NAME, + "Headset_1"); EXPECT_TRUE(test_btif_config_cache.HasUnpairedSection(kBtAddr1)); EXPECT_FALSE(test_btif_config_cache.HasPersistentSection(kBtAddr1)); for (int i = 0; i < kTestRepeatCount; ++i) { // get the LinkKey, the device will be moved from the unpaired cache to // paired cache - test_btif_config_cache.SetString(kBtAddr1, "LinkKey", "1122334455667788"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr1, "LinkKey")); + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_LINK_KEY, + "1122334455667788"); + EXPECT_TRUE( + test_btif_config_cache.HasKey(kBtAddr1, BTIF_STORAGE_KEY_LINK_KEY)); EXPECT_FALSE(test_btif_config_cache.HasUnpairedSection(kBtAddr1)); EXPECT_TRUE(test_btif_config_cache.HasPersistentSection(kBtAddr1)); // remove the LinkKey, the device will be moved from the paired cache to // unpaired cache - test_btif_config_cache.RemoveKey(kBtAddr1, "LinkKey"); - EXPECT_FALSE(test_btif_config_cache.HasKey(kBtAddr1, "LinkKey")); + test_btif_config_cache.RemoveKey(kBtAddr1, BTIF_STORAGE_KEY_LINK_KEY); + EXPECT_FALSE( + test_btif_config_cache.HasKey(kBtAddr1, BTIF_STORAGE_KEY_LINK_KEY)); EXPECT_TRUE(test_btif_config_cache.HasUnpairedSection(kBtAddr1)); EXPECT_FALSE(test_btif_config_cache.HasPersistentSection(kBtAddr1)); } @@ -338,92 +378,111 @@ TEST(BtifConfigCacheTest, test_pair_unpair_device_stress_test) { * 1. Pired with 4 devices with Link-Key type key in order, to check these 4 * devices are in the paired devices list cache * 2. unpair with these 4 devices by removed Link-Key type key in order, to - * check the fisrt device was ruled-out from unpaired devices cache due to + * check the first device was ruled-out from unpaired devices cache due to * capacity limitation, and other 3 devices are be moved to unpaired device * cache. */ TEST(BtifConfigCacheTest, test_multi_pair_unpair_with_devices) { BtifConfigCache test_btif_config_cache(kCapacity); // pair with 4 bt address devices by add different type linkkey. - test_btif_config_cache.SetString(kBtAddr1, "name", "kBtAddr1"); - test_btif_config_cache.SetString(kBtAddr1, "LinkKey", "1122334455667788"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr1, "LinkKey")); - - test_btif_config_cache.SetString(kBtAddr2, "name", "kBtAddr2"); - test_btif_config_cache.SetString(kBtAddr2, "LE_KEY_PENC", "aabbccddeeff9900"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr2, "LE_KEY_PENC")); - - test_btif_config_cache.SetString(kBtAddr3, "name", "kBtAddr3"); - test_btif_config_cache.SetString(kBtAddr3, "LE_KEY_PID", "a1b2c3d4e5feeeee"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr3, "LE_KEY_PID")); - - test_btif_config_cache.SetString(kBtAddr4, "LE_KEY_PCSRK", + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_NAME, "kBtAddr1"); + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_LINK_KEY, + "1122334455667788"); + EXPECT_TRUE( + test_btif_config_cache.HasKey(kBtAddr1, BTIF_STORAGE_KEY_LINK_KEY)); + + test_btif_config_cache.SetString(kBtAddr2, BTIF_STORAGE_KEY_NAME, "kBtAddr2"); + test_btif_config_cache.SetString(kBtAddr2, BTIF_STORAGE_KEY_LE_KEY_PENC, + "aabbccddeeff9900"); + EXPECT_TRUE( + test_btif_config_cache.HasKey(kBtAddr2, BTIF_STORAGE_KEY_LE_KEY_PENC)); + + test_btif_config_cache.SetString(kBtAddr3, BTIF_STORAGE_KEY_NAME, "kBtAddr3"); + test_btif_config_cache.SetString(kBtAddr3, BTIF_STORAGE_KEY_LE_KEY_PID, + "a1b2c3d4e5feeeee"); + EXPECT_TRUE( + test_btif_config_cache.HasKey(kBtAddr3, BTIF_STORAGE_KEY_LE_KEY_PID)); + + test_btif_config_cache.SetString(kBtAddr4, BTIF_STORAGE_KEY_LE_KEY_PCSRK, "aaaabbbbccccdddd"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr4, "LE_KEY_PCSRK")); + EXPECT_TRUE( + test_btif_config_cache.HasKey(kBtAddr4, BTIF_STORAGE_KEY_LE_KEY_PCSRK)); - test_btif_config_cache.SetString(kBtAddr5, "name", "kBtAddr5"); - test_btif_config_cache.SetString(kBtAddr5, "LE_KEY_LENC", "jilkjlkjlkn"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr5, "LE_KEY_LENC")); + test_btif_config_cache.SetString(kBtAddr5, BTIF_STORAGE_KEY_NAME, "kBtAddr5"); + test_btif_config_cache.SetString(kBtAddr5, BTIF_STORAGE_KEY_LE_KEY_LENC, + "jilkjlkjlkn"); + EXPECT_TRUE( + test_btif_config_cache.HasKey(kBtAddr5, BTIF_STORAGE_KEY_LE_KEY_LENC)); // checking these 4 devices are in paired list cache and the content are // correct. EXPECT_TRUE(test_btif_config_cache.HasPersistentSection(kBtAddr1)); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, "LinkKey"), - Optional(StrEq("1122334455667788"))); + EXPECT_THAT( + test_btif_config_cache.GetString(kBtAddr1, BTIF_STORAGE_KEY_LINK_KEY), + Optional(StrEq("1122334455667788"))); EXPECT_TRUE(test_btif_config_cache.HasPersistentSection(kBtAddr2)); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr2, "LE_KEY_PENC"), - Optional(StrEq("aabbccddeeff9900"))); + EXPECT_THAT( + test_btif_config_cache.GetString(kBtAddr2, BTIF_STORAGE_KEY_LE_KEY_PENC), + Optional(StrEq("aabbccddeeff9900"))); EXPECT_TRUE(test_btif_config_cache.HasPersistentSection(kBtAddr3)); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr3, "LE_KEY_PID"), - Optional(StrEq("a1b2c3d4e5feeeee"))); + EXPECT_THAT( + test_btif_config_cache.GetString(kBtAddr3, BTIF_STORAGE_KEY_LE_KEY_PID), + Optional(StrEq("a1b2c3d4e5feeeee"))); EXPECT_TRUE(test_btif_config_cache.HasPersistentSection(kBtAddr4)); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr4, "LE_KEY_PCSRK"), - Optional(StrEq("aaaabbbbccccdddd"))); + EXPECT_THAT( + test_btif_config_cache.GetString(kBtAddr4, BTIF_STORAGE_KEY_LE_KEY_PCSRK), + Optional(StrEq("aaaabbbbccccdddd"))); EXPECT_TRUE(test_btif_config_cache.HasPersistentSection(kBtAddr5)); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr5, "LE_KEY_LENC"), - Optional(StrEq("jilkjlkjlkn"))); + EXPECT_THAT( + test_btif_config_cache.GetString(kBtAddr5, BTIF_STORAGE_KEY_LE_KEY_LENC), + Optional(StrEq("jilkjlkjlkn"))); // unpair with these 4 bt address devices by removed the linkkey. // unpair kBtAddr1 11:22:33:44:55:66 - test_btif_config_cache.RemoveKey(kBtAddr1, "LinkKey"); - EXPECT_FALSE(test_btif_config_cache.HasKey(kBtAddr1, "LinkKey")); + test_btif_config_cache.RemoveKey(kBtAddr1, BTIF_STORAGE_KEY_LINK_KEY); + EXPECT_FALSE( + test_btif_config_cache.HasKey(kBtAddr1, BTIF_STORAGE_KEY_LINK_KEY)); // no empty section is moved to unpaired EXPECT_FALSE(test_btif_config_cache.HasPersistentSection(kBtAddr1)); EXPECT_TRUE(test_btif_config_cache.HasUnpairedSection(kBtAddr1)); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, "name"), + EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, BTIF_STORAGE_KEY_NAME), Optional(StrEq("kBtAddr1"))); // unpair with kBtAddr2 aa:bb:cc:dd:ee:ff - test_btif_config_cache.RemoveKey(kBtAddr2, "LE_KEY_PENC"); - EXPECT_FALSE(test_btif_config_cache.HasKey(kBtAddr2, "LE_KEY_PENC")); + test_btif_config_cache.RemoveKey(kBtAddr2, BTIF_STORAGE_KEY_LE_KEY_PENC); + EXPECT_FALSE( + test_btif_config_cache.HasKey(kBtAddr2, BTIF_STORAGE_KEY_LE_KEY_PENC)); EXPECT_FALSE(test_btif_config_cache.HasPersistentSection(kBtAddr2)); EXPECT_TRUE(test_btif_config_cache.HasUnpairedSection(kBtAddr2)); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr2, "name"), + EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr2, BTIF_STORAGE_KEY_NAME), Optional(StrEq("kBtAddr2"))); // unpair with kBtAddr3 AB:CD:EF:12:34:56 - test_btif_config_cache.RemoveKey(kBtAddr3, "LE_KEY_PID"); - EXPECT_FALSE(test_btif_config_cache.HasKey(kBtAddr3, "LE_KEY_PID")); + test_btif_config_cache.RemoveKey(kBtAddr3, BTIF_STORAGE_KEY_LE_KEY_PID); + EXPECT_FALSE( + test_btif_config_cache.HasKey(kBtAddr3, BTIF_STORAGE_KEY_LE_KEY_PID)); EXPECT_FALSE(test_btif_config_cache.HasPersistentSection(kBtAddr3)); // no empty section is moved to unpaired EXPECT_TRUE(test_btif_config_cache.HasUnpairedSection(kBtAddr3)); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr3, "name"), + EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr3, BTIF_STORAGE_KEY_NAME), Optional(StrEq("kBtAddr3"))); // unpair with kBtAddr4 11:AA:22:BB:33:CC - test_btif_config_cache.RemoveKey(kBtAddr4, "LE_KEY_PCSRK"); - EXPECT_FALSE(test_btif_config_cache.HasKey(kBtAddr4, "LE_KEY_PCSRK")); + test_btif_config_cache.RemoveKey(kBtAddr4, BTIF_STORAGE_KEY_LE_KEY_PCSRK); + EXPECT_FALSE( + test_btif_config_cache.HasKey(kBtAddr4, BTIF_STORAGE_KEY_LE_KEY_PCSRK)); EXPECT_FALSE(test_btif_config_cache.HasPersistentSection(kBtAddr4)); // empty section is removed EXPECT_FALSE(test_btif_config_cache.HasUnpairedSection(kBtAddr4)); // unpair with kBtAddr5 11:AA:22:BB:33:CD - test_btif_config_cache.RemoveKey(kBtAddr5, "LE_KEY_LENC"); - EXPECT_FALSE(test_btif_config_cache.HasKey(kBtAddr5, "LE_KEY_LENC")); + test_btif_config_cache.RemoveKey(kBtAddr5, BTIF_STORAGE_KEY_LE_KEY_LENC); + EXPECT_FALSE( + test_btif_config_cache.HasKey(kBtAddr5, BTIF_STORAGE_KEY_LE_KEY_LENC)); EXPECT_FALSE(test_btif_config_cache.HasPersistentSection(kBtAddr5)); // no empty section is moved to unpaired EXPECT_TRUE(test_btif_config_cache.HasUnpairedSection(kBtAddr5)); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr5, "name"), + EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr5, BTIF_STORAGE_KEY_NAME), Optional(StrEq("kBtAddr5"))); // checking the oldest unpaired device kBtAddr1 was ruled out from cache due @@ -432,26 +491,33 @@ TEST(BtifConfigCacheTest, test_multi_pair_unpair_with_devices) { } /* Test to remove sections with the specific key - * paired with sections with the specific "Restricted" key and then removed the - * "Restricted" key, check if the sections with the specific "Restricted" key - * are removed. + * paired with sections with the specific BTIF_STORAGE_KEY_RESTRICTED key and + * then removed the BTIF_STORAGE_KEY_RESTRICTED key, check if the sections with + * the specific BTIF_STORAGE_KEY_RESTRICTED key are removed. */ TEST(BtifConfigCacheTest, test_remove_sections_with_key) { BtifConfigCache test_btif_config_cache(kCapacity); // pair with Headset_1 (kBtAddr1), Headset_2 (kBtAddr1), Heasdet_3 (kBtAddr3) - // , and Headset_1 (kBtAddr1), Headset_3 (kBtAddr3) have sepcific "Restricted" - // key - test_btif_config_cache.SetString(kBtAddr1, "Name", "Headset_1"); - test_btif_config_cache.SetString(kBtAddr1, "Restricted", "1"); - test_btif_config_cache.SetString(kBtAddr1, "LinkKey", "1122334455667788"); - test_btif_config_cache.SetString(kBtAddr2, "Name", "Headset_2"); - test_btif_config_cache.SetString(kBtAddr2, "LinkKey", "aabbccddeeff9900"); - test_btif_config_cache.SetString(kBtAddr3, "Name", "Headset_3"); - test_btif_config_cache.SetString(kBtAddr3, "LinkKey", "a1b2c3d4e5feeeee"); - test_btif_config_cache.SetString(kBtAddr3, "Restricted", "1"); - - // remove sections with "Restricted" key - test_btif_config_cache.RemovePersistentSectionsWithKey("Restricted"); + // , and Headset_1 (kBtAddr1), Headset_3 (kBtAddr3) have specific + // BTIF_STORAGE_KEY_RESTRICTED key + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_NAME, + "Headset_1"); + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_RESTRICTED, "1"); + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_LINK_KEY, + "1122334455667788"); + test_btif_config_cache.SetString(kBtAddr2, BTIF_STORAGE_KEY_NAME, + "Headset_2"); + test_btif_config_cache.SetString(kBtAddr2, BTIF_STORAGE_KEY_LINK_KEY, + "aabbccddeeff9900"); + test_btif_config_cache.SetString(kBtAddr3, BTIF_STORAGE_KEY_NAME, + "Headset_3"); + test_btif_config_cache.SetString(kBtAddr3, BTIF_STORAGE_KEY_LINK_KEY, + "a1b2c3d4e5feeeee"); + test_btif_config_cache.SetString(kBtAddr3, BTIF_STORAGE_KEY_RESTRICTED, "1"); + + // remove sections with BTIF_STORAGE_KEY_RESTRICTED key + test_btif_config_cache.RemovePersistentSectionsWithKey( + BTIF_STORAGE_KEY_RESTRICTED); // checking the kBtAddr1 and kBtAddr3 can not be found in config cache, only // keep kBtAddr2 in config cache. @@ -465,23 +531,32 @@ TEST(BtifConfigCacheTest, test_PersistentSectionCopy_Init) { BtifConfigCache test_btif_config_cache(kCapacity); config_t config_paired = {}; // pair with 3 bt devices, kBtAddr1, kBtAddr2, kBtAddr3 - test_btif_config_cache.SetString(kBtAddr1, "LinkKey", "1122334455667788"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr1, "LinkKey")); + test_btif_config_cache.SetString(kBtAddr1, BTIF_STORAGE_KEY_LINK_KEY, + "1122334455667788"); + EXPECT_TRUE( + test_btif_config_cache.HasKey(kBtAddr1, BTIF_STORAGE_KEY_LINK_KEY)); EXPECT_TRUE(test_btif_config_cache.HasPersistentSection(kBtAddr1)); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr1, "LinkKey"), - Optional(StrEq("1122334455667788"))); - - test_btif_config_cache.SetString(kBtAddr2, "LE_KEY_PENC", "aabbccddeeff9900"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr2, "LE_KEY_PENC")); + EXPECT_THAT( + test_btif_config_cache.GetString(kBtAddr1, BTIF_STORAGE_KEY_LINK_KEY), + Optional(StrEq("1122334455667788"))); + + test_btif_config_cache.SetString(kBtAddr2, BTIF_STORAGE_KEY_LE_KEY_PENC, + "aabbccddeeff9900"); + EXPECT_TRUE( + test_btif_config_cache.HasKey(kBtAddr2, BTIF_STORAGE_KEY_LE_KEY_PENC)); EXPECT_TRUE(test_btif_config_cache.HasPersistentSection(kBtAddr2)); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr2, "LE_KEY_PENC"), - Optional(StrEq("aabbccddeeff9900"))); - - test_btif_config_cache.SetString(kBtAddr3, "LE_KEY_PID", "a1b2c3d4e5feeeee"); - EXPECT_TRUE(test_btif_config_cache.HasKey(kBtAddr3, "LE_KEY_PID")); + EXPECT_THAT( + test_btif_config_cache.GetString(kBtAddr2, BTIF_STORAGE_KEY_LE_KEY_PENC), + Optional(StrEq("aabbccddeeff9900"))); + + test_btif_config_cache.SetString(kBtAddr3, BTIF_STORAGE_KEY_LE_KEY_PID, + "a1b2c3d4e5feeeee"); + EXPECT_TRUE( + test_btif_config_cache.HasKey(kBtAddr3, BTIF_STORAGE_KEY_LE_KEY_PID)); EXPECT_TRUE(test_btif_config_cache.HasPersistentSection(kBtAddr3)); - EXPECT_THAT(test_btif_config_cache.GetString(kBtAddr3, "LE_KEY_PID"), - Optional(StrEq("a1b2c3d4e5feeeee"))); + EXPECT_THAT( + test_btif_config_cache.GetString(kBtAddr3, BTIF_STORAGE_KEY_LE_KEY_PID), + Optional(StrEq("a1b2c3d4e5feeeee"))); // check GetPersistentSections int num_of_paired_devices = 0; diff --git a/system/btif/test/btif_dm_test.cc b/system/btif/test/btif_dm_test.cc index 852c0aaa48..d1d6b0758a 100644 --- a/system/btif/test/btif_dm_test.cc +++ b/system/btif/test/btif_dm_test.cc @@ -24,8 +24,8 @@ #include "bta/include/bta_api_data_types.h" #include "btif/include/mock_core_callbacks.h" -#include "gd/module.h" #include "main/shim/stack.h" +#include "module.h" #include "stack/include/btm_ble_api_types.h" #include "storage/storage_module.h" diff --git a/system/build/dpkg/floss/build-dpkg b/system/build/dpkg/floss/build-dpkg index e9cb70b9fe..fececbc689 100755 --- a/system/build/dpkg/floss/build-dpkg +++ b/system/build/dpkg/floss/build-dpkg @@ -48,7 +48,7 @@ export PATH="${PATH}:${BIN_DIR}" # Check dependencies # libchrome requires modp_b64 -APT_REQUIRED="modp-b64 libchrome flatbuffers-compiler flex g++-multilib gcc-multilib generate-ninja gnupg gperf libc++-dev libdbus-1-dev libevent-dev libevent-dev libflatbuffers-dev libflatbuffers1 libgl1-mesa-dev libglib2.0-dev liblz4-tool libncurses5 libnss3-dev libprotobuf-dev libre2-9 libssl-dev libtinyxml2-dev libx11-dev libxml2-utils ninja-build openssl protobuf-compiler unzip x11proto-core-dev xsltproc zip zlib1g-dev" +APT_REQUIRED="modp-b64 libchrome flatbuffers-compiler flex g++-multilib gcc-multilib generate-ninja gnupg gperf libc++-dev libdbus-1-dev libevent-dev libevent-dev libflatbuffers-dev libflatbuffers1 libfmt-dev libgl1-mesa-dev libglib2.0-dev liblz4-tool libncurses5 libnss3-dev libprotobuf-dev libre2-9 libssl-dev libtinyxml2-dev libx11-dev libxml2-utils ninja-build openssl protobuf-compiler unzip x11proto-core-dev xsltproc zip zlib1g-dev" # SPEED UP TEST, REMOVE ME APT_REQUIRED="modp-b64 libchrome flatbuffers-compiler" diff --git a/system/build/dpkg/floss/install-dependencies b/system/build/dpkg/floss/install-dependencies index a1b33a74a6..e215399f6f 100755 --- a/system/build/dpkg/floss/install-dependencies +++ b/system/build/dpkg/floss/install-dependencies @@ -24,7 +24,7 @@ function ctrl_c() { # APT dependencies APT_REQUIRED="git curl wget flatbuffers-compiler flex g++-multilib gcc-multilib generate-ninja \ -gnupg gperf libc++-dev libdbus-1-dev libevent-dev libflatbuffers-dev libflatbuffers1 \ +gnupg gperf libc++-dev libdbus-1-dev libevent-dev libflatbuffers-dev libfmt-dev libflatbuffers1 \ libgl1-mesa-dev libglib2.0-dev liblz4-tool libncurses5 libnss3-dev libprotobuf-dev libre2-9 \ libssl-dev libtinyxml2-dev libx11-dev libxml2-utils ninja-build openssl protobuf-compiler unzip \ x11proto-core-dev xsltproc zip zlib1g-dev libc++abi-dev cmake debmake ninja-build libgtest-dev \ diff --git a/system/build/dpkg/floss/package/DEBIAN/control b/system/build/dpkg/floss/package/DEBIAN/control index 3bb5d35eb9..d5f4520c6c 100644 --- a/system/build/dpkg/floss/package/DEBIAN/control +++ b/system/build/dpkg/floss/package/DEBIAN/control @@ -4,7 +4,7 @@ Priority: optional Maintainer: Martin Brabham <optedoblivion@google.com> Version: 0.1 Homepage: https://www.google.com -Depends: debmake, ninja-build, flatbuffers-compiler, flex, g++-multilib, gcc-multilib, generate-ninja, gnupg, gperf, libc++-dev, libdbus-1-dev, libevent-dev, libevent-dev, libflatbuffers-dev, libflatbuffers1, libgl1-mesa-dev, libglib2.0-dev, liblz4-tool, libncurses5, libnss3-dev, libprotobuf-dev, libre2-9, libssl-dev, libtinyxml2-dev, libx11-dev, libxml2-utils, ninja-build, openssl, protobuf-compiler, unzip, x11proto-core-dev, xsltproc, zip, zlib1g-dev, modp-b64, libchrome +Depends: debmake, ninja-build, flatbuffers-compiler, flex, g++-multilib, gcc-multilib, generate-ninja, gnupg, gperf, libc++-dev, libdbus-1-dev, libevent-dev, libevent-dev, libflatbuffers-dev, libflatbuffers1, libfmt-dev, libfmt9, libgl1-mesa-dev, libglib2.0-dev, liblz4-tool, libncurses5, libnss3-dev, libprotobuf-dev, libre2-9, libssl-dev, libtinyxml2-dev, libx11-dev, libxml2-utils, ninja-build, openssl, protobuf-compiler, unzip, x11proto-core-dev, xsltproc, zip, zlib1g-dev, modp-b64, libchrome Architecture: all Essential: no Installed-Size: 490MB diff --git a/system/common/Android.bp b/system/common/Android.bp index c74926a516..379ec9802a 100644 --- a/system/common/Android.bp +++ b/system/common/Android.bp @@ -55,6 +55,7 @@ cc_library_static { header_libs: ["libbluetooth_headers"], static_libs: [ "libbluetooth_crypto_toolbox", + "libbluetooth_log", "libbt-platform-protos-lite", "libbt_shim_bridge", ], @@ -102,6 +103,7 @@ cc_test { static_libs: [ "libbluetooth-types", "libbluetooth_crypto_toolbox", + "libbluetooth_log", "libbt-common", "libbt-platform-protos-lite", "libbt_shim_bridge", diff --git a/system/device/Android.bp b/system/device/Android.bp index 5e090e6c36..4233340e2d 100644 --- a/system/device/Android.bp +++ b/system/device/Android.bp @@ -38,6 +38,7 @@ cc_library_static { static_libs: [ "bluetooth_flags_c_lib", "libbluetooth_hci_pdl", + "libbluetooth_log", "libbt_shim_bridge", "libflatbuffers-cpp", "server_configurable_flags", @@ -63,6 +64,7 @@ cc_test { static_libs: [ "libbluetooth-types", "libbluetooth_gd", + "libbluetooth_log", "libbt_shim_bridge", "libbt_shim_ffi", "libbtcore", @@ -98,6 +100,7 @@ cc_test { ], static_libs: [ "libbluetooth-types", + "libbluetooth_log", "libbt-platform-protos-lite", "libbt_shim_bridge", "libbt_shim_ffi", diff --git a/system/device/fuzzer/Android.bp b/system/device/fuzzer/Android.bp index 35cf3d092d..8e88d1eee8 100644 --- a/system/device/fuzzer/Android.bp +++ b/system/device/fuzzer/Android.bp @@ -46,6 +46,7 @@ cc_fuzz { "libbluetooth-types", "libbluetooth_gd", "libbluetooth_hci_pdl", + "libbluetooth_log", "libbt_shim_bridge", "libbt_shim_ffi", "libbtcore", diff --git a/system/gd/Android.bp b/system/gd/Android.bp index ad3e7a3d7e..e3ec8eb285 100644 --- a/system/gd/Android.bp +++ b/system/gd/Android.bp @@ -176,6 +176,7 @@ cc_defaults { "libbluetooth-protos", "libbluetooth-types", "libbluetooth_crypto_toolbox", + "libbluetooth_log", "libbluetooth_rust_interop", "libbt-platform-protos-lite", "libbt_shim_bridge", @@ -311,6 +312,7 @@ cc_binary { "libbluetooth_gd", "libbluetooth_hci_pdl", "libbluetooth_l2cap_pdl", + "libbluetooth_log", "libbluetooth_rust_interop", "libbluetooth_smp_pdl", "libbt_shim_bridge", @@ -363,6 +365,7 @@ cc_test { "mts_defaults", ], include_dirs: [ + "packages/modules/Bluetooth/system", "packages/modules/Bluetooth/system/include", "packages/modules/Bluetooth/system/types", ], @@ -438,10 +441,10 @@ cc_test { "libbluetooth_gd_unit_tests", "libbluetooth_hci_pdl", "libbluetooth_l2cap_pdl", + "libbluetooth_log", "libbluetooth_rust_interop", "libbluetooth_smp_pdl", "libbt-platform-protos-lite", - "libbt-platform-protos-lite", "libbt_shim_bridge", "libbt_shim_ffi", "libc++fs", @@ -494,6 +497,7 @@ cc_test { "libbluetooth-gdx", "libbluetooth-types", "libbluetooth_gd", + "libbluetooth_log", "libbt-btu-main-thread", "libbt-common", "libbt-jni-thread", @@ -502,6 +506,7 @@ cc_test { "libchrome", "libevent", "libflatbuffers-cpp", + "libgmock", "libosi", ], shared_libs: [ @@ -537,6 +542,7 @@ cc_test { cfi: true, }, static_libs: [ + "libbluetooth_log", "libbluetooth_rust_interop", "libbt_shim_bridge", "libbt_shim_ffi", @@ -572,6 +578,7 @@ cc_defaults { "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd_fuzzing", + "libbluetooth_log", "libbluetooth_rust_interop", "libbt_shim_bridge", "libbt_shim_ffi", diff --git a/system/gd/crypto_toolbox/BUILD.gn b/system/gd/crypto_toolbox/BUILD.gn index 1983ff921f..fac31aba29 100644 --- a/system/gd/crypto_toolbox/BUILD.gn +++ b/system/gd/crypto_toolbox/BUILD.gn @@ -22,5 +22,8 @@ static_library("crypto_toolbox") { include_dirs = [ "//bt/system/gd" ] - configs += [ "//bt/system/gd:gd_defaults" ] + configs += [ + "//bt/system/gd:gd_defaults", + "//bt/system/log:log_defaults", + ] } diff --git a/system/gd/discovery/device/bt_property.h b/system/gd/discovery/device/bt_property.h index 3ba7cb7fd0..8d4583d6ea 100644 --- a/system/gd/discovery/device/bt_property.h +++ b/system/gd/discovery/device/bt_property.h @@ -68,7 +68,7 @@ class BtPropertyLegacy { return const_cast<bt_property_t*>(&properties_[0]); } int Len() const { - return static_cast<int>(properties_.size() * sizeof(bt_property_t)); + return static_cast<int>(properties_.size()); } private: diff --git a/system/gd/discovery/device/bt_property_unittest.cc b/system/gd/discovery/device/bt_property_unittest.cc index 033a3afcd9..e486deea9f 100644 --- a/system/gd/discovery/device/bt_property_unittest.cc +++ b/system/gd/discovery/device/bt_property_unittest.cc @@ -912,7 +912,8 @@ TEST_F(BtPropertyMultiAllocationTest, async_data_multi) { for (size_t i = 0; i < kNumThreads; i++) { std::vector<std::shared_ptr<BtProperty>> props = future_vector[i].get(); BtPropertyLegacy legacy(props); - memcpy(bt_properties[i], (const void*)legacy.Ptr(), (size_t)legacy.Len()); + memcpy( + bt_properties[i], (const void*)legacy.Ptr(), (size_t)legacy.Len() * sizeof(bt_property_t)); ASSERT_EQ(BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP, (int)bt_properties[i]->type); ASSERT_EQ((int)sizeof(uint32_t), bt_properties[i]->len); diff --git a/system/gd/discovery/device/eir_data.cc b/system/gd/discovery/device/eir_data.cc index c7ef264ba8..50a4f8ed78 100644 --- a/system/gd/discovery/device/eir_data.cc +++ b/system/gd/discovery/device/eir_data.cc @@ -44,6 +44,17 @@ bool EirData::GetCompleteNames(std::vector<std::array<uint8_t, 240>>& names) con return !names.empty(); } +bool EirData::GetShortenedNames(std::vector<std::array<uint8_t, 240>>& names) const { + for (const auto& gap_data : gap_data_) { + if (gap_data.data_type_ == hci::GapDataType::SHORTENED_LOCAL_NAME) { + std::array<uint8_t, 240> array; + std::copy(gap_data.data_.begin(), gap_data.data_.end(), array.begin()); + names.push_back(array); + } + } + return !names.empty(); +} + bool EirData::GetUuids16(std::vector<uint16_t>& uuids) const { for (const auto& gap_data : gap_data_) { if (gap_data.data_type_ == hci::GapDataType::COMPLETE_LIST_16_BIT_UUIDS) { @@ -124,10 +135,10 @@ bool EirData::GetUuidsIncomplete128(std::vector<hci::Uuid>& uuids) const { return !uuids.empty(); } -bool EirData::GetDeviceId(std::vector<uint8_t>& device_ids) const { +bool EirData::GetDeviceId(std::vector<std::vector<uint8_t>>& device_ids) const { for (const auto& gap_data : gap_data_) { if (gap_data.data_type_ == hci::GapDataType::DEVICE_ID) { - if (gap_data.data_.size() == 1U) device_ids.push_back(gap_data.data_[0]); + device_ids.push_back(gap_data.data_); } } return !device_ids.empty(); @@ -151,14 +162,29 @@ bool EirData::GetSecurityManagerOobFlags(std::vector<std::vector<uint8_t>>& flag return !flags.empty(); } -bool EirData::GetServiceUuuids32(std::vector<uint32_t>& uuids) const { +bool EirData::GetServiceUuuids16(std::vector<service_uuid16_t>& uuids) const { + for (const auto& gap_data : gap_data_) { + if (gap_data.data_type_ == hci::GapDataType::SERVICE_DATA_16_BIT_UUIDS) { + if (gap_data.data_.size() < Uuid::kNumBytes16) continue; + auto it = gap_data.data_.begin(); + uuids.push_back({ + .uuid = (uint16_t)(*it | *(it + 1) << 8), + .data = std::vector<uint8_t>(it + Uuid::kNumBytes16, gap_data.data_.end()), + }); + } + } + return !uuids.empty(); +} + +bool EirData::GetServiceUuuids32(std::vector<service_uuid32_t>& uuids) const { for (const auto& gap_data : gap_data_) { if (gap_data.data_type_ == hci::GapDataType::SERVICE_DATA_32_BIT_UUIDS) { + if (gap_data.data_.size() < Uuid::kNumBytes32) continue; auto it = gap_data.data_.begin(); - while (std::distance(it, gap_data.data_.end()) >= (signed)Uuid::kNumBytes32) { - uuids.push_back(*it | *(it + 1) << 8 | *(it + 2) << 16 | *(it + 3) << 24); - it += Uuid::kNumBytes32; - } + uuids.push_back({ + .uuid = (uint32_t)(*it | *(it + 1) << 8 | *(it + 2) << 16 | *(it + 3) << 24), + .data = std::vector<uint8_t>(it + Uuid::kNumBytes32, gap_data.data_.end()), + }); } } return !uuids.empty(); diff --git a/system/gd/discovery/device/eir_data.h b/system/gd/discovery/device/eir_data.h index 768b53ba4e..d4752aec18 100644 --- a/system/gd/discovery/device/eir_data.h +++ b/system/gd/discovery/device/eir_data.h @@ -26,11 +26,22 @@ namespace bluetooth { namespace discovery { namespace device { +struct service_uuid16_t { + uint16_t uuid; + std::vector<uint8_t> data; +}; + +struct service_uuid32_t { + uint32_t uuid; + std::vector<uint8_t> data; +}; + class EirData : public DataParser { public: EirData(const std::vector<uint8_t>& data); bool GetCompleteNames(std::vector<std::array<uint8_t, 240>>&) const; + bool GetShortenedNames(std::vector<std::array<uint8_t, 240>>&) const; bool GetUuids16(std::vector<uint16_t>&) const; bool GetUuidsIncomplete16(std::vector<uint16_t>&) const; @@ -39,12 +50,13 @@ class EirData : public DataParser { bool GetUuids128(std::vector<hci::Uuid>&) const; bool GetUuidsIncomplete128(std::vector<hci::Uuid>&) const; - bool GetDeviceId(std::vector<uint8_t>&) const; + bool GetDeviceId(std::vector<std::vector<uint8_t>>&) const; bool GetManufacturerSpecificData(std::vector<std::vector<uint8_t>>&) const; bool GetSecurityManagerOobFlags(std::vector<std::vector<uint8_t>>&) const; - bool GetServiceUuuids32(std::vector<uint32_t>&) const; + bool GetServiceUuuids16(std::vector<service_uuid16_t>&) const; + bool GetServiceUuuids32(std::vector<service_uuid32_t>&) const; bool GetTxPowerLevel(std::vector<int8_t>&) const; }; diff --git a/system/gd/discovery/device/eir_data_unittest.cc b/system/gd/discovery/device/eir_data_unittest.cc index cf7017df61..3d1ea72058 100644 --- a/system/gd/discovery/device/eir_data_unittest.cc +++ b/system/gd/discovery/device/eir_data_unittest.cc @@ -17,6 +17,7 @@ #include "discovery/device/eir_data.h" #include "discovery/device/eir_test_data_packets.h" +#include "gmock/gmock.h" #include "gtest/gtest.h" #include "hci/hci_packets.h" #include "os/log.h" @@ -29,6 +30,9 @@ constexpr uint8_t kPartialUuid16Data[] = { 0x2, static_cast<uint8_t>(hci::GapDataType::COMPLETE_LIST_16_BIT_UUIDS), 0x34}; constexpr uint8_t kOneUuid16Data[] = { 0x3, static_cast<uint8_t>(hci::GapDataType::COMPLETE_LIST_16_BIT_UUIDS), 0x34, 0x12}; +constexpr char kAudiMmi9962[] = "Audi_MMI_9962"; +constexpr char kChromeBoxForMeetings[] = "Chromebox for Meetings"; + } // namespace namespace debug { @@ -64,110 +68,145 @@ TEST(EirDataTest, one_uuid16) { } TEST(EirDataTest, test_data_packets__data_type) { - for (const auto& pkt : data_packets) { - const EirData eir_data(std::vector<uint8_t>(&pkt[kEirOffset], &pkt[kEirOffset] + kEirSize)); - std::vector<hci::GapDataType> gap_data_types = eir_data.GetDataTypes(); - if (!gap_data_types.empty()) { - LOG_INFO("pkt:"); - for (const auto& type : gap_data_types) { - LOG_INFO(" Data type:%s", hci::GapDataTypeText(type).c_str()); - } - } - } + ASSERT_EQ(1U, selected_packets.count("pkt34639")); + const auto& pkt = selected_packets["pkt34639"]; + const EirData eir_data(std::vector<uint8_t>(&pkt[kEirOffset], &pkt[kEirOffset] + kEirSize)); + + std::vector<hci::GapDataType> gap_data_types = eir_data.GetDataTypes(); + ASSERT_EQ(6U, gap_data_types.size()); } TEST(EirDataTest, test_data_packets__complete_name) { - for (const auto& pkt : data_packets) { - const EirData eir_data(std::vector<uint8_t>(&pkt[kEirOffset], &pkt[kEirOffset] + kEirSize)); - std::vector<std::array<uint8_t, kEirSize>> names; - if (eir_data.GetCompleteNames(names)) { - LOG_INFO("Name pkt:"); - for (const auto& v : names) { - std::string name(v.begin(), v.end()); - LOG_INFO(" Name:%s", name.c_str()); - } - } - } + ASSERT_EQ(1U, selected_packets.count("pkt34639")); + const auto& pkt = selected_packets["pkt34639"]; + const EirData eir_data(std::vector<uint8_t>(&pkt[kEirOffset], &pkt[kEirOffset] + kEirSize)); + + std::vector<std::array<uint8_t, kEirSize>> names; + ASSERT_TRUE(eir_data.GetCompleteNames(names)); + ASSERT_EQ(1U, names.size()); + std::string name(names[0].begin(), names[0].end()); + ASSERT_STREQ(kAudiMmi9962, name.c_str()); } TEST(EirDataTest, test_data_packets__uuids16) { - for (const auto& pkt : data_packets) { - const EirData eir_data(std::vector<uint8_t>(&pkt[kEirOffset], &pkt[kEirOffset] + kEirSize)); - std::vector<uint16_t> uuids; - if (eir_data.GetUuids16(uuids)) { - LOG_INFO("Uuid pkt:"); - for (const auto& u : uuids) { - LOG_INFO(" Uuid:0x%x", u); - } - } - } + ASSERT_EQ(1U, selected_packets.count("pkt34639")); + const auto& pkt = selected_packets["pkt34639"]; + const EirData eir_data(std::vector<uint8_t>(&pkt[kEirOffset], &pkt[kEirOffset] + kEirSize)); + + std::vector<uint16_t> uuids16; + ASSERT_TRUE(eir_data.GetUuids16(uuids16)); + ASSERT_EQ(14U, uuids16.size()); + ASSERT_EQ(0x112e, uuids16[0]); + ASSERT_EQ(0x180a, uuids16[13]); } TEST(EirDataTest, test_data_packets__uuids16_incomplete) { - for (const auto& pkt : data_packets) { - const EirData eir_data(std::vector<uint8_t>(&pkt[kEirOffset], &pkt[kEirOffset] + kEirSize)); - std::vector<uint16_t> uuids; - if (eir_data.GetUuidsIncomplete16(uuids)) { - LOG_INFO("Uuid pkt:"); - for (const auto& u : uuids) { - LOG_INFO(" Uuid:0x%x", u); - } - } - } + ASSERT_EQ(1U, selected_packets.count("pkt19200")); + const auto& pkt = selected_packets["pkt19200"]; + const EirData eir_data(std::vector<uint8_t>(&pkt[kEirOffset], &pkt[kEirOffset] + kEirSize)); + + std::vector<uint16_t> uuids16; + ASSERT_TRUE(eir_data.GetUuidsIncomplete16(uuids16)); + ASSERT_EQ(7U, uuids16.size()); + ASSERT_EQ(0x110d, uuids16[0]); + ASSERT_EQ(0x1131, uuids16[6]); } TEST(EirDataTest, test_data_packets__device_id) { - for (const auto& pkt : data_packets) { - const EirData eir_data(std::vector<uint8_t>(&pkt[kEirOffset], &pkt[kEirOffset] + kEirSize)); - std::vector<uint8_t> device_ids; - if (eir_data.GetDeviceId(device_ids)) { - LOG_INFO(" device_id count:%llu", (unsigned long long)device_ids.size()); - } - } + ASSERT_EQ(1U, selected_packets.count("pkt2062")); + const auto& pkt = selected_packets["pkt2062"]; + const EirData eir_data(std::vector<uint8_t>(&pkt[kEirOffset], &pkt[kEirOffset] + kEirSize)); + + std::vector<std::vector<uint8_t>> device_ids; + ASSERT_TRUE(eir_data.GetDeviceId(device_ids)); + ASSERT_EQ(1U, device_ids.size()); + ASSERT_EQ(0x01, device_ids[0][0]); } TEST(EirDataTest, test_data_packets__manufacturer_data) { - for (const auto& pkt : data_packets) { - const EirData eir_data(std::vector<uint8_t>(&pkt[kEirOffset], &pkt[kEirOffset] + kEirSize)); - std::vector<std::vector<uint8_t>> mfr_data; - if (eir_data.GetManufacturerSpecificData(mfr_data)) { - LOG_INFO(" mfr data count:%llu", (unsigned long long)mfr_data.size()); - } - } + ASSERT_EQ(1U, selected_packets.count("pkt26171")); + const auto& pkt = selected_packets["pkt26171"]; + const EirData eir_data(std::vector<uint8_t>(&pkt[kEirOffset], &pkt[kEirOffset] + kEirSize)); + + std::vector<std::vector<uint8_t>> mfr_data; + ASSERT_TRUE(eir_data.GetManufacturerSpecificData(mfr_data)); + ASSERT_EQ(1U, mfr_data.size()); + ASSERT_EQ(0, mfr_data[0][0]); } TEST(EirDataTest, test_data_packets__security_manager_oob_flags) { - for (const auto& pkt : data_packets) { - const EirData eir_data(std::vector<uint8_t>(&pkt[kEirOffset], &pkt[kEirOffset] + kEirSize)); - std::vector<std::vector<uint8_t>> oob_flags; - if (eir_data.GetManufacturerSpecificData(oob_flags)) { - LOG_INFO(" oob flags count:%llu", (unsigned long long)oob_flags.size()); - } - } + ASSERT_EQ(1U, selected_packets.count("pkt26171")); + const auto& pkt = selected_packets["pkt26171"]; + const EirData eir_data(std::vector<uint8_t>(&pkt[kEirOffset], &pkt[kEirOffset] + kEirSize)); + + std::vector<std::vector<uint8_t>> oob_flags; + ASSERT_TRUE(eir_data.GetManufacturerSpecificData(oob_flags)); + ASSERT_EQ(1U, oob_flags.size()); + ASSERT_EQ(0, oob_flags[0][0]); +} + +TEST(EirDataTest, test_data_packets__service_uuids16) { + ASSERT_EQ(1U, selected_packets.count("pktAsha")); + const auto& pkt = selected_packets["pktAsha"]; + const EirData eir_data(std::vector<uint8_t>(&pkt[kEirOffset], &pkt[kEirOffset] + kEirSize)); + + std::vector<discovery::device::service_uuid16_t> service_uuids16; + ASSERT_TRUE(eir_data.GetServiceUuuids16(service_uuids16)); + ASSERT_EQ(1U, service_uuids16.size()); + ASSERT_EQ(0xfdf0, service_uuids16[0].uuid); } TEST(EirDataTest, test_data_packets__service_uuids32) { for (const auto& pkt : data_packets) { const EirData eir_data(std::vector<uint8_t>(&pkt[kEirOffset], &pkt[kEirOffset] + kEirSize)); - std::vector<uint32_t> uuids; - if (eir_data.GetServiceUuuids32(uuids)) { - for (const auto& uuid : uuids) { - LOG_INFO(" service uuid:%u", uuid); - } - } + std::vector<discovery::device::service_uuid32_t> service_uuids32; + ASSERT_FALSE(eir_data.GetServiceUuuids32(service_uuids32)); } } TEST(EirDataTest, test_data_packets__tx_power_level) { - for (const auto& pkt : data_packets) { - const EirData eir_data(std::vector<uint8_t>(&pkt[kEirOffset], &pkt[kEirOffset] + kEirSize)); - std::vector<int8_t> levels; - if (eir_data.GetTxPowerLevel(levels)) { - for (const auto& level : levels) { - LOG_INFO(" tx power level:%hhd", level); - } - } - } + ASSERT_EQ(1U, selected_packets.count("pkt34639")); + const auto& pkt = selected_packets["pkt34639"]; + const EirData eir_data(std::vector<uint8_t>(&pkt[kEirOffset], &pkt[kEirOffset] + kEirSize)); + + std::vector<int8_t> levels; + ASSERT_TRUE(eir_data.GetTxPowerLevel(levels)); + ASSERT_EQ(1U, levels.size()); + ASSERT_EQ(4, levels[0]); +} + +TEST(EirDataTest, test_select_packets__pktAsha) { + ASSERT_EQ(1U, selected_packets.count("pktAsha")); + const auto& pkt = selected_packets["pktAsha"]; + const EirData eir_data(std::vector<uint8_t>(&pkt[kEirOffset], &pkt[kEirOffset] + kEirSize)); + + std::vector<std::array<uint8_t, kEirSize>> names; + ASSERT_TRUE(eir_data.GetCompleteNames(names)); + std::string name(names[0].begin(), names[0].end()); + ASSERT_STREQ(kChromeBoxForMeetings, name.c_str()); + + std::vector<int8_t> tx_power_level; + ASSERT_TRUE(eir_data.GetTxPowerLevel(tx_power_level)); + ASSERT_EQ(10, tx_power_level[0]); + + const std::vector<uint8_t> v1 = + std::vector<uint8_t>({0x01, 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00}); + std::vector<std::vector<uint8_t>> device_ids; + ASSERT_TRUE(eir_data.GetDeviceId(device_ids)); + ASSERT_EQ(v1.size(), device_ids[0].size()); + ASSERT_THAT(v1, testing::ContainerEq(device_ids[0])); + + const std::vector<uint16_t> v2 = + std::vector<uint16_t>({0x1800, 0x1801, 0x180a, 0x110e, 0x110c, 0x111f, 0x110a}); + std::vector<uint16_t> uuids16; + ASSERT_TRUE(eir_data.GetUuids16(uuids16)); + ASSERT_EQ(v2.size(), uuids16.size()); + ASSERT_THAT(v2, testing::ContainerEq(uuids16)); + + std::vector<discovery::device::service_uuid16_t> service_uuids16; + ASSERT_TRUE(eir_data.GetServiceUuuids16(service_uuids16)); + ASSERT_EQ(1U, service_uuids16.size()); + ASSERT_EQ(0xfdf0, service_uuids16[0].uuid); } TEST(EirDataTest, test_select_packets__pkt34639) { diff --git a/system/gd/discovery/device/eir_test_data_packets.cc b/system/gd/discovery/device/eir_test_data_packets.cc index ad974aa840..cf2a21c99f 100644 --- a/system/gd/discovery/device/eir_test_data_packets.cc +++ b/system/gd/discovery/device/eir_test_data_packets.cc @@ -13413,7 +13413,7 @@ static const unsigned char pkt7050[258] = { }; // Frame (258 bytes) -static const unsigned char pkt7051[258] = { +static const unsigned char pktAsha[258] = { 0x04, 0x2f, 0xff, 0x01, 0xdc, 0xd0, 0xf1, 0x2a, // ./.....* 0x9a, 0xb8, 0x01, 0x00, 0x04, 0x01, 0x48, 0x0c, // ......H. 0x0e, 0x7f, 0x17, 0x09, 0x43, 0x68, 0x72, 0x6f, // ....Chro @@ -13422,9 +13422,9 @@ static const unsigned char pkt7051[258] = { 0x67, 0x73, 0x02, 0x0a, 0x0a, 0x09, 0x10, 0x01, // gs...... 0x00, 0xe0, 0x00, 0x05, 0xc4, 0x6c, 0x00, 0x0f, // .....l.. 0x03, 0x00, 0x18, 0x01, 0x18, 0x0a, 0x18, 0x0e, // ........ - 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ + 0x11, 0x0c, 0x11, 0x1f, 0x11, 0x0a, 0x11, 0x0c, // ........ + 0x16, 0xf0, 0xfd, 0x01, 0x02, 0x03, 0x04, 0x05, // ........ + 0x06, 0x07, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ........ @@ -13450,7 +13450,11 @@ static const unsigned char pkt7051[258] = { }; std::unordered_map<std::string, const unsigned char*> selected_packets = { + {"pkt19200", pkt19200}, + {"pkt2062", pkt2062}, + {"pkt26171", pkt26171}, {"pkt34639", pkt34639}, + {"pktAsha", pktAsha}, }; std::vector<const unsigned char*> data_packets = { @@ -13494,5 +13498,5 @@ std::vector<const unsigned char*> data_packets = { pkt6434, pkt6503, pkt6504, pkt6511, pkt6512, pkt6513, pkt6518, pkt6525, pkt6540, pkt6567, pkt6854, pkt6867, pkt6870, pkt6871, pkt6875, pkt6876, pkt6886, pkt6895, pkt6900, pkt6901, pkt6907, pkt6908, pkt6935, pkt7024, pkt7030, pkt7035, pkt7038, - pkt7049, pkt7050, pkt7051, + pkt7049, pkt7050, pktAsha, }; diff --git a/system/gd/dumpsys/BUILD.gn b/system/gd/dumpsys/BUILD.gn index 7944263c1b..327089c2ed 100644 --- a/system/gd/dumpsys/BUILD.gn +++ b/system/gd/dumpsys/BUILD.gn @@ -24,7 +24,10 @@ source_set("BluetoothDumpsysSources") { cflags_cc = [ "-Wno-enum-compare-switch" ] - configs += [ "//bt/system/gd:gd_defaults" ] + configs += [ + "//bt/system/gd:gd_defaults", + "//bt/system/log:log_defaults", + ] deps = [ "//bt/system/gd:gd_default_deps" ] } @@ -33,5 +36,8 @@ bt_flatc_bundler("libbluetooth-dumpsys") { filename = "generated_dumpsys_bundled_schema" namespace = "bluetooth::dumpsys" deps = [ "//bt/system/gd:BluetoothGeneratedDumpsysBinarySchema_bfbs" ] - configs = [ "//bt/system/gd:gd_defaults" ] + configs = [ + "//bt/system/gd:gd_defaults", + "//bt/system/log:log_defaults", + ] } diff --git a/system/gd/hci/acl_manager.cc b/system/gd/hci/acl_manager.cc index ef11ba0c3e..4312baf6c1 100644 --- a/system/gd/hci/acl_manager.cc +++ b/system/gd/hci/acl_manager.cc @@ -34,6 +34,7 @@ #include "hci/remote_name_request.h" #include "hci_acl_manager_generated.h" #include "security/security_module.h" +#include "storage/config_keys.h" #include "storage/storage_module.h" namespace bluetooth { @@ -281,8 +282,8 @@ void AclManager::SetPrivacyPolicyForInitiatorAddress( std::chrono::milliseconds minimum_rotation_time, std::chrono::milliseconds maximum_rotation_time) { Octet16 rotation_irk{}; - auto irk_prop = - GetDependency<storage::StorageModule>()->GetProperty("Adapter", "LE_LOCAL_KEY_IRK"); + auto irk_prop = GetDependency<storage::StorageModule>()->GetProperty( + BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK); if (irk_prop.has_value()) { auto irk = common::ByteArray<16>::FromString(irk_prop.value()); if (irk.has_value()) { diff --git a/system/gd/hci/acl_manager/classic_impl.h b/system/gd/hci/acl_manager/classic_impl.h index 0c0b13d1f8..35c82b71c0 100644 --- a/system/gd/hci/acl_manager/classic_impl.h +++ b/system/gd/hci/acl_manager/classic_impl.h @@ -368,29 +368,6 @@ struct classic_impl : public security::ISecurityManagerListener { auto status = connection_complete.GetStatus(); auto address = connection_complete.GetBdAddr(); - // TODO(b/261610529) - Some controllers incorrectly return connection - // failures via HCI Connect Complete instead of SCO connect complete. - // Temporarily just drop these packets until we have finer grained control - // over these ASSERTs. -#if TARGET_FLOSS - auto handle = connection_complete.GetConnectionHandle(); - auto link_type = connection_complete.GetLinkType(); - - // HACK: Some failed SCO connections are reporting failures via - // ConnectComplete instead of ScoConnectionComplete. - // The pattern of it is that the handle is always 0xffff. - // We check it with 0x0fff since PDL only extracts 12 bits for handle. - // Drop such packets when the pattern is matched. - if (handle == 0x0fff && link_type == LinkType::SCO) { - LOG_ERROR( - "ConnectionComplete with invalid handle(%u), link type(%u) and status(%d). Dropping packet.", - handle, - link_type, - status); - return; - } -#endif - acl_scheduler_->ReportAclConnectionCompletion( address, handler_->BindOnceOn( diff --git a/system/gd/hci/distance_measurement_manager.cc b/system/gd/hci/distance_measurement_manager.cc index f8a26c575a..dac1d9a937 100644 --- a/system/gd/hci/distance_measurement_manager.cc +++ b/system/gd/hci/distance_measurement_manager.cc @@ -110,8 +110,8 @@ struct DistanceMeasurementManager::impl { hci_layer_->RegisterLeEventHandler( hci::SubeventCode::TRANSMIT_POWER_REPORTING, handler_->BindOn(this, &impl::on_transmit_power_reporting)); - if (!IS_FLAG_ENABLED(channel_sounding)) { - LOG_INFO("IS_FLAG_ENABLED channel_sounding: false"); + if (!IS_FLAG_ENABLED(channel_sounding_in_stack)) { + LOG_INFO("IS_FLAG_ENABLED channel_sounding_in_stack: false"); return; } distance_measurement_interface_ = hci_layer_->GetDistanceMeasurementInterface( @@ -172,7 +172,7 @@ struct DistanceMeasurementManager::impl { "connection_handle: %d, address: %s", connection_handle, ADDRESS_TO_LOGGABLE_CSTR(cs_remote_address)); - if (!IS_FLAG_ENABLED(channel_sounding)) { + if (!IS_FLAG_ENABLED(channel_sounding_in_stack)) { LOG_ERROR("Channel Sounding is not enabled"); distance_measurement_callbacks_->OnDistanceMeasurementStartFail( cs_remote_address, REASON_INTERNAL_ERROR, METHOD_CS); diff --git a/system/gd/hci/hci_layer.cc b/system/gd/hci/hci_layer.cc index 20b34cc0ab..8bfb38dd89 100644 --- a/system/gd/hci/hci_layer.cc +++ b/system/gd/hci/hci_layer.cc @@ -425,6 +425,9 @@ struct HciLayer::impl { case EventCode::LE_META_EVENT: on_le_meta_event(event); break; + case EventCode::HARDWARE_ERROR: + on_hardware_error(event); + break; default: if (event_handlers_.find(event_code) == event_handlers_.end()) { LOG_WARN( @@ -437,6 +440,12 @@ struct HciLayer::impl { } } + void on_hardware_error(EventView event) { + HardwareErrorView event_view = HardwareErrorView::Create(event); + ASSERT(event_view.IsValid()); + LOG_ALWAYS_FATAL("Hardware Error Event with code 0x%02x", event_view.GetHardwareCode()); + } + void on_le_meta_event(EventView event) { LeMetaEventView meta_event_view = LeMetaEventView::Create(event); ASSERT(meta_event_view.IsValid()); diff --git a/system/gd/hci/hci_layer_unittest.cc b/system/gd/hci/hci_layer_unittest.cc index f8c8bee72e..adfa8a12f0 100644 --- a/system/gd/hci/hci_layer_unittest.cc +++ b/system/gd/hci/hci_layer_unittest.cc @@ -191,6 +191,18 @@ TEST_F(HciLayerDeathTest, abort_on_root_inflammation_event) { ""); } +TEST_F(HciLayerDeathTest, abort_on_hardware_error) { + FailIfResetNotSent(); + + ASSERT_DEATH( + { + sync_handler(); + hal_->InjectEvent(HardwareErrorBuilder::Create(0xbb)); + sync_handler(); + }, + ""); +} + TEST_F(HciLayerTest, successful_reset) { FailIfResetNotSent(); hal_->InjectEvent(ResetCompleteBuilder::Create(1, ErrorCode::SUCCESS)); diff --git a/system/gd/hci/le_address_manager.cc b/system/gd/hci/le_address_manager.cc index 1c954a36c3..8721adb0b1 100644 --- a/system/gd/hci/le_address_manager.cc +++ b/system/gd/hci/le_address_manager.cc @@ -16,6 +16,8 @@ #include "hci/le_address_manager.h" +#include <android_bluetooth_flags.h> + #include "common/init_flags.h" #include "hci/octets.h" #include "os/log.h" @@ -72,6 +74,11 @@ void LeAddressManager::SetPrivacyPolicyForInitiatorAddress( supports_ble_privacy_ = supports_ble_privacy; LOG_INFO("SetPrivacyPolicyForInitiatorAddress with policy %d", address_policy); + if (IS_FLAG_ENABLED(nrpa_non_connectable_adv)) { + minimum_rotation_time_ = minimum_rotation_time; + maximum_rotation_time_ = maximum_rotation_time; + } + switch (address_policy_) { case AddressPolicy::USE_PUBLIC_ADDRESS: le_address_ = AddressWithType(public_address_, AddressType::PUBLIC_DEVICE_ADDRESS); @@ -97,8 +104,10 @@ void LeAddressManager::SetPrivacyPolicyForInitiatorAddress( case AddressPolicy::USE_RESOLVABLE_ADDRESS: le_address_ = fixed_address; rotation_irk_ = rotation_irk; - minimum_rotation_time_ = minimum_rotation_time; - maximum_rotation_time_ = maximum_rotation_time; + if (!IS_FLAG_ENABLED(nrpa_non_connectable_adv)) { + minimum_rotation_time_ = minimum_rotation_time; + maximum_rotation_time_ = maximum_rotation_time; + } address_rotation_alarm_ = std::make_unique<os::Alarm>(handler_); set_random_address(); break; @@ -228,7 +237,9 @@ AddressWithType LeAddressManager::NewResolvableAddress() { } AddressWithType LeAddressManager::NewNonResolvableAddress() { - ASSERT(RotatingAddress()); + if (!IS_FLAG_ENABLED(nrpa_non_connectable_adv)) { + ASSERT(RotatingAddress()); + } hci::Address address = generate_nrpa(); auto random_address = AddressWithType(address, AddressType::RANDOM_DEVICE_ADDRESS); return random_address; diff --git a/system/gd/hci/le_advertising_manager.cc b/system/gd/hci/le_advertising_manager.cc index 5d4be6313a..5cbc24afbe 100644 --- a/system/gd/hci/le_advertising_manager.cc +++ b/system/gd/hci/le_advertising_manager.cc @@ -110,6 +110,26 @@ AdvertiserAddressType GetAdvertiserAddressTypeFromRequestedTypeAndPolicy( } } +/** + * Determines the address type to use for non-connectable advertisement. + * (1) if the host only supports public/static address policy, non-connectable advertisement + * can use both Public and NRPA if requested. Use NRPA if RPA is requested. + * (2) in other cases, based on the requested type and the address manager policy. + */ +AdvertiserAddressType GetAdvertiserAddressTypeNonConnectable( + AdvertiserAddressType requested_address_type, LeAddressManager::AddressPolicy address_policy) { + switch (address_policy) { + case LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS: + case LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS: + return requested_address_type == AdvertiserAddressType::RESOLVABLE_RANDOM + ? AdvertiserAddressType::NONRESOLVABLE_RANDOM + : requested_address_type; + default: + return GetAdvertiserAddressTypeFromRequestedTypeAndPolicy( + requested_address_type, address_policy); + } +} + struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallback { impl(Module* module) : module_(module), le_advertising_interface_(nullptr), num_instances_(0) {} @@ -440,9 +460,13 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb address_manager_registered = true; } - advertising_sets_[id].address_type = GetAdvertiserAddressTypeFromRequestedTypeAndPolicy( - config.requested_advertiser_address_type, le_address_manager_->GetAddressPolicy()); - + if (IS_FLAG_ENABLED(nrpa_non_connectable_adv) && !config.connectable) { + advertising_sets_[id].address_type = GetAdvertiserAddressTypeNonConnectable( + config.requested_advertiser_address_type, le_address_manager_->GetAddressPolicy()); + } else { + advertising_sets_[id].address_type = GetAdvertiserAddressTypeFromRequestedTypeAndPolicy( + config.requested_advertiser_address_type, le_address_manager_->GetAddressPolicy()); + } advertising_sets_[id].current_address = new_advertiser_address(id); set_parameters(id, config); @@ -572,8 +596,13 @@ struct LeAdvertisingManager::impl : public bluetooth::hci::LeAddressManagerCallb advertising_sets_[id].duration = duration; advertising_sets_[id].max_extended_advertising_events = max_ext_adv_events; advertising_sets_[id].handler = handler; - advertising_sets_[id].address_type = GetAdvertiserAddressTypeFromRequestedTypeAndPolicy( - config.requested_advertiser_address_type, le_address_manager_->GetAddressPolicy()); + if (IS_FLAG_ENABLED(nrpa_non_connectable_adv) && !config.connectable) { + advertising_sets_[id].address_type = GetAdvertiserAddressTypeNonConnectable( + config.requested_advertiser_address_type, le_address_manager_->GetAddressPolicy()); + } else { + advertising_sets_[id].address_type = GetAdvertiserAddressTypeFromRequestedTypeAndPolicy( + config.requested_advertiser_address_type, le_address_manager_->GetAddressPolicy()); + } advertising_sets_[id].current_address = new_advertiser_address(id); set_parameters(id, config); diff --git a/system/gd/hci/le_advertising_manager_test.cc b/system/gd/hci/le_advertising_manager_test.cc index c0c7bc0ed4..2acbaa0b90 100644 --- a/system/gd/hci/le_advertising_manager_test.cc +++ b/system/gd/hci/le_advertising_manager_test.cc @@ -1890,6 +1890,79 @@ TEST_F(LeExtendedAdvertisingManagerTest, use_public_address_type_if_public_addre EXPECT_EQ(set_parameters_command.GetOwnAddressType(), OwnAddressType::PUBLIC_DEVICE_ADDRESS); } +TEST_F_WITH_FLAGS( + LeExtendedAdvertisingManagerTest, + use_nrpa_if_public_address_policy_non_connectable, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, nrpa_non_connectable_adv))) { + // arrange: use PUBLIC address policy + test_acl_manager_->SetAddressPolicy(LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS); + + // act: start non-connectable advertising set with RPA + le_advertising_manager_->ExtendedCreateAdvertiser( + kAdvertiserClientIdJni, + 0x00, + AdvertisingConfig{ + .requested_advertiser_address_type = AdvertiserAddressType::RESOLVABLE_RANDOM, + .channel_map = 1, + .connectable = false, + }, + scan_callback, + set_terminated_callback, + 0, + 0, + client_handler_); + ASSERT_EQ( + test_hci_layer_->GetCommand().GetOpCode(), OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS); + test_hci_layer_->IncomingEvent(LeSetExtendedAdvertisingParametersCompleteBuilder::Create( + uint8_t{1}, ErrorCode::SUCCESS, static_cast<uint8_t>(-23))); + + auto command = LeAdvertisingCommandView::Create(test_hci_layer_->GetCommand()); + ASSERT_TRUE(command.IsValid()); + ASSERT_EQ(command.GetOpCode(), OpCode::LE_SET_ADVERTISING_SET_RANDOM_ADDRESS); + + auto set_address_command = + LeSetAdvertisingSetRandomAddressView::Create(LeAdvertisingCommandView::Create(command)); + ASSERT_TRUE(set_address_command.IsValid()); + EXPECT_EQ(set_address_command.GetOpCode(), OpCode::LE_SET_ADVERTISING_SET_RANDOM_ADDRESS); + + // checking that it is an NRPA (first two bits = 0b00) + Address address = set_address_command.GetRandomAddress(); + EXPECT_EQ(address.data()[5] >> 6, 0b00); +} + +TEST_F_WITH_FLAGS( + LeExtendedAdvertisingManagerTest, + use_public_if_requested_with_public_address_policy_non_connectable, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, nrpa_non_connectable_adv))) { + // arrange: use PUBLIC address policy + test_acl_manager_->SetAddressPolicy(LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS); + + // act: start non-connectable advertising set with PUBLIC + le_advertising_manager_->ExtendedCreateAdvertiser( + kAdvertiserClientIdJni, + 0x00, + AdvertisingConfig{ + .requested_advertiser_address_type = AdvertiserAddressType::PUBLIC, + .channel_map = 1, + .connectable = false, + }, + scan_callback, + set_terminated_callback, + 0, + 0, + client_handler_); + auto command = LeAdvertisingCommandView::Create(test_hci_layer_->GetCommand()); + + // assert + ASSERT_TRUE(command.IsValid()); + EXPECT_EQ(command.GetOpCode(), OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS); + + auto set_parameters_command = + LeSetExtendedAdvertisingParametersView::Create(LeAdvertisingCommandView::Create(command)); + ASSERT_TRUE(set_parameters_command.IsValid()); + EXPECT_EQ(set_parameters_command.GetOwnAddressType(), OwnAddressType::PUBLIC_DEVICE_ADDRESS); +} + } // namespace } // namespace hci } // namespace bluetooth diff --git a/system/gd/hci/le_scanning_manager.cc b/system/gd/hci/le_scanning_manager.cc index 539427648b..0e5c2e306c 100644 --- a/system/gd/hci/le_scanning_manager.cc +++ b/system/gd/hci/le_scanning_manager.cc @@ -457,6 +457,7 @@ struct LeScanningManager::impl : public LeAddressManagerCallback { // with hardware-filtering features should we ignore waiting for scan response, and make sure // scan responses are still reported too. scanning_reassembler_.SetIgnoreScanResponses( + le_scan_type_ == LeScanType::PASSIVE || filter_policy_ == LeScanningFilterPolicy::FILTER_ACCEPT_LIST_ONLY); std::optional<LeScanningReassembler::CompleteAdvertisingData> processed_report = diff --git a/system/gd/metrics/BUILD.gn b/system/gd/metrics/BUILD.gn index d4a952258a..c96a47c3b7 100644 --- a/system/gd/metrics/BUILD.gn +++ b/system/gd/metrics/BUILD.gn @@ -22,12 +22,18 @@ source_set("BluetoothMetricsSources_chromeos") { ] deps = [ "//bt/system/gd:gd_default_deps" ] - configs += [ "//bt/system/gd:gd_defaults" ] + configs += [ + "//bt/system/gd:gd_defaults", + "//bt/system/log:log_defaults", + ] } source_set("BluetoothMetricsSources_linux") { sources = [ "linux/metrics.cc" ] - configs += [ "//bt/system/gd:gd_defaults" ] + configs += [ + "//bt/system/gd:gd_defaults", + "//bt/system/log:log_defaults", + ] } source_set("BluetoothMetricsSources") { @@ -36,7 +42,10 @@ source_set("BluetoothMetricsSources") { "utils.cc", ] - configs += [ "//bt/system/gd:gd_defaults"] + configs += [ + "//bt/system/gd:gd_defaults", + "//bt/system/log:log_defaults", + ] deps = [ "//bt/system/gd:gd_default_deps" ] if (target_os == "chromeos") { diff --git a/system/gd/neighbor/BUILD.gn b/system/gd/neighbor/BUILD.gn index 21571263b7..d3ec55d490 100644 --- a/system/gd/neighbor/BUILD.gn +++ b/system/gd/neighbor/BUILD.gn @@ -25,5 +25,8 @@ source_set("BluetoothNeighborSources") { deps = [ "//bt/system/gd:gd_default_deps" ] - configs += [ "//bt/system/gd:gd_defaults" ] + configs += [ + "//bt/system/gd:gd_defaults", + "//bt/system/log:log_defaults", + ] } diff --git a/system/gd/os/BUILD.gn b/system/gd/os/BUILD.gn index 7842583a42..b463430a9f 100644 --- a/system/gd/os/BUILD.gn +++ b/system/gd/os/BUILD.gn @@ -22,7 +22,10 @@ source_set("BluetoothOsSources_chromeos") { "syslog.cc", ] - configs += [ "//bt/system/gd:gd_defaults" ] + configs += [ + "//bt/system/gd:gd_defaults", + "//bt/system/log:log_defaults", + ] deps = [ "//bt/system:libbt-platform-protos-lite", "//bt/system/gd/rust/shim:init_flags_bridge_header", @@ -39,7 +42,10 @@ source_set("BluetoothOsSources_linux") { "syslog.cc", ] - configs += [ "//bt/system/gd:gd_defaults" ] + configs += [ + "//bt/system/gd:gd_defaults", + "//bt/system/log:log_defaults", + ] deps = [ "//bt/system:libbt-platform-protos-lite", "//bt/system/gd/rust/shim:init_flags_bridge_header", @@ -59,7 +65,10 @@ source_set("BluetoothOsSources_linux_generic") { "linux_generic/wakelock_manager.cc", ] - configs += [ "//bt/system/gd:gd_defaults" ] + configs += [ + "//bt/system/gd:gd_defaults", + "//bt/system/log:log_defaults", + ] deps = [ "//bt/system/gd:gd_default_deps" ] if (target_os == "chromeos") { diff --git a/system/gd/rust/common/BUILD.gn b/system/gd/rust/common/BUILD.gn index 9a6e8ca5ac..dd1e7c33c0 100644 --- a/system/gd/rust/common/BUILD.gn +++ b/system/gd/rust/common/BUILD.gn @@ -22,7 +22,10 @@ static_library("libbt_keystore_cc") { ":libbt_common_bridge_code" ] - configs += ["//bt/system/gd:gd_defaults"] + configs += [ + "//bt/system/gd:gd_defaults", + "//bt/system/log:log_defaults", + ] } config("rust_common_config") { @@ -38,7 +41,10 @@ cxxbridge_header("libbt_common_bridge_header") { cxxbridge_cc("libbt_common_bridge_code") { sources = [ "src/bridge.rs" ] deps = [ ":libbt_common_bridge_header" ] - configs = [ "//bt/system/gd:gd_defaults" ] + configs = [ + "//bt/system/gd:gd_defaults", + "//bt/system/log:log_defaults", + ] } cxxbridge_libheader("cxxlibheader") { diff --git a/system/gd/rust/linux/client/src/callbacks.rs b/system/gd/rust/linux/client/src/callbacks.rs index ca73daa188..749aba4302 100644 --- a/system/gd/rust/linux/client/src/callbacks.rs +++ b/system/gd/rust/linux/client/src/callbacks.rs @@ -1,12 +1,12 @@ use crate::command_handler::SocketSchedule; use crate::dbus_iface::{ export_admin_policy_callback_dbus_intf, export_advertising_set_callback_dbus_intf, - export_bluetooth_callback_dbus_intf, export_bluetooth_connection_callback_dbus_intf, - export_bluetooth_gatt_callback_dbus_intf, export_bluetooth_manager_callback_dbus_intf, - export_bluetooth_media_callback_dbus_intf, export_bluetooth_telephony_callback_dbus_intf, - export_gatt_server_callback_dbus_intf, export_qa_callback_dbus_intf, - export_scanner_callback_dbus_intf, export_socket_callback_dbus_intf, - export_suspend_callback_dbus_intf, + export_battery_manager_callback_dbus_intf, export_bluetooth_callback_dbus_intf, + export_bluetooth_connection_callback_dbus_intf, export_bluetooth_gatt_callback_dbus_intf, + export_bluetooth_manager_callback_dbus_intf, export_bluetooth_media_callback_dbus_intf, + export_bluetooth_telephony_callback_dbus_intf, export_gatt_server_callback_dbus_intf, + export_qa_callback_dbus_intf, export_scanner_callback_dbus_intf, + export_socket_callback_dbus_intf, export_suspend_callback_dbus_intf, }; use crate::ClientContext; use crate::{console_red, console_yellow, print_error, print_info}; @@ -14,6 +14,7 @@ use bt_topshim::btif::{BtBondState, BtPropertyType, BtSspVariant, BtStatus, Uuid use bt_topshim::profiles::gatt::{AdvertisingStatus, GattStatus, LePhy}; use bt_topshim::profiles::hfp::HfpCodecId; use bt_topshim::profiles::sdp::BtSdpRecord; +use btstack::battery_manager::{BatterySet, IBatteryManagerCallback}; use btstack::bluetooth::{ BluetoothDevice, IBluetooth, IBluetoothCallback, IBluetoothConnectionCallback, }; @@ -1468,3 +1469,63 @@ impl RPCProxy for TelephonyCallback { cr.lock().unwrap().insert(self.get_object_id(), &[iface], Arc::new(Mutex::new(self))); } } + +pub(crate) struct BatteryManagerCallback { + objpath: String, + context: Arc<Mutex<ClientContext>>, + + dbus_connection: Arc<SyncConnection>, + dbus_crossroads: Arc<Mutex<Crossroads>>, +} + +impl BatteryManagerCallback { + pub(crate) fn new( + objpath: String, + context: Arc<Mutex<ClientContext>>, + dbus_connection: Arc<SyncConnection>, + dbus_crossroads: Arc<Mutex<Crossroads>>, + ) -> Self { + Self { objpath, context, dbus_connection, dbus_crossroads } + } +} + +impl IBatteryManagerCallback for BatteryManagerCallback { + fn on_battery_info_updated(&mut self, remote_address: String, battery_set: BatterySet) { + let address = remote_address.to_uppercase(); + if self.context.lock().unwrap().battery_address_filter.contains(&address) { + if battery_set.batteries.len() == 0 { + print_info!( + "Battery info for address '{}' updated with empty battery set. \ + The batteries for this device may have been removed.", + address.clone() + ); + return; + } + print_info!( + "Battery data for '{}' from source '{}' and uuid '{}' changed to:", + address.clone(), + battery_set.source_uuid.clone(), + battery_set.source_info.clone() + ); + for battery in battery_set.batteries { + print_info!(" {}%, variant: '{}'", battery.percentage, battery.variant); + } + } + } +} + +impl RPCProxy for BatteryManagerCallback { + fn get_object_id(&self) -> String { + self.objpath.clone() + } + + fn export_for_rpc(self: Box<Self>) { + let cr = self.dbus_crossroads.clone(); + let iface = export_battery_manager_callback_dbus_intf( + self.dbus_connection.clone(), + &mut cr.lock().unwrap(), + Arc::new(Mutex::new(DisconnectWatcher::new())), + ); + cr.lock().unwrap().insert(self.get_object_id(), &[iface], Arc::new(Mutex::new(self))); + } +} diff --git a/system/gd/rust/linux/client/src/command_handler.rs b/system/gd/rust/linux/client/src/command_handler.rs index 262ee4a604..c2ff72d916 100644 --- a/system/gd/rust/linux/client/src/command_handler.rs +++ b/system/gd/rust/linux/client/src/command_handler.rs @@ -13,6 +13,7 @@ use bt_topshim::btif::{BtConnectionState, BtDiscMode, BtStatus, BtTransport, INV use bt_topshim::profiles::hid_host::BthhReportType; use bt_topshim::profiles::sdp::{BtSdpMpsRecord, BtSdpRecord}; use bt_topshim::profiles::{gatt::LePhy, ProfileConnectionState}; +use btstack::battery_manager::IBatteryManager; use btstack::bluetooth::{BluetoothDevice, IBluetooth}; use btstack::bluetooth_gatt::{GattWriteType, IBluetoothGatt}; use btstack::bluetooth_media::{IBluetoothMedia, IBluetoothTelephony}; @@ -139,6 +140,24 @@ fn build_commands() -> HashMap<String, CommandOption> { }, ); command_options.insert( + String::from("battery"), + CommandOption { + rules: vec![ + String::from("battery status <address>"), + String::from("battery track <address>"), + String::from("battery untrack <address>"), + ], + description: String::from( + " + status: Current battery status of a given device.\n + track: Track a given device to monitor battery updates.\n + untrack: Stop tracking a device for battery updates. + ", + ), + function_pointer: CommandHandler::cmd_battery, + }, + ); + command_options.insert( String::from("bond"), CommandOption { rules: vec![String::from("bond <add|remove|cancel> <address>")], @@ -641,6 +660,79 @@ impl CommandHandler { Ok(()) } + fn cmd_battery(&mut self, args: &Vec<String>) -> CommandResult { + if !self.lock_context().adapter_ready { + return Err(self.adapter_not_ready()); + } + + let command = get_arg(args, 0)?; + let address = get_arg(args, 1)?.to_uppercase(); + + match &command[..] { + "status" => { + match self + .lock_context() + .battery_manager_dbus + .as_ref() + .unwrap() + .get_battery_information(address.clone()) + { + None => println!( + "Battery status for device {} could not be fetched", + address.clone() + ), + Some(set) => { + if set.batteries.len() == 0 { + println!("Battery set for device {} is empty", set.address.clone()); + return Ok(()); + } + + println!( + "Battery data for '{}' from source '{}' and uuid '{}':", + set.address.clone(), + set.source_uuid.clone(), + set.source_info.clone() + ); + for battery in set.batteries { + println!(" {}%, variant: '{}'", battery.percentage, battery.variant); + } + } + } + } + "track" => { + if self.lock_context().battery_address_filter.contains(&address) { + println!("Already tracking {}", address.clone()); + return Ok(()); + } + self.lock_context().battery_address_filter.insert(address.clone()); + + println!("Currently tracking:"); + for addr in self.lock_context().battery_address_filter.iter() { + println!("{}", addr); + } + } + "untrack" => { + if !self.lock_context().battery_address_filter.remove(&address) { + println!("Not tracking {}", address.clone()); + return Ok(()); + } + println!("Stopped tracking {}", address.clone()); + + if self.lock_context().battery_address_filter.len() == 0 { + println!("No longer tracking any addresses for battery status updates"); + return Ok(()); + } + + println!("Currently tracking:"); + for addr in self.lock_context().battery_address_filter.iter() { + println!("{}", addr); + } + } + _ => return Err(CommandError::InvalidArgs), + } + Ok(()) + } + fn cmd_bond(&mut self, args: &Vec<String>) -> CommandResult { if !self.lock_context().adapter_ready { return Err(self.adapter_not_ready()); diff --git a/system/gd/rust/linux/client/src/dbus_iface.rs b/system/gd/rust/linux/client/src/dbus_iface.rs index ebee9c011c..96ee587f61 100644 --- a/system/gd/rust/linux/client/src/dbus_iface.rs +++ b/system/gd/rust/linux/client/src/dbus_iface.rs @@ -20,6 +20,7 @@ use bt_topshim::profiles::sdp::{ use bt_topshim::profiles::socket::SocketType; use bt_topshim::profiles::ProfileConnectionState; +use btstack::battery_manager::{Battery, BatterySet, IBatteryManager, IBatteryManagerCallback}; use btstack::bluetooth::{ BluetoothDevice, IBluetooth, IBluetoothCallback, IBluetoothConnectionCallback, IBluetoothQALegacy, @@ -2734,3 +2735,80 @@ impl IBluetoothMediaCallback for IBluetoothMediaCallbackDBus { ) { } } + +pub(crate) struct BatteryManagerDBusRPC { + client_proxy: ClientDBusProxy, +} + +pub(crate) struct BatteryManagerDBus { + client_proxy: ClientDBusProxy, + pub rpc: BatteryManagerDBusRPC, +} + +impl BatteryManagerDBus { + fn make_client_proxy(conn: Arc<SyncConnection>, index: i32) -> ClientDBusProxy { + ClientDBusProxy::new( + conn.clone(), + String::from("org.chromium.bluetooth"), + make_object_path(index, "battery_manager"), + String::from("org.chromium.bluetooth.BatteryManager"), + ) + } + + pub(crate) fn new(conn: Arc<SyncConnection>, index: i32) -> BatteryManagerDBus { + BatteryManagerDBus { + client_proxy: Self::make_client_proxy(conn.clone(), index), + rpc: BatteryManagerDBusRPC { + client_proxy: Self::make_client_proxy(conn.clone(), index), + }, + } + } +} + +#[generate_dbus_interface_client(BatteryManagerDBusRPC)] +impl IBatteryManager for BatteryManagerDBus { + #[dbus_method("RegisterBatteryCallback")] + fn register_battery_callback( + &mut self, + battery_manager_callback: Box<dyn IBatteryManagerCallback + Send>, + ) -> u32 { + dbus_generated!() + } + + #[dbus_method("UnregisterBatteryCallback")] + fn unregister_battery_callback(&mut self, callback_id: u32) -> bool { + dbus_generated!() + } + + #[dbus_method("GetBatteryInformation")] + fn get_battery_information(&self, remote_address: String) -> Option<BatterySet> { + dbus_generated!() + } +} + +#[dbus_propmap(BatterySet)] +pub struct BatterySetDBus { + address: String, + source_uuid: String, + source_info: String, + batteries: Vec<Battery>, +} + +#[dbus_propmap(Battery)] +pub struct BatteryDBus { + percentage: u32, + variant: String, +} + +struct IBatteryManagerCallbackDBus {} + +impl RPCProxy for IBatteryManagerCallbackDBus {} + +#[generate_dbus_exporter( + export_battery_manager_callback_dbus_intf, + "org.chromium.bluetooth.BatteryManagerCallback" +)] +impl IBatteryManagerCallback for IBatteryManagerCallbackDBus { + #[dbus_method("OnBatteryInfoUpdated")] + fn on_battery_info_updated(&mut self, remote_address: String, battery_set: BatterySet) {} +} diff --git a/system/gd/rust/linux/client/src/main.rs b/system/gd/rust/linux/client/src/main.rs index 5793cc16f1..c1847caf41 100644 --- a/system/gd/rust/linux/client/src/main.rs +++ b/system/gd/rust/linux/client/src/main.rs @@ -14,15 +14,15 @@ use tokio::time::{sleep, timeout}; use crate::bt_adv::AdvSet; use crate::bt_gatt::GattClientContext; use crate::callbacks::{ - AdminCallback, AdvertisingSetCallback, BtCallback, BtConnectionCallback, BtManagerCallback, - BtSocketManagerCallback, MediaCallback, QACallback, ScannerCallback, SuspendCallback, - TelephonyCallback, + AdminCallback, AdvertisingSetCallback, BatteryManagerCallback, BtCallback, + BtConnectionCallback, BtManagerCallback, BtSocketManagerCallback, MediaCallback, QACallback, + ScannerCallback, SuspendCallback, TelephonyCallback, }; use crate::command_handler::{CommandHandler, SocketSchedule}; use crate::dbus_iface::{ - BluetoothAdminDBus, BluetoothDBus, BluetoothGattDBus, BluetoothManagerDBus, BluetoothMediaDBus, - BluetoothQADBus, BluetoothQALegacyDBus, BluetoothSocketManagerDBus, BluetoothTelephonyDBus, - SuspendDBus, + BatteryManagerDBus, BluetoothAdminDBus, BluetoothDBus, BluetoothGattDBus, BluetoothManagerDBus, + BluetoothMediaDBus, BluetoothQADBus, BluetoothQALegacyDBus, BluetoothSocketManagerDBus, + BluetoothTelephonyDBus, SuspendDBus, }; use crate::editor::AsyncEditor; use bt_topshim::topstack; @@ -102,6 +102,9 @@ pub(crate) struct ClientContext { /// Proxy for Media interface. pub(crate) media_dbus: Option<BluetoothMediaDBus>, + /// Proxy for battery manager interface. + pub(crate) battery_manager_dbus: Option<BatteryManagerDBus>, + /// Channel to send actions to take in the foreground fg: mpsc::Sender<ForegroundActions>, @@ -146,6 +149,9 @@ pub(crate) struct ClientContext { /// The set of client commands that need to wait for callbacks. client_commands_with_callbacks: Vec<String>, + + /// A set of addresses whose battery changes are being tracked. + pub(crate) battery_address_filter: HashSet<String>, } impl ClientContext { @@ -180,6 +186,7 @@ impl ClientContext { socket_manager_dbus: None, telephony_dbus: None, media_dbus: None, + battery_manager_dbus: None, fg: tx, dbus_connection, dbus_crossroads, @@ -195,6 +202,7 @@ impl ClientContext { socket_test_schedule: None, mps_sdp_handle: None, client_commands_with_callbacks, + battery_address_filter: HashSet::new(), } } @@ -243,6 +251,8 @@ impl ClientContext { self.media_dbus = Some(BluetoothMediaDBus::new(conn.clone(), idx)); + self.battery_manager_dbus = Some(BatteryManagerDBus::new(conn.clone(), idx)); + // Trigger callback registration in the foreground let fg = self.fg.clone(); tokio::spawn(async move { @@ -548,6 +558,8 @@ async fn handle_client_command( "/org/chromium/bluetooth/client/{}/bluetooth_telephony_callback", adapter ); + let battery_cb_objpath: String = + format!("/org/chromium/bluetooth/client/{}/battery_manager_callback", adapter); let dbus_connection = context.lock().unwrap().dbus_connection.clone(); let dbus_crossroads = context.lock().unwrap().dbus_crossroads.clone(); @@ -711,6 +723,22 @@ async fn handle_client_command( .await .expect("D-Bus error on IBluetoothMedia::RegisterTelephonyCallback"); + context + .lock() + .unwrap() + .battery_manager_dbus + .as_mut() + .unwrap() + .rpc + .register_battery_callback(Box::new(BatteryManagerCallback::new( + battery_cb_objpath, + context.clone(), + dbus_connection.clone(), + dbus_crossroads.clone(), + ))) + .await + .expect("D-Bus error on IBatteryManagerDBus::RegisterBatteryCallback"); + context.lock().unwrap().adapter_ready = true; let adapter_address = context.lock().unwrap().update_adapter_address(); context.lock().unwrap().update_bonded_devices(); diff --git a/system/gd/rust/linux/service/build.rs b/system/gd/rust/linux/service/build.rs index 1585a230be..8223fd341c 100644 --- a/system/gd/rust/linux/service/build.rs +++ b/system/gd/rust/linux/service/build.rs @@ -26,6 +26,7 @@ fn main() { Config::new().probe("libmodp_b64").unwrap(); Config::new().probe("tinyxml2").unwrap(); Config::new().probe("lc3").unwrap(); + Config::new().probe("fmt").unwrap(); // Include ChromeOS-specific dependencies. if option_env!("TARGET_OS_VARIANT").unwrap_or("None").to_string() == "chromeos" { diff --git a/system/gd/rust/linux/stack/build.rs b/system/gd/rust/linux/stack/build.rs index 1ecdfad917..9baf3e2211 100644 --- a/system/gd/rust/linux/stack/build.rs +++ b/system/gd/rust/linux/stack/build.rs @@ -12,6 +12,7 @@ fn main() { println!("cargo:rustc-link-lib=dylib=protobuf"); println!("cargo:rustc-link-lib=dylib=resolv"); println!("cargo:rustc-link-lib=dylib=lc3"); + println!("cargo:rustc-link-lib=dylib=fmt"); println!("cargo:rerun-if-changed=build.rs"); } diff --git a/system/gd/rust/linux/stack/src/bluetooth_gatt.rs b/system/gd/rust/linux/stack/src/bluetooth_gatt.rs index c5d59d08b9..708bdb8bd6 100644 --- a/system/gd/rust/linux/stack/src/bluetooth_gatt.rs +++ b/system/gd/rust/linux/stack/src/bluetooth_gatt.rs @@ -1163,7 +1163,7 @@ impl Default for GattWriteType { } } -#[derive(Debug, FromPrimitive, ToPrimitive, Clone)] +#[derive(Debug, FromPrimitive, ToPrimitive, Clone, PartialEq)] #[repr(u32)] /// Scan type configuration. pub enum ScanType { @@ -1173,7 +1173,7 @@ pub enum ScanType { impl Default for ScanType { fn default() -> Self { - ScanType::Active + ScanType::Passive } } @@ -1189,20 +1189,26 @@ pub struct ScanSettings { } impl ScanSettings { - fn extract_scan_parameters(self) -> Option<(u16, u16)> { - let interval = u16::try_from(self.interval); - if interval.is_err() { - println!("Invalid scan interval {}", self.interval); - return None; - } - - let window = u16::try_from(self.window); - if window.is_err() { - println!("Invalid scan window {}", self.window); - return None; - } - - return Some((interval.unwrap(), window.unwrap())); + fn extract_scan_parameters(&self) -> Option<(u8, u16, u16)> { + let scan_type = match self.scan_type { + ScanType::Passive => 0x00, + ScanType::Active => 0x01, + }; + let interval = match u16::try_from(self.interval) { + Ok(i) => i, + Err(e) => { + println!("Invalid scan interval {}: {}", self.interval, e); + return None; + } + }; + let window = match u16::try_from(self.window) { + Ok(w) => w, + Err(e) => { + println!("Invalid scan window {}: {}", self.window, e); + return None; + } + }; + return Some((scan_type, interval, window)); } } @@ -1344,31 +1350,52 @@ impl GattAsyncIntf { .await } - /// Updates the topshim's scan state depending on the states of registered scanners. Scan is - /// enabled if there is at least 1 active registered scanner. + /// Updates the scan state depending on the states of registered scanners: + /// 1. Scan is started if there is at least 1 enabled scanner. + /// 2. Always toggle the scan off and on so that we reset the scan parameters based on whether + /// we have enabled scanners using hardware filtering. + /// TODO(b/266752123): We can do more bookkeeping to optimize when we really need to + /// toggle. Also improve toggling API into 1 operation that guarantees correct ordering. + /// 3. If there is an enabled ScanType::Active scanner, prefer its scan settings. Otherwise, + /// adopt the settings from any of the enabled scanners. We shouldn't just use the settings + /// from |scanner_id| because it may refer to a disabled scan. /// /// Note: this does not need to be async, but declared as async for consistency in this struct. /// May be converted into real async in the future if btif supports it. - async fn update_scan(&mut self, scanner_id: u8, scan_settings: Option<ScanSettings>) { - if self.scanners.lock().unwrap().values().find(|scanner| scanner.is_active).is_some() { - // Toggle the scan off and on so that we reset the scan parameters based on whether - // we have active scanners using hardware filtering. - // TODO(b/266752123): We can do more bookkeeping to optimize when we really need to - // toggle. Also improve toggling API into 1 operation that guarantees correct ordering. - self.gatt.as_ref().unwrap().lock().unwrap().scanner.stop_scan(); - if let Some(settings) = scan_settings { - if let Some((scan_interval, scan_window)) = settings.extract_scan_parameters() { - self.gatt.as_ref().unwrap().lock().unwrap().scanner.set_scan_parameters( - scanner_id, - scan_interval, - scan_window, - ); + async fn update_scan(&mut self, scanner_id: u8) { + let mut has_enabled_scan = false; + let mut enabled_scan_param = None; + let mut enabled_active_scan_param = None; + for scanner in self.scanners.lock().unwrap().values() { + if !scanner.is_enabled { + continue; + } + has_enabled_scan = true; + if let Some(ss) = &scanner.scan_settings { + enabled_scan_param = ss.extract_scan_parameters(); + if ss.scan_type == ScanType::Active { + enabled_active_scan_param = ss.extract_scan_parameters(); + break; } } - self.gatt.as_ref().unwrap().lock().unwrap().scanner.start_scan(); - } else { - self.gatt.as_ref().unwrap().lock().unwrap().scanner.stop_scan(); } + + self.gatt.as_ref().unwrap().lock().unwrap().scanner.stop_scan(); + if !has_enabled_scan { + return; + } + + if let Some((scan_type, scan_interval, scan_window)) = + enabled_active_scan_param.or(enabled_scan_param) + { + self.gatt.as_ref().unwrap().lock().unwrap().scanner.set_scan_parameters( + scanner_id, + scan_type, + scan_interval, + scan_window, + ); + } + self.gatt.as_ref().unwrap().lock().unwrap().scanner.start_scan(); } } @@ -1593,7 +1620,7 @@ impl BluetoothGatt { .unwrap() .iter() .filter_map(|(_uuid, scanner)| { - if let (true, Some(scanner_id)) = (scanner.is_active, scanner.scanner_id) { + if let (true, Some(scanner_id)) = (scanner.is_enabled, scanner.scanner_id) { Some(scanner_id) } else { None @@ -1663,7 +1690,7 @@ impl BluetoothGatt { if let Some(scanner) = Self::find_scanner_by_id(&mut scanners_lock, scanner_id) { if scanner.is_suspended { scanner.is_suspended = false; - scanner.is_active = true; + scanner.is_enabled = true; // When a scanner resumes from a suspended state, the // scanner.filter has already had the filter data. scanner.filter.clone() @@ -1723,14 +1750,14 @@ impl BluetoothGatt { log::debug!("Added adv monitor handle = {}", monitor_handle); } - let has_active_unfiltered_scanner = scanners + let has_enabled_unfiltered_scanner = scanners .lock() .unwrap() .iter() - .any(|(_uuid, scanner)| scanner.is_active && scanner.filter.is_none()); + .any(|(_uuid, scanner)| scanner.is_enabled && scanner.filter.is_none()); if !gatt_async - .msft_adv_monitor_enable(!has_active_unfiltered_scanner) + .msft_adv_monitor_enable(!has_enabled_unfiltered_scanner) .await .map_or(false, |status| status == 0) { @@ -1742,10 +1769,7 @@ impl BluetoothGatt { } } - let scan_settings = Self::find_scanner_by_id(&mut scanners.lock().unwrap(), scanner_id) - .map_or(None, |s| s.scan_settings.clone()); - - gatt_async.update_scan(scanner_id, scan_settings).await; + gatt_async.update_scan(scanner_id).await; }); BtStatus::Success @@ -1909,8 +1933,8 @@ struct ScannerInfo { callback_id: u32, // If the scanner is registered successfully, this contains the scanner id, otherwise None. scanner_id: Option<u8>, - // If one of scanners is active, we scan. - is_active: bool, + // If one of scanners is enabled, we scan. + is_enabled: bool, // Scan filter. filter: Option<ScanFilter>, // Adv monitor handle, if exists. @@ -1926,7 +1950,7 @@ impl ScannerInfo { Self { callback_id, scanner_id: None, - is_active: false, + is_enabled: false, filter: None, monitor_handle: None, is_suspended: false, @@ -2033,7 +2057,7 @@ impl IBluetoothGatt for BluetoothGatt { let settings = settings.unwrap_or_else(|| ScanSettings { interval: sysprop::get_i32(sysprop::PropertyI32::LeInquiryScanInterval), window: sysprop::get_i32(sysprop::PropertyI32::LeInquiryScanWindow), - scan_type: ScanType::Active, + scan_type: ScanType::default(), }); // Multiplexing scanners happens at this layer. The implementations of start_scan @@ -2043,7 +2067,7 @@ impl IBluetoothGatt for BluetoothGatt { let mut scanners_lock = self.scanners.lock().unwrap(); if let Some(scanner) = Self::find_scanner_by_id(&mut scanners_lock, scanner_id) { - scanner.is_active = true; + scanner.is_enabled = true; scanner.filter = filter.clone(); scanner.scan_settings = Some(settings); } else { @@ -2070,7 +2094,7 @@ impl IBluetoothGatt for BluetoothGatt { let mut scanners_lock = self.scanners.lock().unwrap(); if let Some(scanner) = Self::find_scanner_by_id(&mut scanners_lock, scanner_id) { - scanner.is_active = false; + scanner.is_enabled = false; scanner.monitor_handle } else { log::warn!("Scanner {} not found", scanner_id); @@ -2095,14 +2119,14 @@ impl IBluetoothGatt for BluetoothGatt { let _res = gatt_async.msft_adv_monitor_remove(handle).await; } - let has_active_unfiltered_scanner = scanners + let has_enabled_unfiltered_scanner = scanners .lock() .unwrap() .iter() - .any(|(_uuid, scanner)| scanner.is_active && scanner.filter.is_none()); + .any(|(_uuid, scanner)| scanner.is_enabled && scanner.filter.is_none()); if !gatt_async - .msft_adv_monitor_enable(!has_active_unfiltered_scanner) + .msft_adv_monitor_enable(!has_enabled_unfiltered_scanner) .await .map_or(false, |status| status == 0) { @@ -2110,10 +2134,7 @@ impl IBluetoothGatt for BluetoothGatt { } } - let scan_settings = Self::find_scanner_by_id(&mut scanners.lock().unwrap(), scanner_id) - .map_or(None, |s| s.scan_settings.clone()); - - gatt_async.update_scan(scanner_id, scan_settings).await; + gatt_async.update_scan(scanner_id).await; }); BtStatus::Success diff --git a/system/gd/rust/topshim/Android.bp b/system/gd/rust/topshim/Android.bp index 5f3e6e8f79..17b5518445 100644 --- a/system/gd/rust/topshim/Android.bp +++ b/system/gd/rust/topshim/Android.bp @@ -70,7 +70,10 @@ cc_library_static { "packages/modules/Bluetooth/system/types", ], host_supported: true, - static_libs: ["libchrome"], + static_libs: [ + "libbluetooth_log", + "libchrome", + ], } gensrcs { @@ -138,6 +141,9 @@ rust_bindgen { shared_libs: [ "libc++", ], + 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. diff --git a/system/gd/rust/topshim/facade/Android.bp b/system/gd/rust/topshim/facade/Android.bp index edf3035abd..3e197f0919 100644 --- a/system/gd/rust/topshim/facade/Android.bp +++ b/system/gd/rust/topshim/facade/Android.bp @@ -48,6 +48,7 @@ rust_defaults { "libbluetooth_core_rs", "libbluetooth_crypto_toolbox", "libbluetooth_gd", // Gabeldorsche + "libbluetooth_log", "libbt-audio-asrc", "libbt-audio-hal-interface", "libbt-bta", diff --git a/system/gd/rust/topshim/facade/src/gatt_service.rs b/system/gd/rust/topshim/facade/src/gatt_service.rs index 081fb9833a..73a5bc29c8 100644 --- a/system/gd/rust/topshim/facade/src/gatt_service.rs +++ b/system/gd/rust/topshim/facade/src/gatt_service.rs @@ -364,7 +364,7 @@ impl GattService for GattServiceImpl { fn set_scan_parameters(&mut self, ctx: RpcContext<'_>, _req: Empty, sink: UnarySink<Empty>) { let scanner = &mut self.gatt.lock().unwrap().scanner; - scanner.set_scan_parameters(0, 0, 0); + scanner.set_scan_parameters(0, 0, 0, 0); ctx.spawn(async move { sink.success(Empty::default()).await.unwrap(); }) diff --git a/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.cc b/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.cc index 72b9bfcd81..e8f5019a1e 100644 --- a/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.cc +++ b/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.cc @@ -272,9 +272,11 @@ void BleScannerIntf::MsftAdvMonitorEnable(uint32_t call_id, bool enable) { enable, base::Bind(&BleScannerIntf::OnMsftAdvMonitorEnableCallback, base::Unretained(this), call_id)); } -void BleScannerIntf::SetScanParameters(uint8_t scanner_id, uint16_t scan_interval, uint16_t scan_window) { +void BleScannerIntf::SetScanParameters( + uint8_t scanner_id, uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window) { scanner_intf_->SetScanParameters( scanner_id, + scan_type, scan_interval, scan_window, base::Bind(&BleScannerIntf::OnStatusCallback, base::Unretained(this), scanner_id)); diff --git a/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.h b/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.h index 7011ae32b5..75bb38fc6e 100644 --- a/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.h +++ b/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.h @@ -117,7 +117,8 @@ class BleScannerIntf : public ScanningCallbacks { // Sets the LE scan interval and window in units of N * 0.625 msec. The result // of this action is returned via |OnStatusCallback|. - void SetScanParameters(uint8_t scanner_id, uint16_t scan_interval, uint16_t scan_window); + void SetScanParameters( + uint8_t scanner_id, uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window); // Configure the batchscan storage and get a response via |OnStatusCallback|. void BatchscanConfigStorage( diff --git a/system/gd/rust/topshim/src/profiles/gatt.rs b/system/gd/rust/topshim/src/profiles/gatt.rs index 01691a40a9..d2b0e458a5 100644 --- a/system/gd/rust/topshim/src/profiles/gatt.rs +++ b/system/gd/rust/topshim/src/profiles/gatt.rs @@ -199,6 +199,7 @@ pub mod ffi { fn SetScanParameters( self: Pin<&mut BleScannerIntf>, scanner_id: u8, + scan_type: u8, scan_interval: u16, scan_window: u16, ); @@ -1540,8 +1541,14 @@ impl BleScanner { mutcxxcall!(self, MsftAdvMonitorEnable, call_id, enable); } - pub fn set_scan_parameters(&mut self, scanner_id: u8, scan_interval: u16, scan_window: u16) { - mutcxxcall!(self, SetScanParameters, scanner_id, scan_interval, scan_window); + pub fn set_scan_parameters( + &mut self, + scanner_id: u8, + scan_type: u8, + scan_interval: u16, + scan_window: u16, + ) { + mutcxxcall!(self, SetScanParameters, scanner_id, scan_type, scan_interval, scan_window); } pub fn batchscan_config_storage( diff --git a/system/gd/security/BUILD.gn b/system/gd/security/BUILD.gn index 02e04bed55..de17a0a316 100644 --- a/system/gd/security/BUILD.gn +++ b/system/gd/security/BUILD.gn @@ -15,19 +15,28 @@ source_set("BluetoothSecurityChannelSources") { sources = [ "channel/security_manager_channel.cc" ] - configs += [ "//bt/system/gd:gd_defaults" ] + configs += [ + "//bt/system/gd:gd_defaults", + "//bt/system/log:log_defaults", + ] deps = [ "//bt/system/gd:gd_default_deps" ] } source_set("BluetoothSecurityPairingSources") { sources = [ "pairing/classic_pairing_handler.cc" ] - configs += [ "//bt/system/gd:gd_defaults" ] + configs += [ + "//bt/system/gd:gd_defaults", + "//bt/system/log:log_defaults", + ] deps = [ "//bt/system/gd:gd_default_deps" ] } source_set("BluetoothSecurityRecordSources") { sources = [ "record/security_record_storage.cc" ] - configs += [ "//bt/system/gd:gd_defaults" ] + configs += [ + "//bt/system/gd:gd_defaults", + "//bt/system/log:log_defaults", + ] deps = [ "//bt/system/gd:gd_default_deps" ] } @@ -53,5 +62,8 @@ source_set("BluetoothSecuritySources") { "//bt/system/gd:gd_default_deps", ] - configs += [ "//bt/system/gd:gd_defaults" ] + configs += [ + "//bt/system/gd:gd_defaults", + "//bt/system/log:log_defaults", + ] } diff --git a/system/gd/security/internal/security_manager_impl.cc b/system/gd/security/internal/security_manager_impl.cc index fbbf414494..fb49d894f1 100644 --- a/system/gd/security/internal/security_manager_impl.cc +++ b/system/gd/security/internal/security_manager_impl.cc @@ -27,6 +27,7 @@ #include "security/pairing_handler_le.h" #include "security/security_manager_listener.h" #include "security/ui.h" +#include "storage/config_keys.h" namespace bluetooth { namespace security { @@ -78,23 +79,29 @@ void SecurityManagerImpl::Init() { ASSERT_LOG(storage_module_ != nullptr, "Storage module must not be null!"); security_database_.LoadRecordsFromStorage(); - auto irk_prop = storage_module_->GetBin("Adapter", "LE_LOCAL_KEY_IRK"); + auto irk_prop = + storage_module_->GetBin(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK); if (!irk_prop.has_value()) { auto rand16 = bluetooth::os::GenerateRandom<16>(); std::vector<uint8_t> new_irk{rand16.begin(), rand16.end()}; - storage_module_->SetBin("Adapter", "LE_LOCAL_KEY_IRK", new_irk); - irk_prop = storage_module_->GetBin("Adapter", "LE_LOCAL_KEY_IRK"); + storage_module_->SetBin( + BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK, new_irk); + irk_prop = + storage_module_->GetBin(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK); } Address controllerAddress = controller_->GetMacAddress(); - auto address_prop = storage_module_->GetProperty("Adapter", "Address"); + auto address_prop = + storage_module_->GetProperty(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_ADDRESS); if (!address_prop || address_prop.value() != controllerAddress.ToString()) { - storage_module_->SetProperty("Adapter", "Address", controllerAddress.ToString()); + storage_module_->SetProperty( + BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_ADDRESS, controllerAddress.ToString()); } local_identity_address_ = hci::AddressWithType(controllerAddress, hci::AddressType::PUBLIC_DEVICE_ADDRESS); - irk_prop = storage_module_->GetBin("Adapter", "LE_LOCAL_KEY_IRK"); + irk_prop = + storage_module_->GetBin(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK); ASSERT_LOG(irk_prop.has_value(), "Irk not found in storage"); ASSERT_LOG(irk_prop->size() == 16, "Irk corrupted in storage"); std::copy(irk_prop->begin(), irk_prop->end(), local_identity_resolving_key_.data()); diff --git a/system/gd/storage/BUILD.gn b/system/gd/storage/BUILD.gn index 167293caa4..2c9d4bd109 100644 --- a/system/gd/storage/BUILD.gn +++ b/system/gd/storage/BUILD.gn @@ -26,6 +26,9 @@ source_set("BluetoothStorageSources") { "storage_module.cc", ] - configs += [ "//bt/system/gd:gd_defaults" ] + configs += [ + "//bt/system/gd:gd_defaults", + "//bt/system/log:log_defaults", + ] deps = [ "//bt/system/gd:gd_default_deps" ] } diff --git a/system/gd/storage/config_cache_test.cc b/system/gd/storage/config_cache_test.cc index 29773dbe44..d4fde9144a 100644 --- a/system/gd/storage/config_cache_test.cc +++ b/system/gd/storage/config_cache_test.cc @@ -22,6 +22,7 @@ #include <cstdio> #include "hci/enum_helper.h" +#include "storage/config_keys.h" #include "storage/device.h" namespace testing { @@ -61,42 +62,42 @@ TEST(ConfigCacheTest, empty_values_test) { TEST(ConfigCacheTest, insert_boundary_device_with_linkkey_test) { ConfigCache config(2, Device::kLinkKeyProperties); config.SetProperty("A", "B", "C"); - config.SetProperty("CC:DD:EE:FF:00:10", "Name", "Hello"); - config.SetProperty("CC:DD:EE:FF:00:09", "Name", "Hello 2"); - config.SetProperty("CC:DD:EE:FF:00:11", "LinkKey", "AABBAABBCCDDEE"); - ASSERT_TRUE(config.GetProperty("CC:DD:EE:FF:00:10", "Name")); + config.SetProperty("CC:DD:EE:FF:00:10", BTIF_STORAGE_KEY_NAME, "Hello"); + config.SetProperty("CC:DD:EE:FF:00:09", BTIF_STORAGE_KEY_NAME, "Hello 2"); + config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY, "AABBAABBCCDDEE"); + ASSERT_TRUE(config.GetProperty("CC:DD:EE:FF:00:10", BTIF_STORAGE_KEY_NAME)); } TEST(ConfigCacheTest, comparison_test) { ConfigCache config_1(2, Device::kLinkKeyProperties); config_1.SetProperty("A", "B", "C"); - config_1.SetProperty("CC:DD:EE:FF:00:10", "Name", "Hello"); - config_1.SetProperty("CC:DD:EE:FF:00:09", "Name", "Hello 2"); - config_1.SetProperty("CC:DD:EE:FF:00:11", "LinkKey", "AABBAABBCCDDEE"); + config_1.SetProperty("CC:DD:EE:FF:00:10", BTIF_STORAGE_KEY_NAME, "Hello"); + config_1.SetProperty("CC:DD:EE:FF:00:09", BTIF_STORAGE_KEY_NAME, "Hello 2"); + config_1.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY, "AABBAABBCCDDEE"); ConfigCache config_2(2, Device::kLinkKeyProperties); config_2.SetProperty("A", "B", "C"); - config_2.SetProperty("CC:DD:EE:FF:00:10", "Name", "Hello"); - config_2.SetProperty("CC:DD:EE:FF:00:09", "Name", "Hello 2"); - config_2.SetProperty("CC:DD:EE:FF:00:11", "LinkKey", "AABBAABBCCDDEE"); + config_2.SetProperty("CC:DD:EE:FF:00:10", BTIF_STORAGE_KEY_NAME, "Hello"); + config_2.SetProperty("CC:DD:EE:FF:00:09", BTIF_STORAGE_KEY_NAME, "Hello 2"); + config_2.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY, "AABBAABBCCDDEE"); ASSERT_EQ(config_1, config_2); // Config with different temp device order should not be equal - ASSERT_TRUE(config_2.GetProperty("CC:DD:EE:FF:00:10", "Name")); + ASSERT_TRUE(config_2.GetProperty("CC:DD:EE:FF:00:10", BTIF_STORAGE_KEY_NAME)); ASSERT_NE(config_1, config_2); - ASSERT_TRUE(config_1.GetProperty("CC:DD:EE:FF:00:10", "Name")); + ASSERT_TRUE(config_1.GetProperty("CC:DD:EE:FF:00:10", BTIF_STORAGE_KEY_NAME)); ASSERT_EQ(config_1, config_2); // Config with different persistent device order should not be equal - config_1.SetProperty("CC:DD:EE:FF:00:12", "LinkKey", "AABBAABBCCDDEE"); + config_1.SetProperty("CC:DD:EE:FF:00:12", BTIF_STORAGE_KEY_LINK_KEY, "AABBAABBCCDDEE"); config_2.RemoveSection("CC:DD:EE:FF:00:11"); - config_2.SetProperty("CC:DD:EE:FF:00:12", "LinkKey", "AABBAABBCCDDEE"); - config_2.SetProperty("CC:DD:EE:FF:00:11", "LinkKey", "AABBAABBCCDDEE"); + config_2.SetProperty("CC:DD:EE:FF:00:12", BTIF_STORAGE_KEY_LINK_KEY, "AABBAABBCCDDEE"); + config_2.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY, "AABBAABBCCDDEE"); ASSERT_NE(config_1, config_2); // Config with different capacity should not be equal ConfigCache config_3(3, Device::kLinkKeyProperties); config_3.SetProperty("A", "B", "C"); - config_3.SetProperty("CC:DD:EE:FF:00:10", "Name", "Hello"); - config_3.SetProperty("CC:DD:EE:FF:00:09", "Name", "Hello 2"); - config_3.SetProperty("CC:DD:EE:FF:00:11", "LinkKey", "AABBAABBCCDDEE"); - config_3.SetProperty("CC:DD:EE:FF:00:12", "LinkKey", "AABBAABBCCDDEE"); + config_3.SetProperty("CC:DD:EE:FF:00:10", BTIF_STORAGE_KEY_NAME, "Hello"); + config_3.SetProperty("CC:DD:EE:FF:00:09", BTIF_STORAGE_KEY_NAME, "Hello 2"); + config_3.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY, "AABBAABBCCDDEE"); + config_3.SetProperty("CC:DD:EE:FF:00:12", BTIF_STORAGE_KEY_LINK_KEY, "AABBAABBCCDDEE"); ASSERT_NE(config_1, config_3); // Empty config should not be equal to non-empty ones ConfigCache config_4(2, Device::kLinkKeyProperties); @@ -208,31 +209,35 @@ TEST(ConfigCacheTest, get_persistent_devices_test) { config.SetProperty("A", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "C", "D"); - config.SetProperty("CC:DD:EE:FF:00:11", "LinkKey", "AABBAABBCCDDEE"); - ASSERT_TRUE(config.HasProperty("CC:DD:EE:FF:00:11", "LinkKey")); + config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY, "AABBAABBCCDDEE"); + ASSERT_TRUE(config.HasProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY)); ASSERT_THAT(config.GetPersistentSections(), ElementsAre("CC:DD:EE:FF:00:11")); - config.SetProperty("AA:BB:CC:DD:EE:FF", "LinkKey", "DEERDEERDEER"); + config.SetProperty("AA:BB:CC:DD:EE:FF", BTIF_STORAGE_KEY_LINK_KEY, "DEERDEERDEER"); ASSERT_THAT(config.GetPersistentSections(), ElementsAre("CC:DD:EE:FF:00:11", "AA:BB:CC:DD:EE:FF")); - ASSERT_TRUE(config.RemoveProperty("CC:DD:EE:FF:00:11", "LinkKey")); + ASSERT_TRUE(config.RemoveProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY)); ASSERT_THAT(config.GetPersistentSections(), ElementsAre("AA:BB:CC:DD:EE:FF")); } TEST(ConfigCacheTest, appoaching_temporary_config_limit_test) { ConfigCache config(2, Device::kLinkKeyProperties); for (int i = 0; i < 10; ++i) { - config.SetProperty(GetTestAddress(i), "Name", "Hello" + std::to_string(i)); + config.SetProperty(GetTestAddress(i), BTIF_STORAGE_KEY_NAME, "Hello" + std::to_string(i)); if (i % 2 == 0) { - config.SetProperty(GetTestAddress(i), "LinkKey", "Key" + std::to_string(i)); + config.SetProperty(GetTestAddress(i), BTIF_STORAGE_KEY_LINK_KEY, "Key" + std::to_string(i)); } } for (int i = 0; i < 10; ++i) { if (i % 2 == 0) { ASSERT_TRUE(config.HasSection(GetTestAddress(i))); - ASSERT_TRUE(config.HasProperty(GetTestAddress(i), "LinkKey")); - ASSERT_THAT(config.GetProperty(GetTestAddress(i), "Name"), Optional(StrEq("Hello" + std::to_string(i)))); + ASSERT_TRUE(config.HasProperty(GetTestAddress(i), BTIF_STORAGE_KEY_LINK_KEY)); + ASSERT_THAT( + config.GetProperty(GetTestAddress(i), BTIF_STORAGE_KEY_NAME), + Optional(StrEq("Hello" + std::to_string(i)))); } else if (i >= 7) { ASSERT_TRUE(config.HasSection(GetTestAddress(i))); - ASSERT_THAT(config.GetProperty(GetTestAddress(i), "Name"), Optional(StrEq("Hello" + std::to_string(i)))); + ASSERT_THAT( + config.GetProperty(GetTestAddress(i), BTIF_STORAGE_KEY_NAME), + Optional(StrEq("Hello" + std::to_string(i)))); } else { ASSERT_FALSE(config.HasSection(GetTestAddress(i))); } @@ -248,7 +253,7 @@ TEST(ConfigCacheTest, remove_section_with_property_test) { config.SetProperty("AA:BB:CC:DD:EE:FF", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "C", "D"); config.SetProperty("CC:DD:EE:FF:00:11", "B", "AABBAABBCCDDEE"); - config.SetProperty("CC:DD:EE:FF:00:11", "LinkKey", "AABBAABBCCDDEE"); + config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY, "AABBAABBCCDDEE"); config.RemoveSectionWithProperty("B"); ASSERT_FALSE(config.HasSection("A")); ASSERT_FALSE(config.HasSection("AA:BB:CC:DD:EE:FF")); @@ -267,9 +272,9 @@ TEST(ConfigCacheTest, persistent_config_changed_callback_test) { ASSERT_EQ(num_change, 1); config.SetProperty("CC:DD:EE:FF:00:11", "B", "AABBAABBCCDDEE"); ASSERT_EQ(num_change, 1); - config.SetProperty("CC:DD:EE:FF:00:11", "LinkKey", "AABBAABBCCDDEE"); + config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY, "AABBAABBCCDDEE"); ASSERT_EQ(num_change, 2); - config.RemoveProperty("CC:DD:EE:FF:00:11", "LinkKey"); + config.RemoveProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY); ASSERT_EQ(num_change, 3); config.RemoveSectionWithProperty("B"); ASSERT_EQ(num_change, 4); @@ -285,7 +290,7 @@ TEST(ConfigCacheTest, fix_device_type_inconsistency_missing_devtype_no_keys_test ASSERT_TRUE(hadInconsistencies); ASSERT_THAT( - config.GetProperty("AA:BB:CC:DD:EE:FF", "DevType"), + config.GetProperty("AA:BB:CC:DD:EE:FF", BTIF_STORAGE_KEY_DEV_TYPE), Optional(StrEq(std::to_string(bluetooth::hci::DeviceType::BR_EDR)))); } @@ -295,11 +300,17 @@ TEST(ConfigCacheTest, fix_device_type_inconsistency_consistent_devtype_test) { config.SetProperty("A", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "C", "D"); - config.SetProperty("AA:BB:CC:DD:EE:FF", "DevType", std::to_string(bluetooth::hci::DeviceType::BR_EDR)); + config.SetProperty( + "AA:BB:CC:DD:EE:FF", + BTIF_STORAGE_KEY_DEV_TYPE, + std::to_string(bluetooth::hci::DeviceType::BR_EDR)); config.SetProperty("CC:DD:EE:FF:00:11", "B", "AABBAABBCCDDEE"); - config.SetProperty("CC:DD:EE:FF:00:11", "DevType", std::to_string(bluetooth::hci::DeviceType::BR_EDR)); - config.SetProperty("CC:DD:EE:FF:00:11", "LinkKey", "AABBAABBCCDDEE"); + config.SetProperty( + "CC:DD:EE:FF:00:11", + BTIF_STORAGE_KEY_DEV_TYPE, + std::to_string(bluetooth::hci::DeviceType::BR_EDR)); + config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY, "AABBAABBCCDDEE"); // act auto hadInconsistencies = config.FixDeviceTypeInconsistencies(); @@ -307,7 +318,7 @@ TEST(ConfigCacheTest, fix_device_type_inconsistency_consistent_devtype_test) { // assert ASSERT_FALSE(hadInconsistencies); ASSERT_THAT( - config.GetProperty("CC:DD:EE:FF:00:11", "DevType"), + config.GetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_DEV_TYPE), Optional(StrEq(std::to_string(bluetooth::hci::DeviceType::BR_EDR)))); } @@ -317,12 +328,18 @@ TEST(ConfigCacheTest, fix_device_type_inconsistency_devtype_should_be_dual_test) config.SetProperty("A", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "C", "D"); - config.SetProperty("AA:BB:CC:DD:EE:FF", "DevType", std::to_string(bluetooth::hci::DeviceType::BR_EDR)); + config.SetProperty( + "AA:BB:CC:DD:EE:FF", + BTIF_STORAGE_KEY_DEV_TYPE, + std::to_string(bluetooth::hci::DeviceType::BR_EDR)); config.SetProperty("CC:DD:EE:FF:00:11", "B", "AABBAABBCCDDEE"); - config.SetProperty("CC:DD:EE:FF:00:11", "DevType", std::to_string(bluetooth::hci::DeviceType::BR_EDR)); - config.SetProperty("CC:DD:EE:FF:00:11", "LinkKey", "AABBAABBCCDDEE"); - config.SetProperty("CC:DD:EE:FF:00:11", "LE_KEY_PENC", "AABBAABBCCDDEE"); + config.SetProperty( + "CC:DD:EE:FF:00:11", + BTIF_STORAGE_KEY_DEV_TYPE, + std::to_string(bluetooth::hci::DeviceType::BR_EDR)); + config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY, "AABBAABBCCDDEE"); + config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LE_KEY_PENC, "AABBAABBCCDDEE"); // act auto hadInconsistencies = config.FixDeviceTypeInconsistencies(); @@ -330,7 +347,7 @@ TEST(ConfigCacheTest, fix_device_type_inconsistency_devtype_should_be_dual_test) // assert ASSERT_TRUE(hadInconsistencies); ASSERT_THAT( - config.GetProperty("CC:DD:EE:FF:00:11", "DevType"), + config.GetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_DEV_TYPE), Optional(StrEq(std::to_string(bluetooth::hci::DeviceType::DUAL)))); } @@ -340,11 +357,17 @@ TEST(ConfigCacheTest, fix_device_type_inconsistency_devtype_should_be_le_not_cla config.SetProperty("A", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "C", "D"); - config.SetProperty("AA:BB:CC:DD:EE:FF", "DevType", std::to_string(bluetooth::hci::DeviceType::BR_EDR)); + config.SetProperty( + "AA:BB:CC:DD:EE:FF", + BTIF_STORAGE_KEY_DEV_TYPE, + std::to_string(bluetooth::hci::DeviceType::BR_EDR)); config.SetProperty("CC:DD:EE:FF:00:11", "B", "AABBAABBCCDDEE"); - config.SetProperty("CC:DD:EE:FF:00:11", "DevType", std::to_string(bluetooth::hci::DeviceType::BR_EDR)); - config.SetProperty("CC:DD:EE:FF:00:11", "LE_KEY_PENC", "AABBAABBCCDDEE"); + config.SetProperty( + "CC:DD:EE:FF:00:11", + BTIF_STORAGE_KEY_DEV_TYPE, + std::to_string(bluetooth::hci::DeviceType::BR_EDR)); + config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LE_KEY_PENC, "AABBAABBCCDDEE"); // act auto hadInconsistencies = config.FixDeviceTypeInconsistencies(); @@ -352,7 +375,7 @@ TEST(ConfigCacheTest, fix_device_type_inconsistency_devtype_should_be_le_not_cla // assert ASSERT_TRUE(hadInconsistencies); ASSERT_THAT( - config.GetProperty("CC:DD:EE:FF:00:11", "DevType"), + config.GetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_DEV_TYPE), Optional(StrEq(std::to_string(bluetooth::hci::DeviceType::LE)))); } @@ -362,12 +385,18 @@ TEST(ConfigCacheTest, fix_device_type_inconsistency_devtype_dont_override_dual_t config.SetProperty("A", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "C", "D"); - config.SetProperty("AA:BB:CC:DD:EE:FF", "DevType", std::to_string(bluetooth::hci::DeviceType::BR_EDR)); + config.SetProperty( + "AA:BB:CC:DD:EE:FF", + BTIF_STORAGE_KEY_DEV_TYPE, + std::to_string(bluetooth::hci::DeviceType::BR_EDR)); config.SetProperty("CC:DD:EE:FF:00:11", "B", "AABBAABBCCDDEE"); - config.SetProperty("CC:DD:EE:FF:00:11", "DevType", std::to_string(bluetooth::hci::DeviceType::DUAL)); - config.SetProperty("CC:DD:EE:FF:00:11", "LinkKey", "AABBAABBCCDDEE"); - config.SetProperty("CC:DD:EE:FF:00:11", "LE_KEY_PENC", "AABBAABBCCDDEE"); + config.SetProperty( + "CC:DD:EE:FF:00:11", + BTIF_STORAGE_KEY_DEV_TYPE, + std::to_string(bluetooth::hci::DeviceType::DUAL)); + config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY, "AABBAABBCCDDEE"); + config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LE_KEY_PENC, "AABBAABBCCDDEE"); // act auto hadInconsistencies = config.FixDeviceTypeInconsistencies(); @@ -375,7 +404,7 @@ TEST(ConfigCacheTest, fix_device_type_inconsistency_devtype_dont_override_dual_t // assert ASSERT_FALSE(hadInconsistencies); ASSERT_THAT( - config.GetProperty("CC:DD:EE:FF:00:11", "DevType"), + config.GetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_DEV_TYPE), Optional(StrEq(std::to_string(bluetooth::hci::DeviceType::DUAL)))); } @@ -406,7 +435,7 @@ TEST(ConfigCacheTest, test_empty_persistent_properties) { config.SetProperty("A", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:EF", "C", "D"); - config.SetProperty("AA:BB:CC:DD:EE:EF", "LinkKey", "D"); + config.SetProperty("AA:BB:CC:DD:EE:EF", BTIF_STORAGE_KEY_LINK_KEY, "D"); ASSERT_TRUE(config.HasAtLeastOneMatchingPropertiesInSection("AA:BB:CC:DD:EE:FF", {"B", "C", "D"})); ASSERT_TRUE(config.HasAtLeastOneMatchingPropertiesInSection("A", {"B", "C", "D"})); ASSERT_FALSE(config.HasAtLeastOneMatchingPropertiesInSection("AA:BB:CC:DD:EE:FF", {"BC", "D"})); diff --git a/system/gd/storage/config_keys.h b/system/gd/storage/config_keys.h new file mode 100644 index 0000000000..64492aed6d --- /dev/null +++ b/system/gd/storage/config_keys.h @@ -0,0 +1,113 @@ +/** + * Copyright (C) 2024 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#define BTIF_STORAGE_SECTION_ADAPTER "Adapter" +#define BTIF_STORAGE_SECTION_INFO "Info" +#define BTIF_STORAGE_SECTION_METRICS "Metrics" + +#define BTIF_STORAGE_KEY_ADDR_TYPE "AddrType" +#define BTIF_STORAGE_KEY_ADDRESS "Address" +#define BTIF_STORAGE_KEY_ALIAS "Aliase" +#define BTIF_STORAGE_KEY_APPEARANCE "Appearance" +#define BTIF_STORAGE_KEY_AV_REM_CTRL_FEATURES "AvrcpPeerFeatures" +#define BTIF_STORAGE_KEY_AVDTP_VERSION "AvdtpVersion" +#define BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION "AvrcpControllerVersion" +#define BTIF_STORAGE_KEY_CLOCK_OFFSET "ClockOffset" +#define BTIF_STORAGE_KEY_CSIS_AUTOCONNECT "CsisAutoconnect" +#define BTIF_STORAGE_KEY_CSIS_SET_INFO_BIN "CsisSetInfoBin" +#define BTIF_STORAGE_KEY_DEV_CLASS "DevClass" +#define BTIF_STORAGE_KEY_DEV_TYPE "DevType" +#define BTIF_STORAGE_KEY_DEVICE_GROUP_BIN "DeviceGroupBin" +#define BTIF_STORAGE_KEY_DIS_MODEL_NUM "ModelName" +#define BTIF_STORAGE_KEY_DISC_TIMEOUT "DiscoveryTimeout" +#define BTIF_STORAGE_KEY_GATT_CLIENT_DB_HASH "GattClientDatabaseHash" +#define BTIF_STORAGE_KEY_GATT_CLIENT_SUPPORTED "GattClientSupportedFeatures" +#define BTIF_STORAGE_KEY_GATT_SERVER_SUPPORTED "GattServerSupportedFeatures" +#define BTIF_STORAGE_KEY_HEARING_AID_AUDIO_CONTROL_POINT "HearingAidAudioControlPoint" +#define BTIF_STORAGE_KEY_HEARING_AID_AUDIO_STATUS_CCC_HANDLE "HearingAidAudioStatusCccHandle" +#define BTIF_STORAGE_KEY_HEARING_AID_AUDIO_STATUS_HANDLE "HearingAidAudioStatusHandle" +#define BTIF_STORAGE_KEY_HEARING_AID_CAPABILITIES "HearingAidCapabilities" +#define BTIF_STORAGE_KEY_HEARING_AID_CODECS "HearingAidCodecs" +#define BTIF_STORAGE_KEY_HEARING_AID_IS_ACCEPTLISTED "HearingAidIsAcceptlisted" +#define BTIF_STORAGE_KEY_HEARING_AID_PREPARATION_DELAY "HearingAidPreparationDelay" +#define BTIF_STORAGE_KEY_HEARING_AID_READ_PSM_HANDLE "HearingAidReadPsmHandle" +#define BTIF_STORAGE_KEY_HEARING_AID_RENDER_DELAY "HearingAidRenderDelay" +#define BTIF_STORAGE_KEY_HEARING_AID_SERVICE_CHANGED_CCC_HANDLE "HearingAidServiceChangedCccHandle" +#define BTIF_STORAGE_KEY_HEARING_AID_SYNC_ID "HearingAidSyncId" +#define BTIF_STORAGE_KEY_HEARING_AID_VOLUME_HANDLE "HearingAidVolumeHandle" +#define BTIF_STORAGE_KEY_HFP_SDP_FEATURES "HfpSdpFeatures" +#define BTIF_STORAGE_KEY_HFP_VERSION "HfpVersion" +#define BTIF_STORAGE_KEY_HID_APP_ID "HidAppId" +#define BTIF_STORAGE_KEY_HID_ATTR_MASK "HidAttrMask" +#define BTIF_STORAGE_KEY_HID_COUNTRY_CODE "HidCountryCode" +#define BTIF_STORAGE_KEY_HID_DESCRIPTOR "HidDescriptor" +#define BTIF_STORAGE_KEY_HID_DEVICE_CABLED "HidDeviceCabled" +#define BTIF_STORAGE_KEY_HID_PRODUCT_ID "HidProductId" +#define BTIF_STORAGE_KEY_HID_REPORT "HidReport" +#define BTIF_STORAGE_KEY_HID_REPORT_VERSION "HidReportVersion" +#define BTIF_STORAGE_KEY_HID_SSR_MAX_LATENCY "HidSSRMaxLatency" +#define BTIF_STORAGE_KEY_HID_SSR_MIN_TIMEOUT "HidSSRMinTimeout" +#define BTIF_STORAGE_KEY_HID_SUB_CLASS "HidSubClass" +#define BTIF_STORAGE_KEY_HID_VENDOR_ID "HidVendorId" +#define BTIF_STORAGE_KEY_HID_VERSION "HidVersion" +#define BTIF_STORAGE_KEY_LE_KEY_LCSRK "LE_KEY_LCSRK" +#define BTIF_STORAGE_KEY_LE_KEY_LENC "LE_KEY_LENC" +#define BTIF_STORAGE_KEY_LE_KEY_LID "LE_KEY_LID" +#define BTIF_STORAGE_KEY_LE_KEY_PCSRK "LE_KEY_PCSRK" +#define BTIF_STORAGE_KEY_LE_KEY_PENC "LE_KEY_PENC" +#define BTIF_STORAGE_KEY_LE_KEY_PID "LE_KEY_PID" +#define BTIF_STORAGE_KEY_LE_LOCAL_KEY_DHK "LE_LOCAL_KEY_DHK" +#define BTIF_STORAGE_KEY_LE_LOCAL_KEY_ER "LE_LOCAL_KEY_ER" +#define BTIF_STORAGE_KEY_LE_LOCAL_KEY_IR "LE_LOCAL_KEY_IR" +#define BTIF_STORAGE_KEY_LE_LOCAL_KEY_IRK "LE_LOCAL_KEY_IRK" +#define BTIF_STORAGE_KEY_LEAUDIO_ASES_BIN "AsesBin" +#define BTIF_STORAGE_KEY_LEAUDIO_AUTOCONNECT "LeAudioAutoconnect" +#define BTIF_STORAGE_KEY_LEAUDIO_HANDLES_BIN "LeAudioHandlesBin" +#define BTIF_STORAGE_KEY_LEAUDIO_HAS_ACTIVE_PRESET "LeAudioHasActivePreset" +#define BTIF_STORAGE_KEY_LEAUDIO_HAS_FLAGS "LeAudioHasFlags" +#define BTIF_STORAGE_KEY_LEAUDIO_HAS_IS_ACCEPTLISTED "LeAudioHasIsAcceptlisted" +#define BTIF_STORAGE_KEY_LEAUDIO_HAS_SERIALIZED_PRESETS "LeAudioHasSerializedPresets" +#define BTIF_STORAGE_KEY_LEAUDIO_SINK_AUDIOLOCATION "SinkAudioLocation" +#define BTIF_STORAGE_KEY_LEAUDIO_SINK_PACS_BIN "SinkPacsBin" +#define BTIF_STORAGE_KEY_LEAUDIO_SINK_SUPPORTED_CONTEXT_TYPE "SinkSupportedContextType" +#define BTIF_STORAGE_KEY_LEAUDIO_SOURCE_AUDIOLOCATION "SourceAudioLocation" +#define BTIF_STORAGE_KEY_LEAUDIO_SOURCE_PACS_BIN "SourcePacsBin" +#define BTIF_STORAGE_KEY_LEAUDIO_SOURCE_SUPPORTED_CONTEXT_TYPE "SourceSupportedContextType" +#define BTIF_STORAGE_KEY_LINK_KEY "LinkKey" +#define BTIF_STORAGE_KEY_LINK_KEY_TYPE "LinkKeyType" +#define BTIF_STORAGE_KEY_LOCAL_IO_CAPS "LocalIOCaps" +#define BTIF_STORAGE_KEY_METRICS_ID_KEY "MetricsId" +#define BTIF_STORAGE_KEY_METRICS_SALT_256BIT "Salt256Bit" +#define BTIF_STORAGE_KEY_NAME "Name" +#define BTIF_STORAGE_KEY_PBAP_PCE_VERSION "PbapPceVersion" +#define BTIF_STORAGE_KEY_PIN_LENGTH "PinLength" +#define BTIF_STORAGE_KEY_PRODUCT_ID "ProductId" +#define BTIF_STORAGE_KEY_REMOTE_SERVICE "Service" +#define BTIF_STORAGE_KEY_REMOTE_VER_MFCT "Manufacturer" +#define BTIF_STORAGE_KEY_REMOTE_VER_SUBVER "LmpSubVer" +#define BTIF_STORAGE_KEY_REMOTE_VER_VER "LmpVer" +#define BTIF_STORAGE_KEY_RESTRICTED "Restricted" +#define BTIF_STORAGE_KEY_SCANMODE "ScanMode" +#define BTIF_STORAGE_KEY_SDP_DI_HW_VERSION "SdpDiHardwareVersion" +#define BTIF_STORAGE_KEY_SDP_DI_MANUFACTURER "SdpDiManufacturer" +#define BTIF_STORAGE_KEY_SDP_DI_MODEL "SdpDiModel" +#define BTIF_STORAGE_KEY_SDP_DI_VENDOR_ID_SRC "SdpDiVendorIdSource" +#define BTIF_STORAGE_KEY_TIMESTAMP "Timestamp" +#define BTIF_STORAGE_KEY_VENDOR_ID "VendorId" +#define BTIF_STORAGE_KEY_VENDOR_ID_SOURCE "VendorIdSource" +#define BTIF_STORAGE_KEY_VERSION "ProductVersion" diff --git a/system/gd/storage/device.h b/system/gd/storage/device.h index e1b5fd97b7..ffccefdf86 100644 --- a/system/gd/storage/device.h +++ b/system/gd/storage/device.h @@ -29,6 +29,7 @@ #include "hci/enum_helper.h" #include "storage/config_cache.h" #include "storage/config_cache_helper.h" +#include "storage/config_keys.h" #include "storage/mutation_entry.h" #include "storage/serializable.h" @@ -183,11 +184,14 @@ class Device { public: // Macro generate getters, setters and removers - GENERATE_PROPERTY_GETTER_SETTER_REMOVER(Name, std::string, "Name"); - GENERATE_PROPERTY_GETTER_SETTER_REMOVER(ClassOfDevice, hci::ClassOfDevice, "DevClass"); - GENERATE_PROPERTY_GETTER_SETTER_REMOVER_WITH_CUSTOM_SETTER(DeviceType, hci::DeviceType, "DevType", { - return static_cast<hci::DeviceType>(value | GetDeviceType().value_or(hci::DeviceType::UNKNOWN)); - }); + GENERATE_PROPERTY_GETTER_SETTER_REMOVER(Name, std::string, BTIF_STORAGE_KEY_NAME); + GENERATE_PROPERTY_GETTER_SETTER_REMOVER( + ClassOfDevice, hci::ClassOfDevice, BTIF_STORAGE_KEY_DEV_CLASS); + GENERATE_PROPERTY_GETTER_SETTER_REMOVER_WITH_CUSTOM_SETTER( + DeviceType, hci::DeviceType, BTIF_STORAGE_KEY_DEV_TYPE, { + return static_cast<hci::DeviceType>( + value | GetDeviceType().value_or(hci::DeviceType::UNKNOWN)); + }); GENERATE_PROPERTY_GETTER_SETTER_REMOVER(ManufacturerCode, uint16_t, "Manufacturer"); GENERATE_PROPERTY_GETTER_SETTER_REMOVER(LmpVersion, uint8_t, "LmpVer"); GENERATE_PROPERTY_GETTER_SETTER_REMOVER(LmpSubVersion, uint16_t, "LmpSubVer"); @@ -199,7 +203,7 @@ class Device { GENERATE_PROPERTY_GETTER_SETTER_REMOVER(MetricsId, int, "MetricsId"); GENERATE_PROPERTY_GETTER_SETTER_REMOVER(PinLength, int, "PinLength"); // unix timestamp in seconds from epoch - GENERATE_PROPERTY_GETTER_SETTER_REMOVER(CreationUnixTimestamp, int, "DevClass"); + GENERATE_PROPERTY_GETTER_SETTER_REMOVER(CreationUnixTimestamp, int, BTIF_STORAGE_KEY_DEV_CLASS); GENERATE_PROPERTY_GETTER_SETTER_REMOVER(IsAuthenticated, int, "IsAuthenticated"); GENERATE_PROPERTY_GETTER_SETTER_REMOVER(RequiresMitmProtection, int, "RequiresMitmProtection"); GENERATE_PROPERTY_GETTER_SETTER_REMOVER(IsEncryptionRequired, int, "IsEncryptionRequired"); diff --git a/system/gd/storage/le_device.h b/system/gd/storage/le_device.h index d87225f2ba..e855e37e04 100644 --- a/system/gd/storage/le_device.h +++ b/system/gd/storage/le_device.h @@ -20,6 +20,7 @@ #include "hci/hci_packets.h" #include "storage/config_cache.h" +#include "storage/config_keys.h" #include "storage/device.h" namespace bluetooth { @@ -83,13 +84,16 @@ class LeDevice { public: // Get LE address type of the key address - GENERATE_PROPERTY_GETTER_SETTER_REMOVER(AddressType, hci::AddressType, "AddrType"); + GENERATE_PROPERTY_GETTER_SETTER_REMOVER( + AddressType, hci::AddressType, BTIF_STORAGE_KEY_ADDR_TYPE); // IRK + Identity Address Type + Identity Address - GENERATE_PROPERTY_GETTER_SETTER_REMOVER(PeerId, std::string, "LE_KEY_PID"); + GENERATE_PROPERTY_GETTER_SETTER_REMOVER(PeerId, std::string, BTIF_STORAGE_KEY_LE_KEY_PID); // LTK + RAND + EDIV + Security Level + Key Length - GENERATE_PROPERTY_GETTER_SETTER_REMOVER(PeerEncryptionKeys, std::string, "LE_KEY_PENC"); + GENERATE_PROPERTY_GETTER_SETTER_REMOVER( + PeerEncryptionKeys, std::string, BTIF_STORAGE_KEY_LE_KEY_PENC); // counter + CSRK (connection signature resolving key) + security level - GENERATE_PROPERTY_GETTER_SETTER_REMOVER(PeerSignatureResolvingKeys, std::string, "LE_KEY_PCSRK"); + GENERATE_PROPERTY_GETTER_SETTER_REMOVER( + PeerSignatureResolvingKeys, std::string, BTIF_STORAGE_KEY_LE_KEY_PCSRK); GENERATE_PROPERTY_GETTER_SETTER_REMOVER(LegacyPseudoAddress, hci::Address, "LeLegacyPseudoAddr"); }; diff --git a/system/gd/storage/legacy_config_file_test.cc b/system/gd/storage/legacy_config_file_test.cc index 6b82b74729..430dbd403d 100644 --- a/system/gd/storage/legacy_config_file_test.cc +++ b/system/gd/storage/legacy_config_file_test.cc @@ -22,6 +22,7 @@ #include <filesystem> #include "os/files.h" +#include "storage/config_keys.h" #include "storage/device.h" namespace testing { @@ -40,8 +41,8 @@ TEST(LegacyConfigFileTest, write_and_read_loop_back_test) { config.SetProperty("A", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "B", "C"); config.SetProperty("AA:BB:CC:DD:EE:FF", "C", "D"); - config.SetProperty("CC:DD:EE:FF:00:11", "LinkKey", "AABBAABBCCDDEE"); - EXPECT_TRUE(config.HasProperty("CC:DD:EE:FF:00:11", "LinkKey")); + config.SetProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY, "AABBAABBCCDDEE"); + EXPECT_TRUE(config.HasProperty("CC:DD:EE:FF:00:11", BTIF_STORAGE_KEY_LINK_KEY)); EXPECT_THAT(config.GetPersistentSections(), ElementsAre("CC:DD:EE:FF:00:11")); EXPECT_TRUE(LegacyConfigFile::FromPath(temp_config.string()).Write(config)); @@ -103,7 +104,7 @@ static const std::string kWriteTestConfig = "Address = 01:02:03:ab:cd:ef\n" "\n" "[01:02:03:ab:cd:ea]\n" - "name = hello world\n" + "Name = hello world\n" "LinkKey = fedcba0987654321fedcba0987654328\n" "\n"; @@ -114,9 +115,10 @@ TEST(LegacyConfigFileTest, write_test) { ConfigCache config(100, Device::kLinkKeyProperties); config.SetProperty("Info", "FileSource", "Empty"); config.SetProperty("Info", "TimeCreated", ""); - config.SetProperty("Adapter", "Address", "01:02:03:ab:cd:ef"); - config.SetProperty("01:02:03:ab:cd:ea", "name", "hello world"); - config.SetProperty("01:02:03:ab:cd:ea", "LinkKey", "fedcba0987654321fedcba0987654328"); + config.SetProperty(BTIF_STORAGE_SECTION_ADAPTER, BTIF_STORAGE_KEY_ADDRESS, "01:02:03:ab:cd:ef"); + config.SetProperty("01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_NAME, "hello world"); + config.SetProperty( + "01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_LINK_KEY, "fedcba0987654321fedcba0987654328"); EXPECT_TRUE(LegacyConfigFile::FromPath(temp_config.string()).Write(config)); EXPECT_THAT(ReadSmallFile(temp_config.string()), Optional(StrEq(kWriteTestConfig))); diff --git a/system/gd/storage/storage_module.cc b/system/gd/storage/storage_module.cc index f2386f8bf7..febcf95a61 100644 --- a/system/gd/storage/storage_module.cc +++ b/system/gd/storage/storage_module.cc @@ -30,6 +30,7 @@ #include "os/parameter_provider.h" #include "os/system_properties.h" #include "storage/config_cache.h" +#include "storage/config_keys.h" #include "storage/legacy_config_file.h" #include "storage/mutation.h" @@ -53,12 +54,12 @@ const int kConfigBackupComparePass = 2; const std::string kConfigFilePrefix = "bt_config-origin"; const std::string kConfigFileHash = "hash"; -const std::string StorageModule::kInfoSection = "Info"; +const std::string StorageModule::kInfoSection = BTIF_STORAGE_SECTION_INFO; const std::string StorageModule::kFileSourceProperty = "FileSource"; const std::string StorageModule::kTimeCreatedProperty = "TimeCreated"; const std::string StorageModule::kTimeCreatedFormat = "%Y-%m-%d %H:%M:%S"; -const std::string StorageModule::kAdapterSection = "Adapter"; +const std::string StorageModule::kAdapterSection = BTIF_STORAGE_SECTION_ADAPTER; StorageModule::StorageModule( std::string config_file_path, diff --git a/system/gd/storage/storage_module_test.cc b/system/gd/storage/storage_module_test.cc index 6f645482a0..88ec4f6a21 100644 --- a/system/gd/storage/storage_module_test.cc +++ b/system/gd/storage/storage_module_test.cc @@ -31,6 +31,7 @@ #include "os/fake_timer/fake_timerfd.h" #include "os/files.h" #include "storage/config_cache.h" +#include "storage/config_keys.h" #include "storage/device.h" #include "storage/legacy_config_file.h" @@ -187,7 +188,7 @@ static const std::string kReadTestConfig = "DiscoveryTimeout = 120\n" "\n" "[01:02:03:ab:cd:ea]\n" - "name = hello world\n" + "Name = hello world\n" "LinkKey = fedcba0987654321fedcba0987654328\n" "\n"; @@ -203,7 +204,7 @@ TEST_F(StorageModuleTest, read_existing_config_test) { ASSERT_TRUE(storage->HasSectionPublic("Metrics")); ASSERT_THAT(storage->GetPersistentSectionsPublic(), ElementsAre("01:02:03:ab:cd:ea")); ASSERT_THAT( - storage->GetPropertyPublic(StorageModule::kAdapterSection, "Address"), + storage->GetPropertyPublic(StorageModule::kAdapterSection, BTIF_STORAGE_KEY_ADDRESS), Optional(StrEq("01:02:03:ab:cd:ef"))); // Tear down @@ -229,22 +230,26 @@ TEST_F(StorageModuleTest, save_config_test) { // Test // Change a property ASSERT_THAT( - storage->GetPropertyPublic("01:02:03:ab:cd:ea", "name"), Optional(StrEq("hello world"))); - storage->SetPropertyPublic("01:02:03:ab:cd:ea", "name", "foo"); - ASSERT_THAT(storage->GetPropertyPublic("01:02:03:ab:cd:ea", "name"), Optional(StrEq("foo"))); + storage->GetPropertyPublic("01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_NAME), + Optional(StrEq("hello world"))); + storage->SetPropertyPublic("01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_NAME, "foo"); + ASSERT_THAT( + storage->GetPropertyPublic("01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_NAME), + Optional(StrEq("foo"))); ASSERT_TRUE(WaitForReactorIdle(kTestConfigSaveDelay)); auto config = LegacyConfigFile::FromPath(temp_config_.string()).Read(kTestTempDevicesCapacity); ASSERT_TRUE(config); - ASSERT_THAT(config->GetProperty("01:02:03:ab:cd:ea", "name"), Optional(StrEq("foo"))); + ASSERT_THAT( + config->GetProperty("01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_NAME), Optional(StrEq("foo"))); // Remove a property - storage->RemovePropertyPublic("01:02:03:ab:cd:ea", "name"); + storage->RemovePropertyPublic("01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_NAME); ASSERT_TRUE(WaitForReactorIdle(kTestConfigSaveDelay)); LOG_INFO("After waiting 2"); config = LegacyConfigFile::FromPath(temp_config_.string()).Read(kTestTempDevicesCapacity); ASSERT_TRUE(config); - ASSERT_FALSE(config->HasProperty("01:02:03:ab:cd:ea", "name")); + ASSERT_FALSE(config->HasProperty("01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_NAME)); // Remove a section storage->RemoveSectionPublic("01:02:03:ab:cd:ea"); @@ -310,7 +315,7 @@ TEST_F(StorageModuleTest, changed_config_causes_a_write) { DeleteConfigFiles(); // Change a property - storage->SetPropertyPublic("01:02:03:ab:cd:ea", "name", "foo"); + storage->SetPropertyPublic("01:02:03:ab:cd:ea", BTIF_STORAGE_KEY_NAME, "foo"); ASSERT_TRUE(WaitForReactorIdle(std::chrono::milliseconds(1))); diff --git a/system/gd/sysprops/BUILD.gn b/system/gd/sysprops/BUILD.gn index c6401a0b29..fb3204c6c9 100644 --- a/system/gd/sysprops/BUILD.gn +++ b/system/gd/sysprops/BUILD.gn @@ -17,6 +17,9 @@ source_set("BluetoothSyspropsSources") { sources = [ "sysprops_module.cc" ] - configs += [ "//bt/system/gd:gd_defaults" ] + configs += [ + "//bt/system/gd:gd_defaults", + "//bt/system/log:log_defaults", + ] deps = [ "//bt/system/gd:gd_default_deps" ] } diff --git a/system/hci/Android.bp b/system/hci/Android.bp index b85a34cebc..b0773d34c1 100644 --- a/system/hci/Android.bp +++ b/system/hci/Android.bp @@ -32,7 +32,10 @@ cc_library_static { host_supported: true, min_sdk_version: "Tiramisu", header_libs: ["libbluetooth_headers"], - static_libs: ["libbt_shim_bridge"], + static_libs: [ + "libbluetooth_log", + "libbt_shim_bridge", + ], } // HCI unit tests for target @@ -61,6 +64,7 @@ cc_test { ], static_libs: [ "libbluetooth-types", + "libbluetooth_log", "libbt-hci", "libchrome", "libosi", diff --git a/system/include/hardware/avrcp/avrcp.h b/system/include/hardware/avrcp/avrcp.h index cfd9388dc5..9ba033ad0e 100644 --- a/system/include/hardware/avrcp/avrcp.h +++ b/system/include/hardware/avrcp/avrcp.h @@ -16,12 +16,12 @@ #pragma once +#include <base/functional/callback_forward.h> + #include <set> #include <string> #include <vector> -#include <base/functional/callback_forward.h> - #include "avrcp_common.h" #include "raw_address.h" diff --git a/system/include/hardware/avrcp/avrcp_logging_helper.h b/system/include/hardware/avrcp/avrcp_logging_helper.h index dc2d52354f..79792eafc5 100644 --- a/system/include/hardware/avrcp/avrcp_logging_helper.h +++ b/system/include/hardware/avrcp/avrcp_logging_helper.h @@ -16,6 +16,8 @@ #pragma once +#include <bluetooth/log.h> + #include <iomanip> #include <iostream> #include <sstream> @@ -284,3 +286,36 @@ inline std::ostream& operator<<(std::ostream& os, } // namespace avrcp } // namespace bluetooth + +namespace fmt { +template <> +struct formatter<bluetooth::avrcp::CType> : ostream_formatter {}; +template <> +struct formatter<bluetooth::avrcp::Opcode> : ostream_formatter {}; +template <> +struct formatter<bluetooth::avrcp::CommandPdu> : ostream_formatter {}; +template <> +struct formatter<bluetooth::avrcp::PacketType> : ostream_formatter {}; +template <> +struct formatter<bluetooth::avrcp::Capability> : ostream_formatter {}; +template <> +struct formatter<bluetooth::avrcp::Event> : ostream_formatter {}; +template <> +struct formatter<bluetooth::avrcp::Attribute> : ostream_formatter {}; +template <> +struct formatter<bluetooth::avrcp::Status> : ostream_formatter {}; +template <> +struct formatter<bluetooth::avrcp::BrowsePdu> : ostream_formatter {}; +template <> +struct formatter<bluetooth::avrcp::Scope> : ostream_formatter {}; +template <> +struct formatter<bluetooth::avrcp::Direction> : ostream_formatter {}; +template <> +struct formatter<bluetooth::avrcp::KeyState> : ostream_formatter {}; +template <> +struct formatter<bluetooth::avrcp::PlayerAttribute> : ostream_formatter {}; +template <> +struct formatter<bluetooth::avrcp::PlayerRepeatValue> : ostream_formatter {}; +template <> +struct formatter<bluetooth::avrcp::PlayerShuffleValue> : ostream_formatter {}; +} // namespace fmt diff --git a/system/include/hardware/ble_scanner.h b/system/include/hardware/ble_scanner.h index af5b71098e..a899526d53 100644 --- a/system/include/hardware/ble_scanner.h +++ b/system/include/hardware/ble_scanner.h @@ -183,8 +183,9 @@ class BleScannerInterface { MsftAdvMonitorEnableCallback cb) = 0; /** Sets the LE scan interval and window in units of N*0.625 msec */ - virtual void SetScanParameters(int scanner_id, int scan_interval, - int scan_window, Callback cb) = 0; + virtual void SetScanParameters(int scanner_id, uint8_t scan_type, + int scan_interval, int scan_window, + Callback cb) = 0; /* Configure the batchscan storage */ virtual void BatchscanConfigStorage(int client_if, int batch_scan_full_max, diff --git a/system/include/hardware/bt_le_audio.h b/system/include/hardware/bt_le_audio.h index c7d3130d91..93fcc046d3 100644 --- a/system/include/hardware/bt_le_audio.h +++ b/system/include/hardware/bt_le_audio.h @@ -102,11 +102,18 @@ typedef enum { QUALITY_STANDARD = 0, QUALITY_HIGH } btle_audio_quality_t; typedef enum { LE_AUDIO_SAMPLE_RATE_INDEX_NONE = 0, LE_AUDIO_SAMPLE_RATE_INDEX_8000HZ = 0x01 << 0, + LE_AUDIO_SAMPLE_RATE_INDEX_11025HZ = 0x01 << 1, LE_AUDIO_SAMPLE_RATE_INDEX_16000HZ = 0x01 << 2, + LE_AUDIO_SAMPLE_RATE_INDEX_22050HZ = 0x01 << 3, LE_AUDIO_SAMPLE_RATE_INDEX_24000HZ = 0x01 << 4, LE_AUDIO_SAMPLE_RATE_INDEX_32000HZ = 0x01 << 5, LE_AUDIO_SAMPLE_RATE_INDEX_44100HZ = 0x01 << 6, - LE_AUDIO_SAMPLE_RATE_INDEX_48000HZ = 0x01 << 7 + LE_AUDIO_SAMPLE_RATE_INDEX_48000HZ = 0x01 << 7, + LE_AUDIO_SAMPLE_RATE_INDEX_88200HZ = 0x01 << 8, + LE_AUDIO_SAMPLE_RATE_INDEX_96000HZ = 0x01 << 9, + LE_AUDIO_SAMPLE_RATE_INDEX_176400HZ = 0x01 << 10, + LE_AUDIO_SAMPLE_RATE_INDEX_192000HZ = 0x01 << 11, + LE_AUDIO_SAMPLE_RATE_INDEX_384000HZ = 0x01 << 12 } btle_audio_sample_rate_index_t; typedef enum { @@ -162,9 +169,15 @@ typedef struct { case LE_AUDIO_SAMPLE_RATE_INDEX_8000HZ: sample_rate_str = "8000 hz"; break; + case LE_AUDIO_SAMPLE_RATE_INDEX_11025HZ: + sample_rate_str = "11025 hz"; + break; case LE_AUDIO_SAMPLE_RATE_INDEX_16000HZ: sample_rate_str = "16000 hz"; break; + case LE_AUDIO_SAMPLE_RATE_INDEX_22050HZ: + sample_rate_str = "22050 hz"; + break; case LE_AUDIO_SAMPLE_RATE_INDEX_24000HZ: sample_rate_str = "24000 hz"; break; @@ -177,6 +190,21 @@ typedef struct { case LE_AUDIO_SAMPLE_RATE_INDEX_48000HZ: sample_rate_str = "48000 hz"; break; + case LE_AUDIO_SAMPLE_RATE_INDEX_88200HZ: + sample_rate_str = "88200 hz"; + break; + case LE_AUDIO_SAMPLE_RATE_INDEX_96000HZ: + sample_rate_str = "96000 hz"; + break; + case LE_AUDIO_SAMPLE_RATE_INDEX_176400HZ: + sample_rate_str = "176400 hz"; + break; + case LE_AUDIO_SAMPLE_RATE_INDEX_192000HZ: + sample_rate_str = "192000 hz"; + break; + case LE_AUDIO_SAMPLE_RATE_INDEX_384000HZ: + sample_rate_str = "384000 hz"; + break; default: sample_rate_str = "Unknown LE sample rate " + std::to_string(sample_rate); diff --git a/system/log/Android.bp b/system/log/Android.bp new file mode 100644 index 0000000000..10c7e730db --- /dev/null +++ b/system/log/Android.bp @@ -0,0 +1,31 @@ +cc_library { + name: "libbluetooth_log", + host_supported: true, + min_sdk_version: "33", + apex_available: [ + "com.android.btservices", + ], + export_include_dirs: [ + "include", + ], + shared_libs: [ + "libbase", + "liblog", + ], + srcs: [ + "src/vlog_android.cc", + ], +} + +cc_test { + name: "libbluetooth_log_test", + host_supported: true, + srcs: [ + "src/truncating_buffer_test.cc", + "src/vlog_test.cc", + ], + shared_libs: [ + "libbase", + "libbluetooth_log", + ], +} diff --git a/system/log/BUILD.gn b/system/log/BUILD.gn new file mode 100644 index 0000000000..b7b94e7dee --- /dev/null +++ b/system/log/BUILD.gn @@ -0,0 +1,36 @@ +# +# Copyright 2024 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. +# + +config("log_defaults") { + include_dirs = [ + "//bt/system/log/include", + ] +} + +static_library("libbluetooth_log") { + cflags = [ + "-fvisibility=default", + ] + sources = [ + "include/bluetooth/log.h", + "src/truncating_buffer.h", + "src/vlog_syslog.cc", + ] + configs += [ + "//bt/system:target_defaults", + ":log_defaults", + ] +} diff --git a/system/log/include/bluetooth/log.h b/system/log/include/bluetooth/log.h new file mode 100644 index 0000000000..3ed77aa7a4 --- /dev/null +++ b/system/log/include/bluetooth/log.h @@ -0,0 +1,146 @@ +/* + * 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. + */ + +#pragma once + +#include <fmt/core.h> +#include <fmt/format.h> +#include <fmt/std.h> + +#ifndef LOG_TAG +#define LOG_TAG "bluetooth" +#endif // LOG_TAG + +namespace bluetooth::log_internal { + +/// Android framework log priority levels. +/// They are defined in system/logging/liblog/include/android/log.h by +/// the Android Framework code. +enum Level { + kVerbose = 2, + kDebug = 3, + kInfo = 4, + kWarn = 5, + kError = 6, + kFatal = 7, +}; + +/// Write a single log line. +/// The implementation of this function is dependent on the backend. +void vlog(Level level, char const* tag, char const* file_name, int line, + char const* function_name, fmt::string_view fmt, + fmt::format_args vargs); + +template <Level level, typename... T> +struct log { + log(fmt::format_string<T...> fmt, T&&... args, + char const* file_name = __builtin_FILE(), int line = __builtin_LINE(), + char const* function_name = __builtin_FUNCTION()) { + vlog(level, LOG_TAG, file_name, line, function_name, + static_cast<fmt::string_view>(fmt), fmt::make_format_args(args...)); + } +}; + +#if (__cplusplus >= 202002L && defined(__GNUC__) && !defined(__clang__)) + +template <int level, typename... T> +log(fmt::format_string<T...>, T&&...) -> log<level, T...>; + +#endif + +} // namespace bluetooth::log_internal + +namespace bluetooth::log { + +#if (__cplusplus >= 202002L && defined(__GNUC__) && !defined(__clang__)) + +template <typename... T> +using fatal = log_internal::log<log_internal::kFatal, T...>; +template <typename... T> +using error = log_internal::log<log_internal::kError, T...>; +template <typename... T> +using warning = log_internal::log<log_internal::kWarning, T...>; +template <typename... T> +using info = log_internal::log<log_internal::kInfo, T...>; +template <typename... T> +using debug = log_internal::log<log_internal::kDebug, T...>; +template <typename... T> +using verbose = log_internal::log<log_internal::kVerbose, T...>; + +#else + +template <typename... T> +struct fatal : log_internal::log<log_internal::kFatal, T...> { + using log_internal::log<log_internal::kFatal, T...>::log; +}; +template <typename... T> +struct error : log_internal::log<log_internal::kError, T...> { + using log_internal::log<log_internal::kError, T...>::log; +}; +template <typename... T> +struct warn : log_internal::log<log_internal::kWarn, T...> { + using log_internal::log<log_internal::kWarn, T...>::log; +}; +template <typename... T> +struct info : log_internal::log<log_internal::kInfo, T...> { + using log_internal::log<log_internal::kInfo, T...>::log; +}; +template <typename... T> +struct debug : log_internal::log<log_internal::kDebug, T...> { + using log_internal::log<log_internal::kDebug, T...>::log; +}; +template <typename... T> +struct verbose : log_internal::log<log_internal::kVerbose, T...> { + using log_internal::log<log_internal::kVerbose, T...>::log; +}; + +template <typename... T> +fatal(fmt::format_string<T...>, T&&...) -> fatal<T...>; +template <typename... T> +error(fmt::format_string<T...>, T&&...) -> error<T...>; +template <typename... T> +warn(fmt::format_string<T...>, T&&...) -> warn<T...>; +template <typename... T> +info(fmt::format_string<T...>, T&&...) -> info<T...>; +template <typename... T> +debug(fmt::format_string<T...>, T&&...) -> debug<T...>; +template <typename... T> +verbose(fmt::format_string<T...>, T&&...) -> verbose<T...>; + +#endif // GCC / C++20 + +} // namespace bluetooth::log + +namespace fmt { + +/// Default formatter implementation for formatting +/// enum class values to the underlying type. +/// +/// Enable this formatter in the code by declaring: +/// ``` +/// template<> +/// struct fmt::formatter<EnumT> : enum_formatter<EnumT> {}; +/// ``` +template <typename EnumT, class CharT = char> +struct enum_formatter : fmt::formatter<std::underlying_type_t<EnumT>, CharT> { + template <class Context> + typename Context::iterator format(EnumT value, Context& ctx) const { + return fmt::formatter<std::underlying_type_t<EnumT>, CharT>::format( + static_cast<std::underlying_type_t<EnumT>>(value), ctx); + } +}; + +} // namespace fmt diff --git a/system/log/src/truncating_buffer.h b/system/log/src/truncating_buffer.h new file mode 100644 index 0000000000..c2ad0014a9 --- /dev/null +++ b/system/log/src/truncating_buffer.h @@ -0,0 +1,69 @@ +/* + * 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. + */ + +#pragma once + +#include <cstddef> + +namespace bluetooth::log_internal { + +/// Truncating write buffer. +/// +/// This buffer can be used with `std::back_insert_iterator` to create +/// an output iterator. All write actions beyond the maximum length of +/// the buffer are silently ignored. +template <int buffer_size> +struct truncating_buffer { + using value_type = char; + + void push_back(char c) { + if (len < buffer_size - 1) { + buffer[len++] = c; + } + } + + char const* c_str() { + if (len == buffer_size - 1) { + // Inspect the last 4 bytes of the buffer to check if + // the last character was truncated. Remove the character + // entirely if that's the case. + for (size_t n = 0; n < 4; n++) { + char c = buffer[len - n - 1]; + if ((c & 0b11000000) == 0b10000000) { + continue; + } + size_t char_len = (c & 0b10000000) == 0b00000000 ? 1 + : (c & 0b11100000) == 0b11000000 ? 2 + : (c & 0b11110000) == 0b11100000 ? 3 + : (c & 0b11111000) == 0b11110000 ? 4 + : 0; + if ((n + 1) < char_len) { + len -= n + 1; + } + break; + } + } + + buffer[len] = '\0'; + return buffer; + } + + private: + char buffer[buffer_size]; + size_t len{0}; +}; + +} // namespace bluetooth::log_internal diff --git a/system/log/src/truncating_buffer_test.cc b/system/log/src/truncating_buffer_test.cc new file mode 100644 index 0000000000..5790270cdc --- /dev/null +++ b/system/log/src/truncating_buffer_test.cc @@ -0,0 +1,83 @@ +/* + * 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 "test" + +#include "truncating_buffer.h" + +#include <fmt/format.h> +#include <gtest/gtest.h> +#include <log/log.h> + +using namespace bluetooth::log_internal; + +TEST(TruncatingBufferTest, 1byte) { + EXPECT_EQ(sizeof("ab"), 3); + truncating_buffer<2> buffer_1; + truncating_buffer<3> buffer_2; + fmt::format_to(std::back_insert_iterator(buffer_1), "ab"); + fmt::format_to(std::back_insert_iterator(buffer_2), "ab"); + EXPECT_STREQ(buffer_1.c_str(), "a"); + EXPECT_STREQ(buffer_2.c_str(), "ab"); +} + +TEST(TruncatingBufferTest, 2bytes) { + EXPECT_EQ(sizeof("αβ"), 5); + truncating_buffer<3> buffer_1; + truncating_buffer<4> buffer_2; + truncating_buffer<5> buffer_3; + fmt::format_to(std::back_insert_iterator(buffer_1), "αβ"); + fmt::format_to(std::back_insert_iterator(buffer_2), "αβ"); + fmt::format_to(std::back_insert_iterator(buffer_3), "αβ"); + EXPECT_STREQ(buffer_1.c_str(), "α"); + EXPECT_STREQ(buffer_2.c_str(), "α"); + EXPECT_STREQ(buffer_3.c_str(), "αβ"); +} + +TEST(TruncatingBufferTest, 3bytes) { + EXPECT_EQ(sizeof("ພຮ"), 7); + truncating_buffer<4> buffer_1; + truncating_buffer<5> buffer_2; + truncating_buffer<6> buffer_3; + truncating_buffer<7> buffer_4; + fmt::format_to(std::back_insert_iterator(buffer_1), "ພຮ"); + fmt::format_to(std::back_insert_iterator(buffer_2), "ພຮ"); + fmt::format_to(std::back_insert_iterator(buffer_3), "ພຮ"); + fmt::format_to(std::back_insert_iterator(buffer_4), "ພຮ"); + EXPECT_STREQ(buffer_1.c_str(), "ພ"); + EXPECT_STREQ(buffer_2.c_str(), "ພ"); + EXPECT_STREQ(buffer_3.c_str(), "ພ"); + EXPECT_STREQ(buffer_4.c_str(), "ພຮ"); +} + +TEST(TruncatingBufferTest, 4bytes) { + EXPECT_EQ(sizeof("𐎡𐎪"), 9); + truncating_buffer<5> buffer_1; + truncating_buffer<6> buffer_2; + truncating_buffer<7> buffer_3; + truncating_buffer<8> buffer_4; + truncating_buffer<9> buffer_5; + fmt::format_to(std::back_insert_iterator(buffer_1), "𐎡𐎪"); + fmt::format_to(std::back_insert_iterator(buffer_2), "𐎡𐎪"); + fmt::format_to(std::back_insert_iterator(buffer_3), "𐎡𐎪"); + fmt::format_to(std::back_insert_iterator(buffer_4), "𐎡𐎪"); + fmt::format_to(std::back_insert_iterator(buffer_5), "𐎡𐎪"); + EXPECT_STREQ(buffer_1.c_str(), "𐎡"); + EXPECT_STREQ(buffer_2.c_str(), "𐎡"); + EXPECT_STREQ(buffer_3.c_str(), "𐎡"); + EXPECT_STREQ(buffer_4.c_str(), "𐎡"); + EXPECT_STREQ(buffer_5.c_str(), "𐎡𐎪"); +} diff --git a/system/log/src/vlog_android.cc b/system/log/src/vlog_android.cc new file mode 100644 index 0000000000..d6bc1355dc --- /dev/null +++ b/system/log/src/vlog_android.cc @@ -0,0 +1,62 @@ +/* + * 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 <log/log.h> + +#include "bluetooth/log.h" +#include "truncating_buffer.h" + +namespace bluetooth::log_internal { + +static constexpr size_t kBufferSize = 1024; + +void vlog(Level level, char const* tag, char const* file_name, int line, + char const* function_name, fmt::string_view fmt, + fmt::format_args vargs) { + // Check if log is enabled. + if (!__android_log_is_loggable(level, tag, ANDROID_LOG_DEFAULT) && + !__android_log_is_loggable(level, "bluetooth", ANDROID_LOG_DEFAULT)) { + return; + } + + // Format to stack buffer. + truncating_buffer<kBufferSize> buffer; + fmt::format_to(std::back_insert_iterator(buffer), "{}: ", function_name); + fmt::vformat_to(std::back_insert_iterator(buffer), fmt, vargs); + + // Send message to liblog. + struct __android_log_message message = { + .struct_size = sizeof(__android_log_message), + .buffer_id = LOG_ID_MAIN, + .priority = static_cast<android_LogPriority>(level), + .tag = tag, + .file = file_name, + .line = static_cast<uint32_t>(line), + .message = buffer.c_str(), + }; + __android_log_write_log_message(&message); + + if (level == Level::kFatal) { + // Log assertion failures to stderr for the benefit of "adb shell" users + // and gtests (http://b/23675822). + char const* buf = buffer.c_str(); + TEMP_FAILURE_RETRY(write(2, buf, strlen(buf))); + TEMP_FAILURE_RETRY(write(2, "\n", 1)); + __android_log_call_aborter(buf); + } +} + +} // namespace bluetooth::log_internal diff --git a/system/log/src/vlog_syslog.cc b/system/log/src/vlog_syslog.cc new file mode 100644 index 0000000000..9d7dad1a96 --- /dev/null +++ b/system/log/src/vlog_syslog.cc @@ -0,0 +1,66 @@ +/* + * 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 <syslog.h> + +#include "bluetooth/log.h" +#include "truncating_buffer.h" + +namespace bluetooth::log_internal { + +// Default value for $MaxMessageSize for rsyslog. +static constexpr size_t kBufferSize = 8192; + +void vlog(Level level, char const* tag, char const* file_name, int line, + char const* function_name, fmt::string_view fmt, + fmt::format_args vargs) { + // Convert the level to syslog severity. + int severity = LOG_DEBUG; + switch (level) { + case Level::kVerbose: + case Level::kDebug: + default: + severity = LOG_DEBUG; + break; + case Level::kInfo: + severity = LOG_INFO; + break; + case Level::kWarn: + severity = LOG_WARNING; + break; + case Level::kError: + severity = LOG_ERR; + break; + case Level::kFatal: + severity = LOG_CRIT; + break; + } + + // Prepare bounded stack buffer. + truncating_buffer<kBufferSize> buffer; + + // Format file, line. + fmt::format_to(std::back_insert_iterator(buffer), "{} {}:{} {}: ", tag, + file_name, line, function_name); + + // Format message. + fmt::vformat_to(std::back_insert_iterator(buffer), fmt, vargs); + + // Print to vsyslog. + syslog(LOG_USER | severity, "%s", buffer.c_str()); +} + +} // namespace bluetooth::log_internal diff --git a/system/log/src/vlog_test.cc b/system/log/src/vlog_test.cc new file mode 100644 index 0000000000..026dd73708 --- /dev/null +++ b/system/log/src/vlog_test.cc @@ -0,0 +1,114 @@ +/* + * 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 "test" + +#include <gtest/gtest.h> +#include <log/log.h> + +#include "bluetooth/log.h" +#include "truncating_buffer.h" + +/// Captures the latest message generated by the android vlog +/// implementation. +static std::optional<__android_log_message> androidLogMessage; + +/// Mask the implementation from liblog. +int __android_log_is_loggable(int /*prio*/, const char* /*tag*/, + int /*default_prio*/) { + return true; +} + +/// Mask the implementation from liblog. +void __android_log_write_log_message( + struct __android_log_message* log_message) { + if (log_message != nullptr) { + log_message->message = strdup(log_message->message); + androidLogMessage.emplace(*log_message); + } +} + +using namespace bluetooth; + +TEST(BluetoothLoggerTest, verbose) { + androidLogMessage.reset(); + + log::verbose("verbose test"); + + ASSERT_TRUE(androidLogMessage.has_value()); + EXPECT_EQ(androidLogMessage->priority, ANDROID_LOG_VERBOSE); + EXPECT_STREQ(androidLogMessage->tag, LOG_TAG); + EXPECT_STREQ(androidLogMessage->file, + "packages/modules/Bluetooth/system/log/src/vlog_test.cc"); + EXPECT_EQ(androidLogMessage->line, 49); + EXPECT_STREQ(androidLogMessage->message, "TestBody: verbose test"); +} + +TEST(BluetoothLoggerTest, debug) { + androidLogMessage.reset(); + + log::debug("debug test"); + + ASSERT_TRUE(androidLogMessage.has_value()); + EXPECT_EQ(androidLogMessage->priority, ANDROID_LOG_DEBUG); + EXPECT_STREQ(androidLogMessage->tag, LOG_TAG); + EXPECT_STREQ(androidLogMessage->file, + "packages/modules/Bluetooth/system/log/src/vlog_test.cc"); + EXPECT_EQ(androidLogMessage->line, 63); + EXPECT_STREQ(androidLogMessage->message, "TestBody: debug test"); +} + +TEST(BluetoothLoggerTest, info) { + androidLogMessage.reset(); + + log::info("info test"); + + ASSERT_TRUE(androidLogMessage.has_value()); + EXPECT_EQ(androidLogMessage->priority, ANDROID_LOG_INFO); + EXPECT_STREQ(androidLogMessage->tag, LOG_TAG); + EXPECT_STREQ(androidLogMessage->file, + "packages/modules/Bluetooth/system/log/src/vlog_test.cc"); + EXPECT_EQ(androidLogMessage->line, 77); + EXPECT_STREQ(androidLogMessage->message, "TestBody: info test"); +} + +TEST(BluetoothLoggerTest, warn) { + androidLogMessage.reset(); + + log::warn("warn test"); + + ASSERT_TRUE(androidLogMessage.has_value()); + EXPECT_EQ(androidLogMessage->priority, ANDROID_LOG_WARN); + EXPECT_STREQ(androidLogMessage->tag, LOG_TAG); + EXPECT_STREQ(androidLogMessage->file, + "packages/modules/Bluetooth/system/log/src/vlog_test.cc"); + EXPECT_EQ(androidLogMessage->line, 91); + EXPECT_STREQ(androidLogMessage->message, "TestBody: warn test"); +} + +TEST(BluetoothLoggerTest, error) { + androidLogMessage.reset(); + + log::error("error test"); + + ASSERT_TRUE(androidLogMessage.has_value()); + EXPECT_EQ(androidLogMessage->priority, ANDROID_LOG_ERROR); + EXPECT_STREQ(androidLogMessage->tag, LOG_TAG); + EXPECT_STREQ(androidLogMessage->file, + "packages/modules/Bluetooth/system/log/src/vlog_test.cc"); + EXPECT_EQ(androidLogMessage->line, 105); + EXPECT_STREQ(androidLogMessage->message, "TestBody: error test"); +} diff --git a/system/main/Android.bp b/system/main/Android.bp index 9f1fab3592..efcce95a30 100644 --- a/system/main/Android.bp +++ b/system/main/Android.bp @@ -54,6 +54,7 @@ cc_library_static { min_sdk_version: "Tiramisu", static_libs: [ "libbluetooth_gd", + "libbluetooth_log", "libbt-platform-protos-lite", "libbt_shim_bridge", ], @@ -148,6 +149,7 @@ cc_library_static { ], header_libs: ["libbluetooth_headers"], static_libs: [ + "libbluetooth_log", "libbt-platform-protos-lite", "libbt_shim_bridge", ], @@ -177,6 +179,7 @@ cc_test { ":TestMockBta", ":TestMockBtif", ":TestMockBtu", + ":TestMockJni", ":TestMockLegacyHciCommands", ":TestMockLegacyHciInterface", ":TestMockMainShimEntry", @@ -209,6 +212,7 @@ cc_test { "libbluetooth_crypto_toolbox", "libbluetooth_gd", "libbluetooth_hci_pdl", + "libbluetooth_log", "libbt-common", "libbt-platform-protos-lite", "libbt_shim_bridge", diff --git a/system/main/BUILD.gn b/system/main/BUILD.gn index 6ae221d78a..d2e25f742c 100644 --- a/system/main/BUILD.gn +++ b/system/main/BUILD.gn @@ -83,6 +83,7 @@ target(lib_type, "bluetooth") { "//bt/system/embdrv/g722", "//bt/system/embdrv/sbc", "//bt/system/gd:libbluetooth_gd", + "//bt/system/log:libbluetooth_log", "//bt/system/hci", "//bt/system/main/shim:LibBluetoothShimSources", "//bt/system/osi", @@ -105,6 +106,7 @@ target(lib_type, "bluetooth") { libs = [ "dl", + "fmt", "pthread", "resolv", "rt", diff --git a/system/main/shim/acl.cc b/system/main/shim/acl.cc index e34eea7240..cd6339b12c 100644 --- a/system/main/shim/acl.cc +++ b/system/main/shim/acl.cc @@ -542,7 +542,7 @@ class ClassicShimAclConnection TRY_POSTING_ON_MAIN(interface_.on_change_connection_link_key_complete); } - void OnReadClockOffsetComplete(uint16_t clock_offset) override { + void OnReadClockOffsetComplete(uint16_t /* clock_offset */) override { LOG_INFO("UNIMPLEMENTED"); } @@ -563,66 +563,73 @@ class ClassicShimAclConnection minimum_remote_timeout, minimum_local_timeout); } - void OnQosSetupComplete(hci::ServiceType service_type, uint32_t token_rate, - uint32_t peak_bandwidth, uint32_t latency, - uint32_t delay_variation) override { + void OnQosSetupComplete(hci::ServiceType /* service_type */, + uint32_t /* token_rate */, + uint32_t /* peak_bandwidth */, uint32_t /* latency */, + uint32_t /* delay_variation */) override { LOG_INFO("UNIMPLEMENTED"); } - void OnFlowSpecificationComplete(hci::FlowDirection flow_direction, - hci::ServiceType service_type, - uint32_t token_rate, - uint32_t token_bucket_size, - uint32_t peak_bandwidth, - uint32_t access_latency) override { + void OnFlowSpecificationComplete(hci::FlowDirection /* flow_direction */, + hci::ServiceType /* service_type */, + uint32_t /* token_rate */, + uint32_t /* token_bucket_size */, + uint32_t /* peak_bandwidth */, + uint32_t /* access_latency */) override { LOG_INFO("UNIMPLEMENTED"); } void OnFlushOccurred() override { LOG_INFO("UNIMPLEMENTED"); } - void OnRoleDiscoveryComplete(hci::Role current_role) override { + void OnRoleDiscoveryComplete(hci::Role /* current_role */) override { LOG_INFO("UNIMPLEMENTED"); } void OnReadLinkPolicySettingsComplete( - uint16_t link_policy_settings) override { + uint16_t /* link_policy_settings */) override { LOG_INFO("UNIMPLEMENTED"); } - void OnReadAutomaticFlushTimeoutComplete(uint16_t flush_timeout) override { + void OnReadAutomaticFlushTimeoutComplete( + uint16_t /* flush_timeout */) override { LOG_INFO("UNIMPLEMENTED"); } - void OnReadTransmitPowerLevelComplete(uint8_t transmit_power_level) override { + void OnReadTransmitPowerLevelComplete( + uint8_t /* transmit_power_level */) override { LOG_INFO("UNIMPLEMENTED"); } void OnReadLinkSupervisionTimeoutComplete( - uint16_t link_supervision_timeout) override { + uint16_t /* link_supervision_timeout */) override { LOG_INFO("UNIMPLEMENTED"); } void OnReadFailedContactCounterComplete( - uint16_t failed_contact_counter) override { + uint16_t /* failed_contact_counter */) override { LOG_INFO("UNIMPLEMENTED"); } - void OnReadLinkQualityComplete(uint8_t link_quality) override { + void OnReadLinkQualityComplete(uint8_t /* link_quality */) override { LOG_INFO("UNIMPLEMENTED"); } void OnReadAfhChannelMapComplete( - hci::AfhMode afh_mode, std::array<uint8_t, 10> afh_channel_map) override { + hci::AfhMode /* afh_mode */, + std::array<uint8_t, 10> /* afh_channel_map */) override { LOG_INFO("UNIMPLEMENTED"); } - void OnReadRssiComplete(uint8_t rssi) override { LOG_INFO("UNIMPLEMENTED"); } + void OnReadRssiComplete(uint8_t /* rssi */) override { + LOG_INFO("UNIMPLEMENTED"); + } - void OnReadClockComplete(uint32_t clock, uint16_t accuracy) override { + void OnReadClockComplete(uint32_t /* clock */, + uint16_t /* accuracy */) override { LOG_INFO("UNIMPLEMENTED"); } - void OnCentralLinkKeyComplete(hci::KeyFlag key_flag) override { + void OnCentralLinkKeyComplete(hci::KeyFlag /* key_flag */) override { LOG_INFO("%s UNIMPLEMENTED", __func__); } @@ -807,8 +814,8 @@ class LeShimAclConnection manufacturer_name, sub_version); } - void OnLeReadRemoteFeaturesComplete(hci::ErrorCode hci_status, - uint64_t features) { + void OnLeReadRemoteFeaturesComplete(hci::ErrorCode /* hci_status */, + uint64_t /* features */) { // TODO } diff --git a/system/main/shim/acl_api.cc b/system/main/shim/acl_api.cc index e8d8b4c701..b9efc6b847 100644 --- a/system/main/shim/acl_api.cc +++ b/system/main/shim/acl_api.cc @@ -177,7 +177,7 @@ void bluetooth::shim::ACL_LeSubrateRequest( void bluetooth::shim::ACL_RemoteNameRequest(const RawAddress& addr, uint8_t page_scan_rep_mode, - uint8_t page_scan_mode, + uint8_t /* page_scan_mode */, uint16_t clock_offset) { bluetooth::shim::GetRemoteNameRequest()->StartRemoteNameRequest( ToGdAddress(addr), diff --git a/system/main/shim/ble_scanner_interface_impl.h b/system/main/shim/ble_scanner_interface_impl.h index 2d2401cac0..8a952405c4 100644 --- a/system/main/shim/ble_scanner_interface_impl.h +++ b/system/main/shim/ble_scanner_interface_impl.h @@ -74,8 +74,8 @@ class BleScannerInterfaceImpl : public ::BleScannerInterface, MsftAdvMonitorRemoveCallback cb) override; void MsftAdvMonitorEnable(bool enable, MsftAdvMonitorEnableCallback cb) override; - void SetScanParameters(int scanner_id, int scan_interval, int scan_window, - Callback cb) override; + void SetScanParameters(int scanner_id, uint8_t scan_type, int scan_interval, + int scan_window, Callback cb) override; void BatchscanConfigStorage(int client_if, int batch_scan_full_max, int batch_scan_trunc_max, int batch_scan_notify_threshold, diff --git a/system/main/shim/btm.cc b/system/main/shim/btm.cc index 596ae374d0..3ea07ce004 100644 --- a/system/main/shim/btm.cc +++ b/system/main/shim/btm.cc @@ -26,16 +26,16 @@ #include <cstring> #include <mutex> +#include "hci/acl_manager.h" +#include "hci/controller_interface.h" #include "hci/le_advertising_manager.h" #include "hci/le_scanning_manager.h" -#include "main/shim/controller.h" #include "main/shim/entry.h" #include "main/shim/helpers.h" #include "neighbor/connectability.h" #include "neighbor/discoverability.h" #include "neighbor/inquiry.h" #include "neighbor/page.h" -#include "security/security_module.h" #include "stack/btm/btm_dev.h" #include "stack/btm/btm_int_types.h" #include "types/ble_address_with_type.h" @@ -86,16 +86,17 @@ std::string Btm::ReadRemoteName::AddressString() const { } void Btm::ScanningCallbacks::OnScannerRegistered( - const bluetooth::hci::Uuid app_uuid, bluetooth::hci::ScannerId scanner_id, - ScanningStatus status){}; + const bluetooth::hci::Uuid /* app_uuid */, + bluetooth::hci::ScannerId /* scanner_id */, ScanningStatus /* status */){}; void Btm::ScanningCallbacks::OnSetScannerParameterComplete( - bluetooth::hci::ScannerId scanner_id, ScanningStatus status){}; + bluetooth::hci::ScannerId /* scanner_id */, ScanningStatus /* status */){}; void Btm::ScanningCallbacks::OnScanResult( - uint16_t event_type, uint8_t address_type, bluetooth::hci::Address address, - uint8_t primary_phy, uint8_t secondary_phy, uint8_t advertising_sid, - int8_t tx_power, int8_t rssi, uint16_t periodic_advertising_interval, + uint16_t /* event_type */, uint8_t address_type, + bluetooth::hci::Address address, uint8_t primary_phy, uint8_t secondary_phy, + uint8_t advertising_sid, int8_t tx_power, int8_t rssi, + uint16_t periodic_advertising_interval, std::vector<uint8_t> advertising_data) { tBLE_ADDR_TYPE ble_address_type = to_ble_addr_type(address_type); uint16_t extended_event_type = 0; @@ -118,34 +119,37 @@ void Btm::ScanningCallbacks::OnScanResult( } void Btm::ScanningCallbacks::OnTrackAdvFoundLost( - bluetooth::hci::AdvertisingFilterOnFoundOnLostInfo on_found_on_lost_info){}; -void Btm::ScanningCallbacks::OnBatchScanReports(int client_if, int status, - int report_format, - int num_records, - std::vector<uint8_t> data){}; + bluetooth::hci:: + AdvertisingFilterOnFoundOnLostInfo /* on_found_on_lost_info */){}; +void Btm::ScanningCallbacks::OnBatchScanReports( + int /* client_if */, int /* status */, int /* report_format */, + int /* num_records */, std::vector<uint8_t> /* data */){}; -void Btm::ScanningCallbacks::OnBatchScanThresholdCrossed(int client_if){}; +void Btm::ScanningCallbacks::OnBatchScanThresholdCrossed(int /* client_if */){}; void Btm::ScanningCallbacks::OnTimeout(){}; -void Btm::ScanningCallbacks::OnFilterEnable(bluetooth::hci::Enable enable, - uint8_t status){}; +void Btm::ScanningCallbacks::OnFilterEnable(bluetooth::hci::Enable /* enable */, + uint8_t /* status */){}; void Btm::ScanningCallbacks::OnFilterParamSetup( - uint8_t available_spaces, bluetooth::hci::ApcfAction action, - uint8_t status){}; + uint8_t /* available_spaces */, bluetooth::hci::ApcfAction /* action */, + uint8_t /* status */){}; void Btm::ScanningCallbacks::OnFilterConfigCallback( - bluetooth::hci::ApcfFilterType filter_type, uint8_t available_spaces, - bluetooth::hci::ApcfAction action, uint8_t status){}; + bluetooth::hci::ApcfFilterType /* filter_type */, + uint8_t /* available_spaces */, bluetooth::hci::ApcfAction /* action */, + uint8_t /* status */){}; void Btm::ScanningCallbacks::OnPeriodicSyncStarted( - int reg_id, uint8_t status, uint16_t sync_handle, uint8_t advertising_sid, - bluetooth::hci::AddressWithType address_with_type, uint8_t phy, - uint16_t interval) {} -void Btm::ScanningCallbacks::OnPeriodicSyncReport(uint16_t sync_handle, - int8_t tx_power, int8_t rssi, - uint8_t status, - std::vector<uint8_t> data) {} -void Btm::ScanningCallbacks::OnPeriodicSyncLost(uint16_t sync_handle) {} + int /* reg_id */, uint8_t /* status */, uint16_t /* sync_handle */, + uint8_t /* advertising_sid */, + bluetooth::hci::AddressWithType /* address_with_type */, uint8_t /* phy */, + uint16_t /* interval */) {} +void Btm::ScanningCallbacks::OnPeriodicSyncReport( + uint16_t /* sync_handle */, int8_t /* tx_power */, int8_t /* rssi */, + uint8_t /* status */, std::vector<uint8_t> /* data */) {} +void Btm::ScanningCallbacks::OnPeriodicSyncLost(uint16_t /* sync_handle */) {} void Btm::ScanningCallbacks::OnPeriodicSyncTransferred( - int pa_source, uint8_t status, bluetooth::hci::Address address) {} -void Btm::ScanningCallbacks::OnBigInfoReport(uint16_t sync_handle, bool encrypted) {} + int /* pa_source */, uint8_t /* status */, + bluetooth::hci::Address /* address */) {} +void Btm::ScanningCallbacks::OnBigInfoReport(uint16_t /* sync_handle */, + bool /* encrypted */) {} Btm::Btm(os::Handler* handler, neighbor::InquiryModule* inquiry) : scanning_timer_(handler), observing_timer_(handler) { @@ -241,7 +245,7 @@ bool Btm::IsLimitedInquiryActive() const { return limited_inquiry_active_; } bool Btm::StartPeriodicInquiry(uint8_t mode, uint8_t duration, uint8_t max_responses, uint16_t max_delay, uint16_t min_delay, - tBTM_INQ_RESULTS_CB* p_results_cb) { + tBTM_INQ_RESULTS_CB* /* p_results_cb */) { switch (mode) { case kInquiryModeOff: limited_periodic_inquiry_active_ = false; @@ -393,8 +397,8 @@ bool Btm::UseLeLink(const RawAddress& raw_address) const { return true; } -BtmStatus Btm::ReadClassicRemoteDeviceName(const RawAddress& raw_address, - tBTM_NAME_CMPL_CB* callback) { +BtmStatus Btm::ReadClassicRemoteDeviceName(const RawAddress& /* raw_address */, + tBTM_NAME_CMPL_CB* /* callback */) { LOG_ALWAYS_FATAL("unreachable"); return BTM_UNDEFINED; } @@ -444,7 +448,7 @@ void Btm::SetObservingTimer(uint64_t duration_ms, void Btm::CancelObservingTimer() { observing_timer_.Cancel(); } -void Btm::StartScanning(bool use_active_scanning) { +void Btm::StartScanning(bool /* use_active_scanning */) { GetScanning()->RegisterScanningCallback(&scanning_callbacks_); GetScanning()->Scan(true); } diff --git a/system/main/shim/controller.cc b/system/main/shim/controller.cc index 193ebb80a0..c6bfc0f68f 100644 --- a/system/main/shim/controller.cc +++ b/system/main/shim/controller.cc @@ -232,7 +232,7 @@ FORWARD_GETTER( FORWARD_GETTER(uint8_t, get_le_connect_list_size, GetController()->GetLeFilterAcceptListSize()) -static void set_ble_resolving_list_max_size(int resolving_list_max_size) { +static void set_ble_resolving_list_max_size(int /* resolving_list_max_size */) { LOG_DEBUG("UNSUPPORTED"); } diff --git a/system/main/shim/hci_layer.cc b/system/main/shim/hci_layer.cc index c6278598b1..b3307692b1 100644 --- a/system/main/shim/hci_layer.cc +++ b/system/main/shim/hci_layer.cc @@ -25,8 +25,6 @@ #include "common/bidi_queue.h" #include "common/init_flags.h" -#include "hci/acl_connection_interface.h" -#include "hci/controller_interface.h" #include "hci/hci_layer.h" #include "hci/hci_packets.h" #include "hci/include/packet_fragmenter.h" @@ -61,49 +59,31 @@ static base::Callback<void(const base::Location&, BT_HDR*)> send_data_upwards; static const packet_fragmenter_t* packet_fragmenter; namespace { -bool is_valid_event_code(bluetooth::hci::EventCode event_code) { +bool register_event_code(bluetooth::hci::EventCode event_code) { switch (event_code) { + // Inquiry case bluetooth::hci::EventCode::INQUIRY_COMPLETE: case bluetooth::hci::EventCode::INQUIRY_RESULT: - case bluetooth::hci::EventCode::AUTHENTICATION_COMPLETE: + case bluetooth::hci::EventCode::INQUIRY_RESULT_WITH_RSSI: + case bluetooth::hci::EventCode::EXTENDED_INQUIRY_RESULT: + + // SCO + case bluetooth::hci::EventCode::SYNCHRONOUS_CONNECTION_COMPLETE: + case bluetooth::hci::EventCode::SYNCHRONOUS_CONNECTION_CHANGED: + + // SecurityEvents case bluetooth::hci::EventCode::ENCRYPTION_CHANGE: - case bluetooth::hci::EventCode::CHANGE_CONNECTION_LINK_KEY_COMPLETE: - case bluetooth::hci::EventCode::CENTRAL_LINK_KEY_COMPLETE: - case bluetooth::hci::EventCode::READ_REMOTE_SUPPORTED_FEATURES_COMPLETE: - case bluetooth::hci::EventCode::QOS_SETUP_COMPLETE: - case bluetooth::hci::EventCode::HARDWARE_ERROR: - case bluetooth::hci::EventCode::FLUSH_OCCURRED: - case bluetooth::hci::EventCode::ROLE_CHANGE: - case bluetooth::hci::EventCode::NUMBER_OF_COMPLETED_PACKETS: - case bluetooth::hci::EventCode::MODE_CHANGE: - case bluetooth::hci::EventCode::RETURN_LINK_KEYS: case bluetooth::hci::EventCode::PIN_CODE_REQUEST: case bluetooth::hci::EventCode::LINK_KEY_REQUEST: case bluetooth::hci::EventCode::LINK_KEY_NOTIFICATION: - case bluetooth::hci::EventCode::LOOPBACK_COMMAND: - case bluetooth::hci::EventCode::DATA_BUFFER_OVERFLOW: - case bluetooth::hci::EventCode::READ_CLOCK_OFFSET_COMPLETE: - case bluetooth::hci::EventCode::CONNECTION_PACKET_TYPE_CHANGED: - case bluetooth::hci::EventCode::QOS_VIOLATION: - case bluetooth::hci::EventCode::FLOW_SPECIFICATION_COMPLETE: - case bluetooth::hci::EventCode::INQUIRY_RESULT_WITH_RSSI: - case bluetooth::hci::EventCode::READ_REMOTE_EXTENDED_FEATURES_COMPLETE: - case bluetooth::hci::EventCode::SYNCHRONOUS_CONNECTION_COMPLETE: - case bluetooth::hci::EventCode::SYNCHRONOUS_CONNECTION_CHANGED: - case bluetooth::hci::EventCode::SNIFF_SUBRATING: - case bluetooth::hci::EventCode::EXTENDED_INQUIRY_RESULT: case bluetooth::hci::EventCode::ENCRYPTION_KEY_REFRESH_COMPLETE: case bluetooth::hci::EventCode::IO_CAPABILITY_REQUEST: case bluetooth::hci::EventCode::IO_CAPABILITY_RESPONSE: - case bluetooth::hci::EventCode::USER_CONFIRMATION_REQUEST: - case bluetooth::hci::EventCode::USER_PASSKEY_REQUEST: case bluetooth::hci::EventCode::REMOTE_OOB_DATA_REQUEST: case bluetooth::hci::EventCode::SIMPLE_PAIRING_COMPLETE: - case bluetooth::hci::EventCode::LINK_SUPERVISION_TIMEOUT_CHANGED: - case bluetooth::hci::EventCode::ENHANCED_FLUSH_COMPLETE: case bluetooth::hci::EventCode::USER_PASSKEY_NOTIFICATION: - case bluetooth::hci::EventCode::KEYPRESS_NOTIFICATION: - case bluetooth::hci::EventCode::NUMBER_OF_COMPLETED_DATA_BLOCKS: + case bluetooth::hci::EventCode::USER_CONFIRMATION_REQUEST: + case bluetooth::hci::EventCode::USER_PASSKEY_REQUEST: return true; default: return false; @@ -152,26 +132,6 @@ bool is_valid_subevent_code(bluetooth::hci::SubeventCode subevent_code) { } } -static bool event_already_registered_in_controller_layer( - bluetooth::hci::EventCode event_code) { - switch (event_code) { - case bluetooth::hci::EventCode::NUMBER_OF_COMPLETED_PACKETS: - return true; - default: - return false; - } -} - -static bool event_already_registered_in_acl_layer( - bluetooth::hci::EventCode event_code) { - for (auto event : bluetooth::hci::AclConnectionEvents) { - if (event == event_code) { - return true; - } - } - return false; -} - static bool subevent_already_registered_in_le_hci_layer( bluetooth::hci::SubeventCode subevent_code) { switch (subevent_code) { @@ -484,15 +444,9 @@ void bluetooth::shim::hci_on_reset_complete() { for (uint16_t event_code_raw = 0; event_code_raw < 0x100; event_code_raw++) { auto event_code = static_cast<bluetooth::hci::EventCode>(event_code_raw); - if (!is_valid_event_code(event_code)) { + if (!register_event_code(event_code)) { continue; } - if (event_already_registered_in_acl_layer(event_code)) { - continue; - } else if (event_already_registered_in_controller_layer(event_code)) { - continue; - } - cpp::register_event(event_code); } diff --git a/system/main/shim/le_advertising_manager.cc b/system/main/shim/le_advertising_manager.cc index b19f99de86..a1ec02f05e 100644 --- a/system/main/shim/le_advertising_manager.cc +++ b/system/main/shim/le_advertising_manager.cc @@ -93,7 +93,7 @@ class BleAdvertiserInterfaceImpl : public BleAdvertiserInterface, } void SetParameters(uint8_t advertiser_id, AdvertiseParameters params, - ParametersCallback cb) override { + ParametersCallback /* cb */) override { LOG(INFO) << __func__ << " in shim layer"; bluetooth::hci::AdvertisingConfig config{}; parse_parameter(config, params); @@ -101,7 +101,7 @@ class BleAdvertiserInterfaceImpl : public BleAdvertiserInterface, } void SetData(int advertiser_id, bool set_scan_rsp, vector<uint8_t> data, - StatusCallback cb) override { + StatusCallback /* cb */) override { LOG(INFO) << __func__ << " in shim layer"; std::vector<GapData> advertising_data = {}; parse_gap_data(data, advertising_data); @@ -109,9 +109,9 @@ class BleAdvertiserInterfaceImpl : public BleAdvertiserInterface, advertising_data); } - void Enable(uint8_t advertiser_id, bool enable, StatusCallback cb, + void Enable(uint8_t advertiser_id, bool enable, StatusCallback /* cb */, uint16_t duration, uint8_t maxExtAdvEvents, - StatusCallback timeout_cb) override { + StatusCallback /* timeout_cb */) override { LOG(INFO) << __func__ << " in shim layer"; bluetooth::shim::GetAdvertising()->EnableAdvertiser( advertiser_id, enable, duration, maxExtAdvEvents); @@ -137,14 +137,14 @@ class BleAdvertiserInterfaceImpl : public BleAdvertiserInterface, } void StartAdvertisingSet(uint8_t client_id, int reg_id, - IdTxPowerStatusCallback register_cb, + IdTxPowerStatusCallback /* register_cb */, AdvertiseParameters params, std::vector<uint8_t> advertise_data, std::vector<uint8_t> scan_response_data, PeriodicAdvertisingParameters periodic_params, std::vector<uint8_t> periodic_data, uint16_t duration, uint8_t maxExtAdvEvents, - IdStatusCallback timeout_cb) { + IdStatusCallback /* timeout_cb */) { LOG(INFO) << __func__ << " in shim layer"; bluetooth::hci::AdvertisingConfig config{}; @@ -175,7 +175,7 @@ class BleAdvertiserInterfaceImpl : public BleAdvertiserInterface, void SetPeriodicAdvertisingParameters( int advertiser_id, PeriodicAdvertisingParameters periodic_params, - StatusCallback cb) override { + StatusCallback /* cb */) override { LOG(INFO) << __func__ << " in shim layer"; bluetooth::hci::PeriodicAdvertisingParameters parameters; parameters.max_interval = periodic_params.max_interval; @@ -186,7 +186,7 @@ class BleAdvertiserInterfaceImpl : public BleAdvertiserInterface, } void SetPeriodicAdvertisingData(int advertiser_id, std::vector<uint8_t> data, - StatusCallback cb) override { + StatusCallback /* cb */) override { LOG(INFO) << __func__ << " in shim layer"; std::vector<GapData> advertising_data = {}; parse_gap_data(data, advertising_data); @@ -196,7 +196,7 @@ class BleAdvertiserInterfaceImpl : public BleAdvertiserInterface, void SetPeriodicAdvertisingEnable(int advertiser_id, bool enable, bool include_adi, - StatusCallback cb) override { + StatusCallback /* cb */) override { LOG(INFO) << __func__ << " in shim layer"; bluetooth::shim::GetAdvertising()->EnablePeriodicAdvertising( advertiser_id, enable, include_adi); @@ -211,11 +211,11 @@ class BleAdvertiserInterfaceImpl : public BleAdvertiserInterface, native_adv_callbacks_map_[client_id] = callbacks; } - void on_scan(Address address, AddressType address_type) { + void on_scan(Address /* address */, AddressType /* address_type */) { LOG(INFO) << __func__ << " in shim layer"; } - void on_set_terminated(ErrorCode error_code, uint8_t, uint8_t) { + void on_set_terminated(ErrorCode /* error_code */, uint8_t, uint8_t) { LOG(INFO) << __func__ << " in shim layer"; } diff --git a/system/main/shim/le_scanning_manager.cc b/system/main/shim/le_scanning_manager.cc index 59d83912cb..58d0ef6bce 100644 --- a/system/main/shim/le_scanning_manager.cc +++ b/system/main/shim/le_scanning_manager.cc @@ -62,48 +62,58 @@ constexpr uint16_t kAllowAllFilter = 0x00; constexpr uint16_t kListLogicOr = 0x01; class DefaultScanningCallback : public ::ScanningCallbacks { - void OnScannerRegistered(const bluetooth::Uuid app_uuid, uint8_t scanner_id, - uint8_t status) override { + void OnScannerRegistered(const bluetooth::Uuid /* app_uuid */, + uint8_t /* scanner_id */, + uint8_t /* status */) override { LogUnused(); } - void OnSetScannerParameterComplete(uint8_t scanner_id, - uint8_t status) override { + void OnSetScannerParameterComplete(uint8_t /* scanner_id */, + uint8_t /* status */) override { LogUnused(); } - void OnScanResult(uint16_t event_type, uint8_t address_type, RawAddress bda, - uint8_t primary_phy, uint8_t secondary_phy, - uint8_t advertising_sid, int8_t tx_power, int8_t rssi, - uint16_t periodic_advertising_interval, - std::vector<uint8_t> advertising_data) override { + void OnScanResult(uint16_t /* event_type */, uint8_t /* address_type */, + RawAddress /* bda */, uint8_t /* primary_phy */, + uint8_t /* secondary_phy */, uint8_t /* advertising_sid */, + int8_t /* tx_power */, int8_t /* rssi */, + uint16_t /* periodic_advertising_interval */, + std::vector<uint8_t> /* advertising_data */) override { LogUnused(); } void OnTrackAdvFoundLost( - AdvertisingTrackInfo advertising_track_info) override { + AdvertisingTrackInfo /* advertising_track_info */) override { LogUnused(); } - void OnBatchScanReports(int client_if, int status, int report_format, - int num_records, std::vector<uint8_t> data) override { + void OnBatchScanReports(int /* client_if */, int /* status */, + int /* report_format */, int /* num_records */, + std::vector<uint8_t> /* data */) override { LogUnused(); } - void OnBatchScanThresholdCrossed(int client_if) override { LogUnused(); } - void OnPeriodicSyncStarted(int reg_id, uint8_t status, uint16_t sync_handle, - uint8_t advertising_sid, uint8_t address_type, - RawAddress address, uint8_t phy, - uint16_t interval) override { + void OnBatchScanThresholdCrossed(int /* client_if */) override { + LogUnused(); + } + void OnPeriodicSyncStarted(int /* reg_id */, uint8_t /* status */, + uint16_t /* sync_handle */, + uint8_t /* advertising_sid */, + uint8_t /* address_type */, + RawAddress /* address */, uint8_t /* phy */, + uint16_t /* interval */) override { LogUnused(); }; - void OnPeriodicSyncReport(uint16_t sync_handle, int8_t tx_power, int8_t rssi, - uint8_t status, - std::vector<uint8_t> data) override { + void OnPeriodicSyncReport(uint16_t /* sync_handle */, int8_t /* tx_power */, + int8_t /* rssi */, uint8_t /* status */, + std::vector<uint8_t> /* data */) override { LogUnused(); }; - void OnPeriodicSyncLost(uint16_t sync_handle) override { LogUnused(); }; - void OnPeriodicSyncTransferred(int pa_source, uint8_t status, - RawAddress address) override { + void OnPeriodicSyncLost(uint16_t /* sync_handle */) override { LogUnused(); }; + void OnPeriodicSyncTransferred(int /* pa_source */, uint8_t /* status */, + RawAddress /* address */) override { LogUnused(); }; - void OnBigInfoReport(uint16_t sync_handle, bool encrypted) override {LogUnused(); }; + void OnBigInfoReport(uint16_t /* sync_handle */, + bool /* encrypted */) override { + LogUnused(); + }; private: static void LogUnused() { @@ -255,8 +265,8 @@ void BleScannerInterfaceImpl::ScanFilterAdd(int filter_index, } /** Clear all scan filter conditions for specific filter index*/ -void BleScannerInterfaceImpl::ScanFilterClear(int filter_index, - FilterConfigCallback cb) { +void BleScannerInterfaceImpl::ScanFilterClear(int /* filter_index */, + FilterConfigCallback /* cb */) { LOG(INFO) << __func__ << " in shim layer"; // This function doesn't used in java layer } @@ -339,8 +349,10 @@ void BleScannerInterfaceImpl::OnMsftAdvMonitorEnable( /** Sets the LE scan interval and window in units of N*0.625 msec */ void BleScannerInterfaceImpl::SetScanParameters(int scanner_id, + uint8_t scan_type, int scan_interval, - int scan_window, Callback cb) { + int scan_window, + Callback /* cb */) { LOG(INFO) << __func__ << " in shim layer"; if (BTM_BLE_ISVALID_PARAM(scan_interval, BTM_BLE_SCAN_INT_MIN, BTM_BLE_EXT_SCAN_INT_MAX) && @@ -351,10 +363,9 @@ void BleScannerInterfaceImpl::SetScanParameters(int scanner_id, btm_cb.ble_ctr_cb.inq_var.scan_window = scan_window; } - // use active scan - auto scan_type = static_cast<bluetooth::hci::LeScanType>(0x01); - bluetooth::shim::GetScanning()->SetScanParameters(scanner_id, scan_type, - scan_interval, scan_window); + bluetooth::shim::GetScanning()->SetScanParameters( + scanner_id, static_cast<bluetooth::hci::LeScanType>(scan_type), + scan_interval, scan_window); } /* Configure the batchscan storage */ @@ -371,7 +382,8 @@ void BleScannerInterfaceImpl::BatchscanConfigStorage( /* Enable batchscan */ void BleScannerInterfaceImpl::BatchscanEnable(int scan_mode, int scan_interval, - int scan_window, int addr_type, + int scan_window, + int /* addr_type */, int discard_rule, Callback cb) { LOG(INFO) << __func__ << " in shim layer"; auto batch_scan_mode = static_cast<bluetooth::hci::BatchScanMode>(scan_mode); @@ -653,14 +665,15 @@ void BleScannerInterfaceImpl::OnBigInfoReport(uint16_t sync_handle, bool encrypt } void BleScannerInterfaceImpl::OnTimeout() {} -void BleScannerInterfaceImpl::OnFilterEnable(bluetooth::hci::Enable enable, - uint8_t status) {} +void BleScannerInterfaceImpl::OnFilterEnable( + bluetooth::hci::Enable /* enable */, uint8_t /* status */) {} void BleScannerInterfaceImpl::OnFilterParamSetup( - uint8_t available_spaces, bluetooth::hci::ApcfAction action, - uint8_t status) {} + uint8_t /* available_spaces */, bluetooth::hci::ApcfAction /* action */, + uint8_t /* status */) {} void BleScannerInterfaceImpl::OnFilterConfigCallback( - bluetooth::hci::ApcfFilterType filter_type, uint8_t available_spaces, - bluetooth::hci::ApcfAction action, uint8_t status) {} + bluetooth::hci::ApcfFilterType /* filter_type */, + uint8_t /* available_spaces */, bluetooth::hci::ApcfAction /* action */, + uint8_t /* status */) {} bool BleScannerInterfaceImpl::parse_filter_command( bluetooth::hci::AdvertisingPacketContentFilterCommand& diff --git a/system/osi/Android.bp b/system/osi/Android.bp index 33feacea61..beef0f61aa 100644 --- a/system/osi/Android.bp +++ b/system/osi/Android.bp @@ -92,6 +92,7 @@ cc_library_static { ], header_libs: ["libbluetooth_headers"], static_libs: [ + "libbluetooth_log", "libbt-platform-protos-lite", "libbt_shim_bridge", ], @@ -139,6 +140,7 @@ cc_test { "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt_shim_bridge", "libbt_shim_ffi", diff --git a/system/packet/Android.bp b/system/packet/Android.bp index 6fa932d7b7..e0bd28ad84 100644 --- a/system/packet/Android.bp +++ b/system/packet/Android.bp @@ -78,6 +78,7 @@ cc_test { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], diff --git a/system/packet/BUILD.gn b/system/packet/BUILD.gn index 3a4dc5ca48..a6f8f2560c 100644 --- a/system/packet/BUILD.gn +++ b/system/packet/BUILD.gn @@ -22,7 +22,10 @@ config("packet_config") { "//bt/system/profile/avrcp", ] - configs = [ "//bt/system:target_defaults" ] + configs = [ + "//bt/system:target_defaults", + "//bt/system/log:log_defaults", + ] } static_library("packet") { diff --git a/system/packet/avrcp/Android.bp b/system/packet/avrcp/Android.bp index 4e3190811e..1808112072 100644 --- a/system/packet/avrcp/Android.bp +++ b/system/packet/avrcp/Android.bp @@ -45,6 +45,7 @@ cc_library_static { ], static_libs: [ "lib-bt-packets-base", + "libbluetooth_log", "libchrome", ], apex_available: [ diff --git a/system/packet/tests/fuzzers/Android.bp b/system/packet/tests/fuzzers/Android.bp index ed27340541..a99de59d13 100644 --- a/system/packet/tests/fuzzers/Android.bp +++ b/system/packet/tests/fuzzers/Android.bp @@ -32,6 +32,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -68,6 +69,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -104,6 +106,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -140,6 +143,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -176,6 +180,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -212,6 +217,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -248,6 +254,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -284,6 +291,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -320,6 +328,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -356,6 +365,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -392,6 +402,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -428,6 +439,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -464,6 +476,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -500,6 +513,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -536,6 +550,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -572,6 +587,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -608,6 +624,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -644,6 +661,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -680,6 +698,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -716,6 +735,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -752,6 +772,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -788,6 +809,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -824,6 +846,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -860,6 +883,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], @@ -896,6 +920,7 @@ cc_fuzz { "lib-bt-packets", "lib-bt-packets-avrcp", "lib-bt-packets-base", + "libbluetooth_log", "libchrome", "libgmock", ], diff --git a/system/profile/avrcp/Android.bp b/system/profile/avrcp/Android.bp index 5d3c58e48f..f664baa0fd 100644 --- a/system/profile/avrcp/Android.bp +++ b/system/profile/avrcp/Android.bp @@ -26,6 +26,7 @@ cc_library_static { static_libs: [ "lib-bt-packets", "libbluetooth-types", + "libbluetooth_log", "libbt_shim_bridge", "libosi", ], @@ -71,6 +72,7 @@ cc_test { "libbase", "libbluetooth-types", "libbluetooth_gd", + "libbluetooth_log", "libbt_shim_bridge", "libbt_shim_ffi", "libbtdevice", @@ -115,6 +117,7 @@ cc_fuzz { "libbase", "libbluetooth-types", "libbluetooth_gd", + "libbluetooth_log", "libbt_shim_bridge", "libbt_shim_ffi", "libchrome", diff --git a/system/profile/avrcp/BUILD.gn b/system/profile/avrcp/BUILD.gn index 6a8cbbe3e3..788c60e003 100644 --- a/system/profile/avrcp/BUILD.gn +++ b/system/profile/avrcp/BUILD.gn @@ -24,7 +24,10 @@ config("avrcp_config") { "//bt/system/include/hardware/avrcp", ] - configs = ["//bt/system:target_defaults"] + configs = [ + "//bt/system:target_defaults", + "//bt/system/log:log_defaults", + ] } static_library("profile_avrcp") { diff --git a/system/profile/avrcp/avrcp_message_converter.h b/system/profile/avrcp/avrcp_message_converter.h index 0b47f9610f..db6dd4946c 100644 --- a/system/profile/avrcp/avrcp_message_converter.h +++ b/system/profile/avrcp/avrcp_message_converter.h @@ -16,6 +16,8 @@ #pragma once +#include <bluetooth/log.h> + #include <iostream> #include <vector> @@ -98,7 +100,7 @@ class AvrcpMessageConverter { } } break; default: - LOG(ERROR) << "Unknown opcode for AVRCP message"; + bluetooth::log::error("Unknown opcode for AVRCP message"); break; } diff --git a/system/profile/avrcp/connection_handler.cc b/system/profile/avrcp/connection_handler.cc index 04836faaa7..9881e9e6e4 100644 --- a/system/profile/avrcp/connection_handler.cc +++ b/system/profile/avrcp/connection_handler.cc @@ -14,10 +14,12 @@ * limitations under the License. */ +#define LOG_TAG "avrcp" + #include "connection_handler.h" #include <base/functional/bind.h> -#include <base/logging.h> +#include <bluetooth/log.h> #include <map> #include <mutex> @@ -61,11 +63,11 @@ 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) { - LOG(INFO) << "Absolute volume disabled by property"; + log::info("Absolute volume disabled by property"); return false; } if (interop_match_addr(INTEROP_DISABLE_ABSOLUTE_VOLUME, bdaddr)) { - LOG(INFO) << "Absolute volume disabled by IOP table"; + log::info("Absolute volume disabled by IOP table"); return false; } return true; @@ -124,13 +126,13 @@ void ConnectionHandler::InitForTesting(ConnectionHandler* handler) { } bool ConnectionHandler::ConnectDevice(const RawAddress& bdaddr) { - LOG(INFO) << "Attempting to connect to device " - << ADDRESS_TO_LOGGABLE_STR(bdaddr); + log::info("Attempting to connect to device {}", + ADDRESS_TO_LOGGABLE_STR(bdaddr)); for (const auto& pair : device_map_) { if (bdaddr == pair.second->GetAddress()) { - LOG(WARNING) << "Already connected to device with address " - << ADDRESS_TO_LOGGABLE_STR(bdaddr); + log::warn("Already connected to device with address {}", + ADDRESS_TO_LOGGABLE_STR(bdaddr)); return false; } } @@ -138,12 +140,11 @@ bool ConnectionHandler::ConnectDevice(const RawAddress& bdaddr) { auto connection_lambda = [](ConnectionHandler* instance_, const RawAddress& bdaddr, uint16_t status, uint16_t version, uint16_t features) { - LOG(INFO) << __PRETTY_FUNCTION__ - << " SDP Completed features=" << loghex(features); + log::info("SDP Completed features={}", loghex(features)); if (status != AVRC_SUCCESS || !(features & BTA_AV_FEAT_RCCT)) { - LOG(ERROR) << "Failed to do SDP: status=" << loghex(status) - << " features=" << loghex(features) - << " supports controller: " << (features & BTA_AV_FEAT_RCCT); + log::error( + "Failed to do SDP: status={} features={} supports controller: {}", + loghex(status), loghex(features), (features & BTA_AV_FEAT_RCCT)); instance_->connection_cb_.Run(std::shared_ptr<Device>()); } @@ -188,7 +189,7 @@ std::vector<std::shared_ptr<Device>> ConnectionHandler::GetListOfDevices() bool ConnectionHandler::SdpLookup(const RawAddress& bdaddr, SdpCallback cb, bool retry) { - LOG(INFO) << __PRETTY_FUNCTION__; + log::info(""); tAVRC_SDP_DB_PARAMS db_params; // TODO (apanicke): This needs to be replaced with smarter memory management. @@ -212,7 +213,7 @@ bool ConnectionHandler::SdpLookup(const RawAddress& bdaddr, SdpCallback cb, } bool ConnectionHandler::AvrcpConnect(bool initiator, const RawAddress& bdaddr) { - LOG(INFO) << "Connect to device " << ADDRESS_TO_LOGGABLE_STR(bdaddr); + log::info("Connect to device {}", ADDRESS_TO_LOGGABLE_STR(bdaddr)); tAVRC_CONN_CB open_cb; if (initiator) { @@ -234,8 +235,7 @@ bool ConnectionHandler::AvrcpConnect(bool initiator, const RawAddress& bdaddr) { uint8_t handle = 0; uint16_t status = avrc_->Open(&handle, &open_cb, bdaddr); - LOG(INFO) << __PRETTY_FUNCTION__ << ": handle=" << loghex(handle) - << " status= " << loghex(status); + log::info("handle={} status= {}", loghex(handle), loghex(status)); return status == AVRC_SUCCESS; } @@ -244,18 +244,18 @@ void ConnectionHandler::InitiatorControlCb(uint8_t handle, uint8_t event, const RawAddress* peer_addr) { DCHECK(!connection_cb_.is_null()); - LOG(INFO) << __PRETTY_FUNCTION__ << ": handle=" << loghex(handle) - << " result=" << loghex(result) << " addr=" - << (peer_addr ? ADDRESS_TO_LOGGABLE_STR(*peer_addr) : "none"); + log::info("handle={} result={} addr={}", loghex(handle), loghex(result), + (peer_addr ? ADDRESS_TO_LOGGABLE_STR(*peer_addr) : "none")); switch (event) { case AVRC_OPEN_IND_EVT: { - LOG(INFO) << __PRETTY_FUNCTION__ << ": Connection Opened Event"; + log::info("Connection Opened Event"); const auto& feature_iter = feature_map_.find(*peer_addr); if (feature_iter == feature_map_.end()) { - LOG(ERROR) << "Features do not exist even though SDP should have been " - "done first"; + log::error( + "Features do not exist even though SDP should have been " + "done first"); return; } @@ -295,11 +295,10 @@ void ConnectionHandler::InitiatorControlCb(uint8_t handle, uint8_t event, } break; case AVRC_CLOSE_IND_EVT: { - LOG(INFO) << __PRETTY_FUNCTION__ << ": Connection Closed Event"; + log::info("Connection Closed Event"); if (device_map_.find(handle) == device_map_.end()) { - LOG(WARNING) - << "Connection Close received from device that doesn't exist"; + log::warn("Connection Close received from device that doesn't exist"); return; } std::lock_guard<std::recursive_mutex> lock(device_map_lock); @@ -310,13 +309,13 @@ void ConnectionHandler::InitiatorControlCb(uint8_t handle, uint8_t event, } break; case AVRC_BROWSE_OPEN_IND_EVT: { - LOG(INFO) << __PRETTY_FUNCTION__ << ": Browse Open Event"; + log::info("Browse Open Event"); // NOTE (apanicke): We don't need to explicitly handle this message // since the AVCTP Layer will still send us browsing messages // regardless. It would be useful to note this though for future // compatibility issues. if (device_map_.find(handle) == device_map_.end()) { - LOG(WARNING) << "Browse Opened received from device that doesn't exist"; + log::warn("Browse Opened received from device that doesn't exist"); return; } @@ -324,10 +323,10 @@ void ConnectionHandler::InitiatorControlCb(uint8_t handle, uint8_t event, device_map_[handle]->SetBrowseMtu(browse_mtu); } break; case AVRC_BROWSE_CLOSE_IND_EVT: - LOG(INFO) << __PRETTY_FUNCTION__ << ": Browse Close Event"; + log::info("Browse Close Event"); break; default: - LOG(ERROR) << "Unknown AVRCP Control event"; + log::error("Unknown AVRCP Control event"); break; } } @@ -337,19 +336,18 @@ void ConnectionHandler::AcceptorControlCb(uint8_t handle, uint8_t event, const RawAddress* peer_addr) { DCHECK(!connection_cb_.is_null()); - LOG(INFO) << __PRETTY_FUNCTION__ << ": handle=" << loghex(handle) - << " result=" << loghex(result) << " addr=" - << (peer_addr ? ADDRESS_TO_LOGGABLE_STR(*peer_addr) : "none"); + log::info("handle={} result={} addr={}", loghex(handle), loghex(result), + (peer_addr ? ADDRESS_TO_LOGGABLE_STR(*peer_addr) : "none")); switch (event) { case AVRC_OPEN_IND_EVT: { - LOG(INFO) << __PRETTY_FUNCTION__ << ": Connection Opened Event"; + log::info("Connection Opened Event"); if (peer_addr == NULL) { return; } if (btif_av_src_sink_coexist_enabled() && btif_av_peer_is_connected_source(*peer_addr)) { - LOG(WARNING) << "peer is src, close new avrcp cback"; + log::warn("peer is src, close new avrcp cback"); if (device_map_.find(handle) != device_map_.end()) { std::lock_guard<std::recursive_mutex> lock(device_map_lock); feature_map_.erase(device_map_[handle]->GetAddress()); @@ -371,16 +369,14 @@ void ConnectionHandler::AcceptorControlCb(uint8_t handle, uint8_t event, device_map_[handle] = newDevice; connection_cb_.Run(newDevice); - LOG(INFO) << __PRETTY_FUNCTION__ - << ": Performing SDP on connected device. address=" - << ADDRESS_TO_LOGGABLE_STR(*peer_addr); + log::info("Performing SDP on connected device. address={}", + ADDRESS_TO_LOGGABLE_STR(*peer_addr)); auto sdp_lambda = [](ConnectionHandler* instance_, uint8_t handle, uint16_t status, uint16_t version, uint16_t features) { if (instance_->device_map_.find(handle) == instance_->device_map_.end()) { - LOG(WARNING) << __PRETTY_FUNCTION__ - << ": No device found for handle: " << loghex(handle); + log::warn("No device found for handle: {}", loghex(handle)); return; } @@ -406,9 +402,8 @@ void ConnectionHandler::AcceptorControlCb(uint8_t handle, uint8_t event, // SDP search failed, this could be due to a collision between outgoing // and incoming connection. In any case, we need to reject the current // connection. - LOG(ERROR) << __PRETTY_FUNCTION__ - << ": SDP search failed for handle: " << loghex(handle) - << ", closing connection"; + log::error("SDP search failed for handle: {}, closing connection", + loghex(handle)); DisconnectDevice(*peer_addr); } // Open for the next incoming connection. The handle will not be the same @@ -417,11 +412,10 @@ void ConnectionHandler::AcceptorControlCb(uint8_t handle, uint8_t event, } break; case AVRC_CLOSE_IND_EVT: { - LOG(INFO) << __PRETTY_FUNCTION__ << ": Connection Closed Event"; + log::info("Connection Closed Event"); if (device_map_.find(handle) == device_map_.end()) { - LOG(WARNING) - << "Connection Close received from device that doesn't exist"; + log::warn("Connection Close received from device that doesn't exist"); return; } { @@ -434,13 +428,13 @@ void ConnectionHandler::AcceptorControlCb(uint8_t handle, uint8_t event, } break; case AVRC_BROWSE_OPEN_IND_EVT: { - LOG(INFO) << __PRETTY_FUNCTION__ << ": Browse Open Event"; + log::info("Browse Open Event"); // NOTE (apanicke): We don't need to explicitly handle this message // since the AVCTP Layer will still send us browsing messages // regardless. It would be useful to note this though for future // compatibility issues. if (device_map_.find(handle) == device_map_.end()) { - LOG(WARNING) << "Browse Opened received from device that doesn't exist"; + log::warn("Browse Opened received from device that doesn't exist"); return; } @@ -448,10 +442,10 @@ void ConnectionHandler::AcceptorControlCb(uint8_t handle, uint8_t event, device_map_[handle]->SetBrowseMtu(browse_mtu); } break; case AVRC_BROWSE_CLOSE_IND_EVT: - LOG(INFO) << __PRETTY_FUNCTION__ << ": Browse Close Event"; + log::info("Browse Close Event"); break; default: - LOG(ERROR) << "Unknown AVRCP Control event"; + log::error("Unknown AVRCP Control event"); break; } } @@ -459,8 +453,8 @@ void ConnectionHandler::AcceptorControlCb(uint8_t handle, uint8_t event, void ConnectionHandler::MessageCb(uint8_t handle, uint8_t label, uint8_t opcode, tAVRC_MSG* p_msg) { if (device_map_.find(handle) == device_map_.end()) { - LOG(ERROR) << "Message received for unconnected device: handle=" - << loghex(handle); + log::error("Message received for unconnected device: handle={}", + loghex(handle)); return; } @@ -469,31 +463,30 @@ void ConnectionHandler::MessageCb(uint8_t handle, uint8_t label, uint8_t opcode, if (opcode == AVRC_OP_BROWSE) { if (btif_av_src_sink_coexist_enabled() && btif_av_both_enable()) { if (p_msg->browse.hdr.ctype == AVCT_RSP) { - VLOG(2) << "ignore response handle " << (unsigned int)handle; + log::verbose("ignore response handle {}", (unsigned int)handle); return; } } - VLOG(4) << "Browse Message received on handle " << (unsigned int)handle; + log::verbose("Browse Message received on handle {}", (unsigned int)handle); device_map_[handle]->BrowseMessageReceived(label, BrowsePacket::Parse(pkt)); return; } - VLOG(4) << "Message received on handle " << (unsigned int)handle; + log::verbose("Message received on handle {}", (unsigned int)handle); device_map_[handle]->MessageReceived(label, Packet::Parse(pkt)); } void ConnectionHandler::SdpCb(RawAddress bdaddr, SdpCallback cb, tSDP_DISCOVERY_DB* disc_db, bool retry, uint16_t status) { - VLOG(1) << __PRETTY_FUNCTION__ << ": SDP lookup callback received"; + log::verbose("SDP lookup callback received"); if (status == SDP_CONN_FAILED && !retry) { - LOG(WARNING) << __PRETTY_FUNCTION__ << ": SDP Failure retry again"; + log::warn("SDP Failure retry again"); SdpLookup(bdaddr, cb, true); return; } else if (status != AVRC_SUCCESS) { - LOG(ERROR) << __PRETTY_FUNCTION__ - << ": SDP Failure: status = " << (unsigned int)status; + log::error("SDP Failure: status = {}", (unsigned int)status); cb.Run(status, 0, 0); osi_free(disc_db); return; @@ -508,8 +501,8 @@ void ConnectionHandler::SdpCb(RawAddress bdaddr, SdpCallback cb, sdp_record = sdp_->FindServiceInDb(disc_db, UUID_SERVCLASS_AV_REMOTE_CONTROL, nullptr); if (sdp_record != nullptr) { - LOG(INFO) << __PRETTY_FUNCTION__ << ": Device " - << ADDRESS_TO_LOGGABLE_STR(bdaddr) << " supports remote control"; + log::info("Device {} supports remote control", + ADDRESS_TO_LOGGABLE_STR(bdaddr)); peer_features |= BTA_AV_FEAT_RCCT; if ((sdp_->FindAttributeInRec(sdp_record, ATTR_ID_BT_PROFILE_DESC_LIST)) != @@ -517,39 +510,36 @@ void ConnectionHandler::SdpCb(RawAddress bdaddr, SdpCallback cb, /* get profile version (if failure, version parameter is not updated) */ sdp_->FindProfileVersionInRec( sdp_record, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_avrcp_version); - VLOG(1) << __PRETTY_FUNCTION__ << ": Device " - << ADDRESS_TO_LOGGABLE_STR(bdaddr) - << " peer avrcp version=" << loghex(peer_avrcp_version); + log::verbose("Device {} peer avrcp version={}", + ADDRESS_TO_LOGGABLE_STR(bdaddr), loghex(peer_avrcp_version)); if (peer_avrcp_version >= AVRC_REV_1_3) { // These are the standard features, another way to check this is to // search for CAT1 on the remote device - VLOG(1) << __PRETTY_FUNCTION__ << ": Device " - << ADDRESS_TO_LOGGABLE_STR(bdaddr) << " supports metadata"; + log::verbose("Device {} supports metadata", + ADDRESS_TO_LOGGABLE_STR(bdaddr)); peer_features |= (BTA_AV_FEAT_VENDOR | BTA_AV_FEAT_METADATA); } if (peer_avrcp_version >= AVRC_REV_1_4) { /* get supported categories */ - VLOG(1) << __PRETTY_FUNCTION__ << " Get Supported categories"; + log::verbose("Get Supported categories"); tSDP_DISC_ATTR* sdp_attribute = sdp_->FindAttributeInRec(sdp_record, ATTR_ID_SUPPORTED_FEATURES); if (sdp_attribute != NULL && SDP_DISC_ATTR_TYPE(sdp_attribute->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(sdp_attribute->attr_len_type) >= 2) { - VLOG(1) << __PRETTY_FUNCTION__ - << "Get Supported categories SDP ATTRIBUTES != null"; + log::verbose("Get Supported categories SDP ATTRIBUTES != null"); uint16_t categories = sdp_attribute->attr_value.v.u16; if (categories & AVRC_SUPF_CT_CAT2) { - VLOG(1) << __PRETTY_FUNCTION__ << ": Device " - << ADDRESS_TO_LOGGABLE_STR(bdaddr) - << " supports advanced control"; + log::verbose("Device {} supports advanced control", + ADDRESS_TO_LOGGABLE_STR(bdaddr)); if (IsAbsoluteVolumeEnabled(&bdaddr)) { peer_features |= (BTA_AV_FEAT_ADV_CTRL); } } if (categories & AVRC_SUPF_CT_BROWSE) { - VLOG(1) << __PRETTY_FUNCTION__ << ": Device " - << ADDRESS_TO_LOGGABLE_STR(bdaddr) << " supports browsing"; + log::verbose("Device {} supports browsing", + ADDRESS_TO_LOGGABLE_STR(bdaddr)); peer_features |= (BTA_AV_FEAT_BROWSE); } } @@ -564,34 +554,31 @@ void ConnectionHandler::SdpCb(RawAddress bdaddr, SdpCallback cb, sdp_record = sdp_->FindServiceInDb(disc_db, UUID_SERVCLASS_AV_REM_CTRL_TARGET, nullptr); if (sdp_record != nullptr) { - VLOG(1) << __PRETTY_FUNCTION__ << ": Device " - << ADDRESS_TO_LOGGABLE_STR(bdaddr) - << " supports remote control target"; + log::verbose("Device {} supports remote control target", + ADDRESS_TO_LOGGABLE_STR(bdaddr)); uint16_t peer_avrcp_target_version = 0; sdp_->FindProfileVersionInRec(sdp_record, UUID_SERVCLASS_AV_REMOTE_CONTROL, &peer_avrcp_target_version); - VLOG(1) << __PRETTY_FUNCTION__ << ": Device " - << ADDRESS_TO_LOGGABLE_STR(bdaddr) << " peer avrcp target version=" - << loghex(peer_avrcp_target_version); + log::verbose("Device {} peer avrcp target version={}", + ADDRESS_TO_LOGGABLE_STR(bdaddr), + loghex(peer_avrcp_target_version)); if ((sdp_->FindAttributeInRec(sdp_record, ATTR_ID_BT_PROFILE_DESC_LIST)) != NULL) { if (peer_avrcp_target_version >= AVRC_REV_1_4) { /* get supported categories */ - VLOG(1) << __PRETTY_FUNCTION__ << " Get Supported categories"; + log::verbose("Get Supported categories"); tSDP_DISC_ATTR* sdp_attribute = sdp_->FindAttributeInRec(sdp_record, ATTR_ID_SUPPORTED_FEATURES); if (sdp_attribute != NULL && SDP_DISC_ATTR_TYPE(sdp_attribute->attr_len_type) == UINT_DESC_TYPE && SDP_DISC_ATTR_LEN(sdp_attribute->attr_len_type) >= 2) { - VLOG(1) << __PRETTY_FUNCTION__ - << "Get Supported categories SDP ATTRIBUTES != null"; + log::verbose("Get Supported categories SDP ATTRIBUTES != null"); uint16_t categories = sdp_attribute->attr_value.v.u16; if (categories & AVRC_SUPF_CT_CAT2) { - VLOG(1) << __PRETTY_FUNCTION__ << ": Device " - << ADDRESS_TO_LOGGABLE_STR(bdaddr) - << " supports advanced control"; + log::verbose("Device {} supports advanced control", + ADDRESS_TO_LOGGABLE_STR(bdaddr)); if (IsAbsoluteVolumeEnabled(&bdaddr)) { peer_features |= (BTA_AV_FEAT_ADV_CTRL); } @@ -618,7 +605,7 @@ void ConnectionHandler::SendMessage( (uint8_t)(::bluetooth::Packet::Specialize<Packet>(packet)->GetCType()); } - DLOG(INFO) << "SendMessage to handle=" << loghex(handle); + log::info("SendMessage to handle={}", loghex(handle)); BT_HDR* pkt = (BT_HDR*)osi_malloc(BT_DEFAULT_BUFFER_SIZE); @@ -652,7 +639,8 @@ void ConnectionHandler::SendMessage( } void ConnectionHandler::RegisterVolChanged(const RawAddress& bdaddr) { - LOG(INFO) << "Attempting to RegisterVolChanged device " << bdaddr; + log::info("Attempting to RegisterVolChanged device {}", + ADDRESS_TO_LOGGABLE_STR(bdaddr)); for (auto it = device_map_.begin(); it != device_map_.end(); it++) { if (bdaddr == it->second->GetAddress()) { const auto& feature_iter = feature_map_.find(bdaddr); diff --git a/system/profile/avrcp/device.cc b/system/profile/avrcp/device.cc index d2cc951faa..ece0d640f4 100644 --- a/system/profile/avrcp/device.cc +++ b/system/profile/avrcp/device.cc @@ -13,9 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +#define LOG_TAG "avrcp" + #include "device.h" -#include <base/logging.h> +#include <bluetooth/log.h> #include "abstract_message_loop.h" #include "avrcp_common.h" @@ -37,14 +40,13 @@ 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 fmt::formatter<bluetooth::avrcp::PlayState> + : enum_formatter<bluetooth::avrcp::PlayState> {}; + namespace bluetooth { namespace avrcp { -#define DEVICE_LOG(LEVEL) \ - LOG(LEVEL) << ADDRESS_TO_LOGGABLE_STR(address_) << " : " -#define DEVICE_VLOG(LEVEL) \ - VLOG(LEVEL) << ADDRESS_TO_LOGGABLE_STR(address_) << " : " - #define VOL_NOT_SUPPORTED -1 #define VOL_REGISTRATION_FAILED -2 @@ -77,12 +79,13 @@ void Device::RegisterInterfaces( base::WeakPtr<Device> Device::Get() { return weak_ptr_factory_.GetWeakPtr(); } void Device::SetBrowseMtu(uint16_t browse_mtu) { - DEVICE_LOG(INFO) << __PRETTY_FUNCTION__ << ": browse_mtu = " << browse_mtu; + log::info("{}: browse_mtu = {}", ADDRESS_TO_LOGGABLE_STR(address_), + browse_mtu); browse_mtu_ = browse_mtu; } void Device::SetBipClientStatus(bool connected) { - DEVICE_LOG(INFO) << __PRETTY_FUNCTION__ << ": connected = " << connected; + log::info("{}: connected = {}", ADDRESS_TO_LOGGABLE_STR(address_), connected); has_bip_client_ = connected; } @@ -108,10 +111,11 @@ bool Device::IsInSilenceMode() const { void Device::VendorPacketHandler(uint8_t label, std::shared_ptr<VendorPacket> pkt) { CHECK(media_interface_); - DEVICE_VLOG(3) << __func__ << ": pdu=" << pkt->GetCommandPdu(); + log::verbose("pdu={}", pkt->GetCommandPdu()); if (!pkt->IsValid()) { - DEVICE_LOG(WARNING) << __func__ << ": Request packet is not valid"; + log::warn("{}: Request packet is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = RejectBuilder::MakeBuilder(static_cast<CommandPdu>(0), Status::INVALID_COMMAND); send_message(label, false, std::move(response)); @@ -134,7 +138,8 @@ void Device::VendorPacketHandler(uint8_t label, (btif_av_src_sink_coexist_enabled() && register_notification->GetEvent() == Event::VOLUME_CHANGED)) && !register_notification->IsValid()) { - DEVICE_LOG(WARNING) << __func__ << ": Request packet is not valid"; + log::warn("{}: Request packet is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); @@ -145,9 +150,9 @@ void Device::VendorPacketHandler(uint8_t label, } if (register_notification->GetEvent() != Event::VOLUME_CHANGED) { - DEVICE_LOG(WARNING) - << __func__ << ": Unhandled register notification received: " - << register_notification->GetEvent(); + log::warn("{}: Unhandled register notification received: {}", + ADDRESS_TO_LOGGABLE_STR(address_), + register_notification->GetEvent()); return; } HandleVolumeChanged(label, register_notification); @@ -159,8 +164,8 @@ void Device::VendorPacketHandler(uint8_t label, // about the response to this message. break; default: - DEVICE_LOG(WARNING) - << __func__ << ": Unhandled Response: pdu=" << pkt->GetCommandPdu(); + log::warn("{}: Unhandled Response: pdu={}", + ADDRESS_TO_LOGGABLE_STR(address_), pkt->GetCommandPdu()); break; } return; @@ -182,7 +187,8 @@ void Device::VendorPacketHandler(uint8_t label, Packet::Specialize<GetElementAttributesRequest>(pkt); if (!get_element_attributes_request_pkt->IsValid()) { - DEVICE_LOG(WARNING) << __func__ << ": Request packet is not valid"; + log::warn("{}: Request packet is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); @@ -212,7 +218,8 @@ void Device::VendorPacketHandler(uint8_t label, Packet::Specialize<SetAddressedPlayerRequest>(pkt); if (!set_addressed_player_request->IsValid()) { - DEVICE_LOG(WARNING) << __func__ << ": Request packet is not valid"; + log::warn("{}: Request packet is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); @@ -226,8 +233,7 @@ void Device::VendorPacketHandler(uint8_t label, case CommandPdu::LIST_PLAYER_APPLICATION_SETTING_ATTRIBUTES: { if (player_settings_interface_ == nullptr) { - LOG(ERROR) << __func__ - << ": Player Settings Interface not initialized."; + log::error("Player Settings Interface not initialized."); auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_COMMAND); send_message(label, false, std::move(response)); @@ -241,8 +247,7 @@ void Device::VendorPacketHandler(uint8_t label, case CommandPdu::LIST_PLAYER_APPLICATION_SETTING_VALUES: { if (player_settings_interface_ == nullptr) { - LOG(ERROR) << __func__ - << ": Player Settings Interface not initialized."; + log::error("Player Settings Interface not initialized."); auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_COMMAND); send_message(label, false, std::move(response)); @@ -252,7 +257,8 @@ void Device::VendorPacketHandler(uint8_t label, Packet::Specialize<ListPlayerApplicationSettingValuesRequest>(pkt); if (!list_player_setting_values_request->IsValid()) { - DEVICE_LOG(WARNING) << __func__ << ": Request packet is not valid"; + log::warn("{}: Request packet is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); @@ -263,8 +269,8 @@ void Device::VendorPacketHandler(uint8_t label, list_player_setting_values_request->GetRequestedAttribute(); if (attribute < PlayerAttribute::EQUALIZER || attribute > PlayerAttribute::SCAN) { - DEVICE_LOG(WARNING) - << __func__ << ": Player Setting Attribute is not valid"; + log::warn("{}: Player Setting Attribute is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); @@ -279,8 +285,7 @@ void Device::VendorPacketHandler(uint8_t label, case CommandPdu::GET_CURRENT_PLAYER_APPLICATION_SETTING_VALUE: { if (player_settings_interface_ == nullptr) { - LOG(ERROR) << __func__ - << ": Player Settings Interface not initialized."; + log::error("Player Settings Interface not initialized."); auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_COMMAND); send_message(label, false, std::move(response)); @@ -291,7 +296,8 @@ void Device::VendorPacketHandler(uint8_t label, pkt); if (!get_current_player_setting_value_request->IsValid()) { - DEVICE_LOG(WARNING) << __func__ << ": Request packet is not valid"; + log::warn("{}: Request packet is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); @@ -303,8 +309,8 @@ void Device::VendorPacketHandler(uint8_t label, for (auto attribute : attributes) { if (attribute < PlayerAttribute::EQUALIZER || attribute > PlayerAttribute::SCAN) { - DEVICE_LOG(WARNING) - << __func__ << ": Player Setting Attribute is not valid"; + log::warn("{}: Player Setting Attribute is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); @@ -320,8 +326,7 @@ void Device::VendorPacketHandler(uint8_t label, case CommandPdu::SET_PLAYER_APPLICATION_SETTING_VALUE: { if (player_settings_interface_ == nullptr) { - LOG(ERROR) << __func__ - << ": Player Settings Interface not initialized."; + log::error("Player Settings Interface not initialized."); auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_COMMAND); send_message(label, false, std::move(response)); @@ -331,7 +336,8 @@ void Device::VendorPacketHandler(uint8_t label, Packet::Specialize<SetPlayerApplicationSettingValueRequest>(pkt); if (!set_player_setting_value_request->IsValid()) { - DEVICE_LOG(WARNING) << __func__ << ": Request packet is not valid"; + log::warn("{} : Request packet is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); @@ -347,8 +353,8 @@ void Device::VendorPacketHandler(uint8_t label, for (size_t i = 0; i < attributes.size(); i++) { if (attributes[i] < PlayerAttribute::EQUALIZER || attributes[i] > PlayerAttribute::SCAN) { - DEVICE_LOG(WARNING) - << __func__ << ": Player Setting Attribute is not valid"; + log::warn("{}: Player Setting Attribute is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); invalid_request = true; break; } @@ -357,8 +363,8 @@ void Device::VendorPacketHandler(uint8_t label, PlayerRepeatValue value = static_cast<PlayerRepeatValue>(values[i]); if (value < PlayerRepeatValue::OFF || value > PlayerRepeatValue::GROUP) { - DEVICE_LOG(WARNING) - << __func__ << ": Player Repeat Value is not valid"; + log::warn("{}: Player Repeat Value is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); invalid_request = true; break; } @@ -366,8 +372,8 @@ void Device::VendorPacketHandler(uint8_t label, PlayerShuffleValue value = static_cast<PlayerShuffleValue>(values[i]); if (value < PlayerShuffleValue::OFF || value > PlayerShuffleValue::GROUP) { - DEVICE_LOG(WARNING) - << __func__ << ": Player Shuffle Value is not valid"; + log::warn("{}: Player Shuffle Value is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); invalid_request = true; break; } @@ -389,7 +395,8 @@ void Device::VendorPacketHandler(uint8_t label, } break; default: { - DEVICE_LOG(ERROR) << "Unhandled Vendor Packet: " << pkt->ToString(); + log::error("{}: Unhandled Vendor Packet: {}", + ADDRESS_TO_LOGGABLE_STR(address_), pkt->ToString()); auto response = RejectBuilder::MakeBuilder( (CommandPdu)pkt->GetCommandPdu(), Status::INVALID_COMMAND); send_message(label, false, std::move(response)); @@ -399,17 +406,17 @@ void Device::VendorPacketHandler(uint8_t label, void Device::HandleGetCapabilities( uint8_t label, const std::shared_ptr<GetCapabilitiesRequest>& pkt) { - DEVICE_VLOG(4) << __func__ - << ": capability=" << pkt->GetCapabilityRequested(); - if (!pkt->IsValid()) { - DEVICE_LOG(WARNING) << __func__ << ": Request packet is not valid"; + log::warn("{}: Request packet is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); return; } + log::verbose("capability={}", pkt->GetCapabilityRequested()); + switch (pkt->GetCapabilityRequested()) { case Capability::COMPANY_ID: { auto response = @@ -439,8 +446,9 @@ void Device::HandleGetCapabilities( } break; default: { - DEVICE_LOG(WARNING) << "Unhandled Capability: " - << pkt->GetCapabilityRequested(); + log::warn("{}: Unhandled Capability: {}", + ADDRESS_TO_LOGGABLE_STR(address_), + pkt->GetCapabilityRequested()); auto response = RejectBuilder::MakeBuilder(CommandPdu::GET_CAPABILITIES, Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); @@ -451,14 +459,15 @@ void Device::HandleGetCapabilities( void Device::HandleNotification( uint8_t label, const std::shared_ptr<RegisterNotificationRequest>& pkt) { if (!pkt->IsValid()) { - DEVICE_LOG(WARNING) << __func__ << ": Request packet is not valid"; + log::warn("{}: Request packet is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); return; } - DEVICE_VLOG(4) << __func__ << ": event=" << pkt->GetEventRegistered(); + log::verbose("event={}", pkt->GetEventRegistered()); switch (pkt->GetEventRegistered()) { case Event::TRACK_CHANGED: { @@ -482,8 +491,7 @@ void Device::HandleNotification( case Event::PLAYER_APPLICATION_SETTING_CHANGED: { if (player_settings_interface_ == nullptr) { - LOG(ERROR) << __func__ - << ": Player Settings Interface not initialized."; + log::error("Player Settings Interface not initialized."); auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_COMMAND); send_message(label, false, std::move(response)); @@ -534,8 +542,8 @@ void Device::HandleNotification( } break; default: { - DEVICE_LOG(ERROR) << __func__ << " : Unknown event registered. Event ID=" - << pkt->GetEventRegistered(); + log::error("{}: Unknown event registered. Event ID={}", + ADDRESS_TO_LOGGABLE_STR(address_), pkt->GetEventRegistered()); auto response = RejectBuilder::MakeBuilder( (CommandPdu)pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); @@ -544,7 +552,7 @@ void Device::HandleNotification( } void Device::RegisterVolumeChanged() { - DEVICE_VLOG(2) << __func__; + log::verbose(""); if (volume_interface_ == nullptr) return; auto request = @@ -563,9 +571,8 @@ void Device::RegisterVolumeChanged() { } if (label == MAX_TRANSACTION_LABEL) { - DEVICE_LOG(FATAL) - << __func__ - << ": Abandon all hope, something went catastrophically wrong"; + log::fatal("{}: Abandon all hope, something went catastrophically wrong", + ADDRESS_TO_LOGGABLE_STR(address_)); } send_message_cb_.Run(label, false, std::move(request)); @@ -573,7 +580,7 @@ void Device::RegisterVolumeChanged() { void Device::HandleVolumeChanged( uint8_t label, const std::shared_ptr<RegisterNotificationResponse>& pkt) { - DEVICE_VLOG(1) << __func__ << ": interim=" << pkt->IsInterim(); + log::verbose("interim={}", pkt->IsInterim()); if (volume_interface_ == nullptr) return; @@ -606,23 +613,22 @@ void Device::HandleVolumeChanged( } if (!IsActive()) { - DEVICE_VLOG(3) << __func__ - << ": Ignoring volume changes from non active device"; + log::verbose("Ignoring volume changes from non active device"); return; } volume_ = pkt->GetVolume(); volume_ &= ~0x80; // remove RFA bit - DEVICE_VLOG(1) << __func__ << ": Volume has changed to " << (uint32_t)volume_; + log::verbose("Volume has changed to {}", (uint32_t)volume_); volume_interface_->SetVolume(volume_); } void Device::SetVolume(int8_t volume) { // TODO (apanicke): Implement logic for Multi-AVRCP - DEVICE_VLOG(1) << __func__ << ": volume=" << (int)volume; + log::verbose("volume={}", (int)volume); if (volume == volume_) { - DEVICE_LOG(WARNING) - << __func__ << ": Ignoring volume change same as current volume level"; + log::warn("{}: Ignoring volume change same as current volume level", + ADDRESS_TO_LOGGABLE_STR(address_)); return; } auto request = SetAbsoluteVolumeRequestBuilder::MakeBuilder(volume); @@ -643,12 +649,12 @@ void Device::SetVolume(int8_t volume) { void Device::TrackChangedNotificationResponse(uint8_t label, bool interim, std::string curr_song_id, std::vector<SongInfo> song_list) { - DEVICE_VLOG(1) << __func__; + log::verbose(""); if (interim) { track_changed_ = Notification(true, label); } else if (!track_changed_.first) { - DEVICE_VLOG(0) << __func__ << ": Device not registered for update"; + log::verbose("Device not registered for update"); return; } @@ -665,7 +671,7 @@ void Device::TrackChangedNotificationResponse(uint8_t label, bool interim, // Case for browsing not supported; // PTS BV-04-C and BV-5-C assume browsing not supported if (stack_config_get_interface()->get_pts_avrcp_test()) { - DEVICE_LOG(WARNING) << __func__ << ": pts test mode"; + log::warn("{}: pts test mode", ADDRESS_TO_LOGGABLE_STR(address_)); uint64_t uid = curr_song_id.empty() ? 0xffffffffffffffff : 0; auto response = RegisterNotificationResponseBuilder::MakeTrackChangedBuilder(interim, @@ -681,15 +687,15 @@ void Device::TrackChangedNotificationResponse(uint8_t label, bool interim, for (const SongInfo& song : song_list) { now_playing_ids_.insert(song.media_id); if (curr_song_id == song.media_id) { - DEVICE_VLOG(3) << __func__ << ": Found media ID match for " - << song.media_id; + log::verbose("Found media ID match for {}", song.media_id); uid = now_playing_ids_.get_uid(curr_song_id); } } if (uid == 0) { // uid 0 is not valid here when browsing is supported - DEVICE_LOG(ERROR) << "No match for media ID found"; + log::error("{}: No match for media ID found", + ADDRESS_TO_LOGGABLE_STR(address_)); } auto response = RegisterNotificationResponseBuilder::MakeTrackChangedBuilder( @@ -699,22 +705,21 @@ void Device::TrackChangedNotificationResponse(uint8_t label, bool interim, void Device::PlaybackStatusNotificationResponse(uint8_t label, bool interim, PlayStatus status) { - DEVICE_VLOG(1) << __func__; + log::verbose(""); if (status.state == PlayState::PAUSED) play_pos_update_cb_.Cancel(); if (interim) { play_status_changed_ = Notification(true, label); } else if (!play_status_changed_.first) { - DEVICE_VLOG(0) << __func__ << ": Device not registered for update"; + log::verbose("Device not registered for update"); return; } auto state_to_send = status.state; if (!IsActive()) state_to_send = PlayState::PAUSED; if (!interim && state_to_send == last_play_status_.state) { - DEVICE_VLOG(0) << __func__ - << ": Not sending notification due to no state update " - << ADDRESS_TO_LOGGABLE_STR(address_); + log::verbose("Not sending notification due to no state update {}", + ADDRESS_TO_LOGGABLE_STR(address_)); return; } @@ -733,18 +738,18 @@ void Device::PlaybackStatusNotificationResponse(uint8_t label, bool interim, void Device::PlaybackPosNotificationResponse(uint8_t label, bool interim, PlayStatus status) { - DEVICE_VLOG(4) << __func__; + log::verbose(""); if (interim) { play_pos_changed_ = Notification(true, label); } else if (!play_pos_changed_.first) { - DEVICE_VLOG(3) << __func__ << ": Device not registered for update"; + log::verbose("Device not registered for update"); return; } if (!interim && last_play_status_.position == status.position) { - DEVICE_LOG(WARNING) << ADDRESS_TO_LOGGABLE_STR(address_) - << ": No update to play position"; + log::warn("{}: No update to play position", + ADDRESS_TO_LOGGABLE_STR(address_)); return; } @@ -764,7 +769,7 @@ void Device::PlaybackPosNotificationResponse(uint8_t label, bool interim, // device even though the device thinks the music is paused. This makes // the status bar on the remote device move. if (status.state == PlayState::PLAYING && !IsInSilenceMode()) { - DEVICE_VLOG(0) << __func__ << ": Queue next play position update"; + log::verbose("Queue next play position update"); play_pos_update_cb_.Reset(base::Bind(&Device::HandlePlayPosUpdate, weak_ptr_factory_.GetWeakPtr())); btbase::AbstractMessageLoop::current_task_runner()->PostDelayedTask( @@ -782,13 +787,12 @@ void Device::PlaybackPosNotificationResponse(uint8_t label, bool interim, void Device::AddressedPlayerNotificationResponse( uint8_t label, bool interim, uint16_t curr_player, std::vector<MediaPlayerInfo> /* unused */) { - DEVICE_VLOG(1) << __func__ - << ": curr_player_id=" << (unsigned int)curr_player; + log::verbose("curr_player_id={}", (unsigned int)curr_player); if (interim) { addr_player_changed_ = Notification(true, label); } else if (!addr_player_changed_.first) { - DEVICE_VLOG(3) << __func__ << ": Device not registered for update"; + log::verbose("Device not registered for update"); return; } @@ -811,7 +815,7 @@ void Device::AddressedPlayerNotificationResponse( } void Device::RejectNotification() { - DEVICE_VLOG(1) << __func__; + log::verbose(""); Notification* rejectNotification[] = {&play_status_changed_, &track_changed_, &play_pos_changed_, &now_playing_changed_}; @@ -826,9 +830,8 @@ void Device::RejectNotification() { } void Device::GetPlayStatusResponse(uint8_t label, PlayStatus status) { - DEVICE_VLOG(2) << __func__ << ": position=" << status.position - << " duration=" << status.duration - << " state=" << status.state; + log::verbose("position={} duration={} state={}", status.position, + status.duration, status.state); auto response = GetPlayStatusResponseBuilder::MakeBuilder( status.duration, status.position, IsActive() ? status.state : PlayState::PAUSED); @@ -868,14 +871,15 @@ void Device::GetElementAttributesResponse( void Device::MessageReceived(uint8_t label, std::shared_ptr<Packet> pkt) { if (!pkt->IsValid()) { - DEVICE_LOG(WARNING) << __func__ << ": Request packet is not valid"; + log::warn("{}: Request packet is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = RejectBuilder::MakeBuilder(static_cast<CommandPdu>(0), Status::INVALID_COMMAND); send_message(label, false, std::move(response)); return; } - DEVICE_VLOG(4) << __func__ << ": opcode=" << pkt->GetOpcode(); + log::verbose("opcode={}", pkt->GetOpcode()); active_labels_.insert(label); switch (pkt->GetOpcode()) { // TODO (apanicke): Remove handling of UNIT_INFO and SUBUNIT_INFO from @@ -894,7 +898,8 @@ void Device::MessageReceived(uint8_t label, std::shared_ptr<Packet> pkt) { auto pass_through_packet = Packet::Specialize<PassThroughPacket>(pkt); if (!pass_through_packet->IsValid()) { - DEVICE_LOG(WARNING) << __func__ << ": Request packet is not valid"; + log::warn("{}: Request packet is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = RejectBuilder::MakeBuilder(static_cast<CommandPdu>(0), Status::INVALID_COMMAND); send_message(label, false, std::move(response)); @@ -917,13 +922,13 @@ void Device::MessageReceived(uint8_t label, std::shared_ptr<Packet> pkt) { if (!d) return; if (!d->IsActive()) { - LOG(INFO) << "Setting " << ADDRESS_TO_LOGGABLE_STR(d->address_) - << " to be the active device"; + log::info("Setting {} to be the active device", + ADDRESS_TO_LOGGABLE_STR(d->address_)); d->media_interface_->SetActiveDevice(d->address_); if (s.state == PlayState::PLAYING) { - LOG(INFO) - << "Skipping sendKeyEvent since music is already playing"; + log::info( + "Skipping sendKeyEvent since music is already playing"); return; } } @@ -948,17 +953,17 @@ void Device::MessageReceived(uint8_t label, std::shared_ptr<Packet> pkt) { void Device::HandlePlayItem(uint8_t label, std::shared_ptr<PlayItemRequest> pkt) { - DEVICE_VLOG(2) << __func__ << ": scope=" << pkt->GetScope() - << " uid=" << pkt->GetUid(); - if (!pkt->IsValid()) { - DEVICE_LOG(WARNING) << __func__ << ": Request packet is not valid"; + log::warn("{}: Request packet is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = RejectBuilder::MakeBuilder(pkt->GetCommandPdu(), Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); return; } + log::verbose("scope={} uid={}", pkt->GetScope(), pkt->GetUid()); + std::string media_id = ""; switch (pkt->GetScope()) { case Scope::NOW_PLAYING: @@ -968,11 +973,12 @@ void Device::HandlePlayItem(uint8_t label, media_id = vfs_ids_.get_media_id(pkt->GetUid()); break; default: - DEVICE_LOG(WARNING) << __func__ << ": Unknown scope for play item"; + log::warn("{}: Unknown scope for play item", + ADDRESS_TO_LOGGABLE_STR(address_)); } if (media_id == "") { - DEVICE_VLOG(2) << "Could not find item"; + log::verbose("Could not find item"); auto response = RejectBuilder::MakeBuilder(CommandPdu::PLAY_ITEM, Status::DOES_NOT_EXIST); send_message(label, false, std::move(response)); @@ -989,10 +995,10 @@ void Device::HandlePlayItem(uint8_t label, void Device::HandleSetAddressedPlayer( uint8_t label, std::shared_ptr<SetAddressedPlayerRequest> pkt, uint16_t curr_player, std::vector<MediaPlayerInfo> players) { - DEVICE_VLOG(2) << __func__ << ": PlayerId=" << pkt->GetPlayerId(); + log::verbose("PlayerId={}", pkt->GetPlayerId()); if (curr_player != pkt->GetPlayerId()) { - DEVICE_VLOG(2) << "Reject invalid addressed player ID"; + log::verbose("Reject invalid addressed player ID"); auto response = RejectBuilder::MakeBuilder(CommandPdu::SET_ADDRESSED_PLAYER, Status::INVALID_PLAYER_ID); send_message(label, false, std::move(response)); @@ -1007,11 +1013,10 @@ void Device::HandleSetAddressedPlayer( void Device::ListPlayerApplicationSettingAttributesResponse( uint8_t label, std::vector<PlayerAttribute> attributes) { uint8_t num_of_attributes = attributes.size(); - DEVICE_VLOG(2) << __func__ - << ": num_of_attributes=" << std::to_string(num_of_attributes); + log::verbose("num_of_attributes={}", num_of_attributes); if (num_of_attributes > 0) { for (auto attribute : attributes) { - DEVICE_VLOG(2) << __func__ << ": attribute=" << attribute; + log::verbose("attribute={}", attribute); } } auto response = @@ -1023,22 +1028,20 @@ void Device::ListPlayerApplicationSettingAttributesResponse( void Device::ListPlayerApplicationSettingValuesResponse( uint8_t label, PlayerAttribute attribute, std::vector<uint8_t> values) { uint8_t number_of_values = values.size(); - DEVICE_VLOG(2) << __func__ << ": attribute=" << attribute - << ", number_of_values=" << std::to_string(number_of_values); + log::verbose("attribute={}, number_of_values={}", attribute, + number_of_values); if (number_of_values > 0) { if (attribute == PlayerAttribute::REPEAT) { for (auto value : values) { - DEVICE_VLOG(2) << __func__ - << ": value=" << static_cast<PlayerRepeatValue>(value); + log::verbose("value={}", static_cast<PlayerRepeatValue>(value)); } } else if (attribute == PlayerAttribute::SHUFFLE) { for (auto value : values) { - DEVICE_VLOG(2) << __func__ - << ": value=" << static_cast<PlayerShuffleValue>(value); + log::verbose("value={}", static_cast<PlayerShuffleValue>(value)); } } else { - DEVICE_VLOG(2) << __func__ << ": value=" << loghex(values.at(0)); + log::verbose("value={}", loghex(values.at(0))); } } @@ -1052,16 +1055,13 @@ void Device::GetPlayerApplicationSettingValueResponse( uint8_t label, std::vector<PlayerAttribute> attributes, std::vector<uint8_t> values) { for (size_t i = 0; i < attributes.size(); i++) { - DEVICE_VLOG(2) << __func__ << ": attribute=" - << static_cast<PlayerAttribute>(attributes[i]); + log::verbose("attribute={}", static_cast<PlayerAttribute>(attributes[i])); if (attributes[i] == PlayerAttribute::REPEAT) { - DEVICE_VLOG(2) << __func__ - << ": value=" << static_cast<PlayerRepeatValue>(values[i]); + log::verbose("value={}", static_cast<PlayerRepeatValue>(values[i])); } else if (attributes[i] == PlayerAttribute::SHUFFLE) { - DEVICE_VLOG(2) << __func__ << ": value=" - << static_cast<PlayerShuffleValue>(values[i]); + log::verbose("value={}", static_cast<PlayerShuffleValue>(values[i])); } else { - DEVICE_VLOG(2) << __func__ << ": value=" << loghex(values.at(0)); + log::verbose("value={}", loghex(values.at(0))); } } @@ -1075,8 +1075,8 @@ void Device::SetPlayerApplicationSettingValueResponse(uint8_t label, CommandPdu pdu, bool success) { if (!success) { - DEVICE_LOG(ERROR) << __func__ - << ": Set Player Application Setting Value failed"; + log::error("{}: Set Player Application Setting Value failed", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = RejectBuilder::MakeBuilder(pdu, Status::INVALID_PARAMETER); send_message(label, false, std::move(response)); return; @@ -1090,13 +1090,14 @@ void Device::SetPlayerApplicationSettingValueResponse(uint8_t label, void Device::BrowseMessageReceived(uint8_t label, std::shared_ptr<BrowsePacket> pkt) { if (!pkt->IsValid()) { - DEVICE_LOG(WARNING) << __func__ << ": Request packet is not valid"; + log::warn("{}: Request packet is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = GeneralRejectBuilder::MakeBuilder(Status::INVALID_COMMAND); send_message(label, false, std::move(response)); return; } - DEVICE_VLOG(1) << __func__ << ": pdu=" << pkt->GetPdu(); + log::verbose("pdu={}", pkt->GetPdu()); switch (pkt->GetPdu()) { case BrowsePdu::SET_BROWSED_PLAYER: @@ -1119,7 +1120,7 @@ void Device::BrowseMessageReceived(uint8_t label, label, Packet::Specialize<GetTotalNumberOfItemsRequest>(pkt)); break; default: - DEVICE_LOG(WARNING) << __func__ << ": " << pkt->GetPdu(); + log::warn("{}: pdu={}", ADDRESS_TO_LOGGABLE_STR(address_), pkt->GetPdu()); auto response = GeneralRejectBuilder::MakeBuilder(Status::INVALID_COMMAND); send_message(label, true, std::move(response)); @@ -1132,15 +1133,15 @@ void Device::HandleGetFolderItems(uint8_t label, std::shared_ptr<GetFolderItemsRequest> pkt) { if (!pkt->IsValid()) { // The specific get folder items builder is unimportant on failure. - DEVICE_LOG(WARNING) << __func__ - << ": Get folder items request packet is not valid"; + log::warn("{}: Get folder items request packet is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = GetFolderItemsResponseBuilder::MakePlayerListBuilder( Status::INVALID_PARAMETER, 0x0000, browse_mtu_); send_message(label, true, std::move(response)); return; } - DEVICE_VLOG(2) << __func__ << ": scope=" << pkt->GetScope(); + log::verbose("scope={}", pkt->GetScope()); switch (pkt->GetScope()) { case Scope::MEDIA_PLAYER_LIST: @@ -1160,7 +1161,8 @@ void Device::HandleGetFolderItems(uint8_t label, weak_ptr_factory_.GetWeakPtr(), label, pkt)); break; default: - DEVICE_LOG(ERROR) << __func__ << ": " << pkt->GetScope(); + log::error("{}: scope={}", ADDRESS_TO_LOGGABLE_STR(address_), + pkt->GetScope()); auto response = GetFolderItemsResponseBuilder::MakePlayerListBuilder( Status::INVALID_PARAMETER, 0, browse_mtu_); send_message(label, true, std::move(response)); @@ -1171,14 +1173,15 @@ void Device::HandleGetFolderItems(uint8_t label, void Device::HandleGetTotalNumberOfItems( uint8_t label, std::shared_ptr<GetTotalNumberOfItemsRequest> pkt) { if (!pkt->IsValid()) { - DEVICE_LOG(WARNING) << __func__ << ": Request packet is not valid"; + log::warn("{}: Request packet is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = GetTotalNumberOfItemsResponseBuilder::MakeBuilder( Status::INVALID_PARAMETER, 0x0000, 0); send_message(label, true, std::move(response)); return; } - DEVICE_VLOG(2) << __func__ << ": scope=" << pkt->GetScope(); + log::verbose("scope={}", pkt->GetScope()); switch (pkt->GetScope()) { case Scope::MEDIA_PLAYER_LIST: { @@ -1199,14 +1202,15 @@ void Device::HandleGetTotalNumberOfItems( weak_ptr_factory_.GetWeakPtr(), label)); break; default: - DEVICE_LOG(ERROR) << __func__ << ": " << pkt->GetScope(); + log::error("{}: scope={}", ADDRESS_TO_LOGGABLE_STR(address_), + pkt->GetScope()); break; } } void Device::GetTotalNumberOfItemsMediaPlayersResponse( uint8_t label, uint16_t curr_player, std::vector<MediaPlayerInfo> list) { - DEVICE_VLOG(2) << __func__ << ": num_items=" << list.size(); + log::verbose("num_items={}", list.size()); auto builder = GetTotalNumberOfItemsResponseBuilder::MakeBuilder( Status::NO_ERROR, 0x0000, list.size()); @@ -1215,7 +1219,7 @@ void Device::GetTotalNumberOfItemsMediaPlayersResponse( void Device::GetTotalNumberOfItemsVFSResponse(uint8_t label, std::vector<ListItem> list) { - DEVICE_VLOG(2) << __func__ << ": num_items=" << list.size(); + log::verbose("num_items={}", list.size()); auto builder = GetTotalNumberOfItemsResponseBuilder::MakeBuilder( Status::NO_ERROR, 0x0000, list.size()); @@ -1224,7 +1228,7 @@ void Device::GetTotalNumberOfItemsVFSResponse(uint8_t label, void Device::GetTotalNumberOfItemsNowPlayingResponse( uint8_t label, std::string curr_song_id, std::vector<SongInfo> list) { - DEVICE_VLOG(2) << __func__ << ": num_items=" << list.size(); + log::verbose("num_items={}", list.size()); auto builder = GetTotalNumberOfItemsResponseBuilder::MakeBuilder( Status::NO_ERROR, 0x0000, list.size()); @@ -1234,20 +1238,21 @@ void Device::GetTotalNumberOfItemsNowPlayingResponse( void Device::HandleChangePath(uint8_t label, std::shared_ptr<ChangePathRequest> pkt) { if (!pkt->IsValid()) { - DEVICE_LOG(WARNING) << __func__ << ": Request packet is not valid"; + log::warn("{}: Request packet is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = ChangePathResponseBuilder::MakeBuilder(Status::INVALID_PARAMETER, 0); send_message(label, true, std::move(response)); return; } - DEVICE_VLOG(2) << __func__ << ": direction=" << pkt->GetDirection() - << " uid=" << loghex(pkt->GetUid()); + log::verbose("direction={} uid={}", pkt->GetDirection(), + loghex(pkt->GetUid())); if (pkt->GetDirection() == Direction::DOWN && vfs_ids_.get_media_id(pkt->GetUid()) == "") { - DEVICE_LOG(ERROR) << __func__ - << ": No item found for UID=" << pkt->GetUid(); + log::error("{}: No item found for UID={}", + ADDRESS_TO_LOGGABLE_STR(address_), pkt->GetUid()); auto builder = ChangePathResponseBuilder::MakeBuilder(Status::DOES_NOT_EXIST, 0); send_message(label, true, std::move(builder)); @@ -1256,21 +1261,21 @@ void Device::HandleChangePath(uint8_t label, if (pkt->GetDirection() == Direction::DOWN) { current_path_.push(vfs_ids_.get_media_id(pkt->GetUid())); - DEVICE_VLOG(2) << "Pushing Path to stack: \"" << CurrentFolder() << "\""; + log::verbose("Pushing Path to stack: \"{}\"", CurrentFolder()); } else { // Don't pop the root id off the stack if (current_path_.size() > 1) { current_path_.pop(); } else { - DEVICE_LOG(ERROR) << "Trying to change directory up past root."; + log::error("{}: Trying to change directory up past root.", + ADDRESS_TO_LOGGABLE_STR(address_)); auto builder = ChangePathResponseBuilder::MakeBuilder(Status::DOES_NOT_EXIST, 0); send_message(label, true, std::move(builder)); return; } - DEVICE_VLOG(2) << "Popping Path from stack: new path=\"" << CurrentFolder() - << "\""; + log::verbose("Popping Path from stack: new path=\"{}\"", CurrentFolder()); } media_interface_->GetFolderItems( @@ -1292,18 +1297,18 @@ void Device::ChangePathResponse(uint8_t label, void Device::HandleGetItemAttributes( uint8_t label, std::shared_ptr<GetItemAttributesRequest> pkt) { if (!pkt->IsValid()) { - DEVICE_LOG(WARNING) << __func__ << ": Request packet is not valid"; + log::warn("{}: Request packet is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto builder = GetItemAttributesResponseBuilder::MakeBuilder( Status::INVALID_PARAMETER, browse_mtu_); send_message(label, true, std::move(builder)); return; } - DEVICE_VLOG(2) << __func__ << ": scope=" << pkt->GetScope() - << " uid=" << loghex(pkt->GetUid()) - << " uid counter=" << loghex(pkt->GetUidCounter()); + log::verbose("scope={} uid={} uid counter={}", pkt->GetScope(), + loghex(pkt->GetUid()), loghex(pkt->GetUidCounter())); if (pkt->GetUidCounter() != 0x0000) { // For database unaware player, use 0 - DEVICE_LOG(WARNING) << "UidCounter is invalid"; + log::warn("{}: UidCounter is invalid", ADDRESS_TO_LOGGABLE_STR(address_)); auto builder = GetItemAttributesResponseBuilder::MakeBuilder( Status::UIDS_CHANGED, browse_mtu_); send_message(label, true, std::move(builder)); @@ -1327,7 +1332,8 @@ void Device::HandleGetItemAttributes( weak_ptr_factory_.GetWeakPtr(), label, pkt)); break; default: - DEVICE_LOG(ERROR) << "UNKNOWN SCOPE FOR HANDLE GET ITEM ATTRIBUTES"; + log::error("{}: UNKNOWN SCOPE FOR HANDLE GET ITEM ATTRIBUTES", + ADDRESS_TO_LOGGABLE_STR(address_)); break; } } @@ -1335,7 +1341,7 @@ void Device::HandleGetItemAttributes( void Device::GetItemAttributesNowPlayingResponse( uint8_t label, std::shared_ptr<GetItemAttributesRequest> pkt, std::string curr_media_id, std::vector<SongInfo> song_list) { - DEVICE_VLOG(2) << __func__ << ": uid=" << loghex(pkt->GetUid()); + log::verbose("uid={}", loghex(pkt->GetUid())); auto builder = GetItemAttributesResponseBuilder::MakeBuilder(Status::NO_ERROR, browse_mtu_); @@ -1344,13 +1350,11 @@ void Device::GetItemAttributesNowPlayingResponse( media_id = curr_media_id; } - DEVICE_VLOG(2) << __func__ << ": media_id=\"" << media_id << "\""; + log::verbose("media_id=\"{}\"", media_id); SongInfo info; if (song_list.size() == 1) { - DEVICE_VLOG(2) - << __func__ - << " Send out the only song in the queue as now playing song."; + log::verbose("Send out the only song in the queue as now playing song."); info = song_list.front(); } else { for (const auto& temp : song_list) { @@ -1386,11 +1390,11 @@ void Device::GetItemAttributesNowPlayingResponse( void Device::GetItemAttributesVFSResponse( uint8_t label, std::shared_ptr<GetItemAttributesRequest> pkt, std::vector<ListItem> item_list) { - DEVICE_VLOG(2) << __func__ << ": uid=" << loghex(pkt->GetUid()); + log::verbose("uid={}", loghex(pkt->GetUid())); auto media_id = vfs_ids_.get_media_id(pkt->GetUid()); if (media_id == "") { - LOG(WARNING) << __func__ << ": Item not found"; + log::warn("Item not found"); auto builder = GetItemAttributesResponseBuilder::MakeBuilder( Status::DOES_NOT_EXIST, browse_mtu_); send_message(label, true, std::move(builder)); @@ -1453,7 +1457,7 @@ void Device::GetItemAttributesVFSResponse( void Device::GetMediaPlayerListResponse( uint8_t label, std::shared_ptr<GetFolderItemsRequest> pkt, uint16_t curr_player, std::vector<MediaPlayerInfo> players) { - DEVICE_VLOG(2) << __func__; + log::verbose(""); if (players.size() == 0) { auto no_items_rsp = GetFolderItemsResponseBuilder::MakePlayerListBuilder( @@ -1469,7 +1473,7 @@ void Device::GetMediaPlayerListResponse( // returned by Addressed Player Changed for (auto it = players.begin(); it != players.end(); it++) { if (it->id == curr_player) { - DEVICE_VLOG(1) << " Adding player to first spot: " << it->name; + log::verbose(" Adding player to first spot: {}", it->name); auto temp_player = *it; players.erase(it); players.insert(players.begin(), temp_player); @@ -1502,8 +1506,8 @@ std::set<AttributeEntry> filter_attributes_requested( void Device::GetVFSListResponse(uint8_t label, std::shared_ptr<GetFolderItemsRequest> pkt, std::vector<ListItem> items) { - DEVICE_VLOG(2) << __func__ << ": start_item=" << pkt->GetStartItem() - << " end_item=" << pkt->GetEndItem(); + log::verbose("start_item={} end_item={}", pkt->GetStartItem(), + pkt->GetEndItem()); // The builder will automatically correct the status if there are zero items auto builder = GetFolderItemsResponseBuilder::MakeVFSBuilder( @@ -1566,7 +1570,7 @@ void Device::GetVFSListResponse(uint8_t label, void Device::GetNowPlayingListResponse( uint8_t label, std::shared_ptr<GetFolderItemsRequest> pkt, std::string /* unused curr_song_id */, std::vector<SongInfo> song_list) { - DEVICE_VLOG(2) << __func__; + log::verbose(""); auto builder = GetFolderItemsResponseBuilder::MakeNowPlayingBuilder( Status::NO_ERROR, 0x0000, browse_mtu_); @@ -1607,14 +1611,15 @@ void Device::GetNowPlayingListResponse( void Device::HandleSetBrowsedPlayer( uint8_t label, std::shared_ptr<SetBrowsedPlayerRequest> pkt) { if (!pkt->IsValid()) { - DEVICE_LOG(WARNING) << __func__ << ": Request packet is not valid"; + log::warn("{}: Request packet is not valid", + ADDRESS_TO_LOGGABLE_STR(address_)); auto response = SetBrowsedPlayerResponseBuilder::MakeBuilder( Status::INVALID_PARAMETER, 0x0000, 0, 0, ""); send_message(label, true, std::move(response)); return; } - DEVICE_VLOG(2) << __func__ << ": player_id=" << pkt->GetPlayerId(); + log::verbose("player_id={}", pkt->GetPlayerId()); media_interface_->SetBrowsedPlayer( pkt->GetPlayerId(), base::Bind(&Device::SetBrowsedPlayerResponse, @@ -1624,8 +1629,8 @@ void Device::HandleSetBrowsedPlayer( void Device::SetBrowsedPlayerResponse( uint8_t label, std::shared_ptr<SetBrowsedPlayerRequest> pkt, bool success, std::string root_id, uint32_t num_items) { - DEVICE_VLOG(2) << __func__ << ": success=" << success << " root_id=\"" - << root_id << "\" num_items=" << num_items; + log::verbose("success={} root_id=\"{}\" num_items={}", success, root_id, + num_items); if (!success) { auto response = SetBrowsedPlayerResponseBuilder::MakeBuilder( @@ -1657,9 +1662,8 @@ void Device::SendMediaUpdate(bool metadata, bool play_status, bool queue) { bool is_silence = IsInSilenceMode(); CHECK(media_interface_); - DEVICE_VLOG(4) << __func__ << ": Metadata=" << metadata - << " : play_status= " << play_status << " : queue=" << queue - << " ; is_silence=" << is_silence; + log::verbose("Metadata={} : play_status= {} : queue={} : is_silence={}", + metadata, play_status, queue, is_silence); if (queue) { HandleNowPlayingUpdate(); @@ -1678,7 +1682,7 @@ void Device::SendMediaUpdate(bool metadata, bool play_status, bool queue) { void Device::SendFolderUpdate(bool available_players, bool addressed_player, bool uids) { CHECK(media_interface_); - DEVICE_VLOG(4) << __func__; + log::verbose(""); if (available_players) { HandleAvailablePlayerUpdate(); @@ -1690,9 +1694,9 @@ void Device::SendFolderUpdate(bool available_players, bool addressed_player, } void Device::HandleTrackUpdate() { - DEVICE_VLOG(2) << __func__; + log::verbose(""); if (!track_changed_.first) { - LOG(WARNING) << "Device is not registered for track changed updates"; + log::warn("Device is not registered for track changed updates"); return; } @@ -1702,9 +1706,9 @@ void Device::HandleTrackUpdate() { } void Device::HandlePlayStatusUpdate() { - DEVICE_VLOG(2) << __func__; + log::verbose(""); if (!play_status_changed_.first) { - LOG(WARNING) << "Device is not registered for play status updates"; + log::warn("Device is not registered for play status updates"); return; } @@ -1714,10 +1718,10 @@ void Device::HandlePlayStatusUpdate() { } void Device::HandleNowPlayingUpdate() { - DEVICE_VLOG(2) << __func__; + log::verbose(""); if (!now_playing_changed_.first) { - LOG(WARNING) << "Device is not registered for now playing updates"; + log::warn("Device is not registered for now playing updates"); return; } @@ -1728,21 +1732,20 @@ void Device::HandleNowPlayingUpdate() { void Device::HandlePlayerSettingChanged(std::vector<PlayerAttribute> attributes, std::vector<uint8_t> values) { - DEVICE_VLOG(2) << __func__; + log::verbose(""); if (!player_setting_changed_.first) { - LOG(WARNING) << "Device is not registered for player settings updates"; + log::warn("Device is not registered for player settings updates"); return; } for (size_t i = 0; i < attributes.size(); i++) { - DEVICE_VLOG(2) << " attribute: " << attributes[i] << std::endl; + log::verbose(" attribute: {}", attributes[i]); if (attributes[i] == PlayerAttribute::SHUFFLE) { - DEVICE_VLOG(2) << " value: " << (PlayerShuffleValue)values[i] - << std::endl; + log::verbose(" value: {}", (PlayerShuffleValue)values[i]); } else if (attributes[i] == PlayerAttribute::REPEAT) { - DEVICE_VLOG(2) << " value: " << (PlayerRepeatValue)values[i] << std::endl; + log::verbose(" value: {}", (PlayerRepeatValue)values[i]); } else { - DEVICE_VLOG(2) << " value: " << std::to_string(values[i]) << std::endl; + log::verbose(" value: {}", values[i]); } } @@ -1755,23 +1758,22 @@ void Device::HandlePlayerSettingChanged(std::vector<PlayerAttribute> attributes, void Device::PlayerSettingChangedNotificationResponse( uint8_t label, bool interim, std::vector<PlayerAttribute> attributes, std::vector<uint8_t> values) { - DEVICE_VLOG(2) << __func__ << " interim: " << interim << std::endl; + log::verbose("interim: {}", interim); for (size_t i = 0; i < attributes.size(); i++) { - DEVICE_VLOG(2) << " attribute: " << attributes[i] << std::endl; + log::verbose(" attribute: {}", attributes[i]); if (attributes[i] == PlayerAttribute::SHUFFLE) { - DEVICE_VLOG(2) << " value: " << (PlayerShuffleValue)values[i] - << std::endl; + log::verbose(" value: {}", (PlayerShuffleValue)values[i]); } else if (attributes[i] == PlayerAttribute::REPEAT) { - DEVICE_VLOG(2) << " value: " << (PlayerRepeatValue)values[i] << std::endl; + log::verbose(" value: {}", (PlayerRepeatValue)values[i]); } else { - DEVICE_VLOG(2) << " value: " << std::to_string(values[i]) << std::endl; + log::verbose(" value: {}", values[i]); } } if (interim) { player_setting_changed_ = Notification(true, label); } else if (!player_setting_changed_.first) { - LOG(WARNING) << "Device is not registered for now playing updates"; + log::warn("Device is not registered for now playing updates"); return; } @@ -1792,7 +1794,7 @@ void Device::HandleNowPlayingNotificationResponse( if (interim) { now_playing_changed_ = Notification(true, label); } else if (!now_playing_changed_.first) { - LOG(WARNING) << "Device is not registered for now playing updates"; + log::warn("Device is not registered for now playing updates"); return; } @@ -1812,9 +1814,9 @@ void Device::HandleNowPlayingNotificationResponse( } void Device::HandlePlayPosUpdate() { - DEVICE_VLOG(0) << __func__; + log::verbose(""); if (!play_pos_changed_.first) { - LOG(WARNING) << "Device is not registered for play position updates"; + log::warn("Device is not registered for play position updates"); return; } @@ -1824,10 +1826,10 @@ void Device::HandlePlayPosUpdate() { } void Device::HandleAvailablePlayerUpdate() { - DEVICE_VLOG(1) << __func__; + log::verbose(""); if (!avail_players_changed_.first) { - LOG(WARNING) << "Device is not registered for available player updates"; + log::warn("Device is not registered for available player updates"); return; } @@ -1843,10 +1845,10 @@ void Device::HandleAvailablePlayerUpdate() { } void Device::HandleAddressedPlayerUpdate() { - DEVICE_VLOG(1) << __func__; + log::verbose(""); if (!addr_player_changed_.first) { - DEVICE_LOG(WARNING) - << "Device is not registered for addressed player updates"; + log::warn("{}: Device is not registered for addressed player updates", + ADDRESS_TO_LOGGABLE_STR(address_)); return; } media_interface_->GetMediaPlayerList(base::Bind( @@ -1855,7 +1857,7 @@ void Device::HandleAddressedPlayerUpdate() { } void Device::DeviceDisconnected() { - DEVICE_LOG(INFO) << "Device was disconnected"; + log::info("{} : Device was disconnected", ADDRESS_TO_LOGGABLE_STR(address_)); play_pos_update_cb_.Cancel(); // TODO (apanicke): Once the interfaces are set in the Device construction, diff --git a/system/profile/avrcp/tests/avrcp_connection_handler_test.cc b/system/profile/avrcp/tests/avrcp_connection_handler_test.cc index 957fdb33e7..7b3ea7bd22 100644 --- a/system/profile/avrcp/tests/avrcp_connection_handler_test.cc +++ b/system/profile/avrcp/tests/avrcp_connection_handler_test.cc @@ -15,14 +15,13 @@ */ #include <base/functional/bind.h> -#include <base/logging.h> #include <gmock/gmock.h> #include <gtest/gtest.h> -#include "sdpdefs.h" #include "avrcp_internal.h" #include "avrcp_test_helper.h" #include "connection_handler.h" +#include "sdpdefs.h" #include "types/raw_address.h" using ::testing::_; diff --git a/system/profile/avrcp/tests/avrcp_device_test.cc b/system/profile/avrcp/tests/avrcp_device_test.cc index 7216a5dbf0..52672baa59 100644 --- a/system/profile/avrcp/tests/avrcp_device_test.cc +++ b/system/profile/avrcp/tests/avrcp_device_test.cc @@ -15,7 +15,6 @@ */ #include <base/functional/bind.h> -#include <base/logging.h> #include <base/threading/thread.h> #include <gmock/gmock.h> #include <gtest/gtest.h> diff --git a/system/profile/sdp/Android.bp b/system/profile/sdp/Android.bp index fe68a2be69..88e491644f 100644 --- a/system/profile/sdp/Android.bp +++ b/system/profile/sdp/Android.bp @@ -23,6 +23,7 @@ cc_library_static { static_libs: [ "lib-bt-packets", "libbluetooth-types", + "libbluetooth_log", ], header_libs: ["libbluetooth_headers"], } @@ -47,9 +48,13 @@ cc_test { "lib-bt-packets-avrcp", "lib-bt-packets-base", "libbluetooth-types", + "libbluetooth_log", "libchrome", "libgmock", "sdp_service", ], - shared_libs: ["liblog"], + shared_libs: [ + "libbase", + "liblog", + ], } diff --git a/system/profile/sdp/common/data_element_reader.cc b/system/profile/sdp/common/data_element_reader.cc index 992e7c8b87..5bba190576 100644 --- a/system/profile/sdp/common/data_element_reader.cc +++ b/system/profile/sdp/common/data_element_reader.cc @@ -16,7 +16,7 @@ #include "data_element_reader.h" -#include <base/logging.h> +#include <bluetooth/log.h> #include <type_traits> @@ -27,19 +27,19 @@ // reader to extract without overflowing. end_ - it_ should never be negative // so casting it to a size_t is always safe. If it does fail, set it_ to end_ // so that all additional readings fail. -#define CHECK_REMAINING_LEN(x) \ - do { \ - if ((size_t)(end_ - it_) < x) { \ - LOG(WARNING) << __func__ << ": Extract would read past end of data."; \ - return ParseFail(); \ - } \ +#define CHECK_REMAINING_LEN(x) \ + do { \ + if ((size_t)(end_ - it_) < x) { \ + log::warn("Extract would read past end of data."); \ + return ParseFail(); \ + } \ } while (0) namespace bluetooth { namespace sdp { DataElementReader::DataElement DataElementReader::ReadNext() { - if (it_ > end_) LOG(FATAL) << "Beginning of buffer is past end of buffer."; + if (it_ > end_) log::fatal("Beginning of buffer is past end of buffer."); if (it_ == end_) return std::monostate(); uint8_t descriptor = *it_++; @@ -48,14 +48,14 @@ DataElementReader::DataElement DataElementReader::ReadNext() { // All types with a value greater than URL are currently reserved. if (type > DataElementType::MAX_VALUE) { - LOG(WARNING) << __func__ << ": Trying to use a reserved data element type"; + log::warn("Trying to use a reserved data element type"); return ParseFail(); } switch (type) { case DataElementType::BOOLEAN: if (size != DataElementSize::BYTE1) { - LOG(WARNING) << __func__ << ": Invalid size for bool: " << size; + log::warn("Invalid size for bool: {}", size); return ParseFail(); } @@ -75,7 +75,7 @@ DataElementReader::DataElement DataElementReader::ReadNext() { // TODO: The other data element types are never used in the previous SDP // implementation. We should properly handle them in the future though // for completeness. - LOG(ERROR) << __func__ << ": Unhandled Data Element Type: " << type; + log::error("Unhandled Data Element Type: {}", type); } return ParseFail(); @@ -120,7 +120,7 @@ DataElementReader::DataElement DataElementReader::ReadSignedInt( case DataElementSize::BYTE16: return ReadLargeInt(); default: - LOG(WARNING) << __func__ << ": Invalid size for int: " << size; + log::warn("Invalid size for int: {}", size); } return ParseFail(); @@ -140,7 +140,7 @@ DataElementReader::DataElement DataElementReader::ReadUnsignedInt( case DataElementSize::BYTE16: return ReadLargeInt(); default: - LOG(WARNING) << __func__ << ": Invalid size for uint: " << size; + log::warn("Invalid size for uint: {}", size); } return ParseFail(); @@ -169,7 +169,7 @@ DataElementReader::DataElement DataElementReader::ReadUuid( return Uuid::From128BitBE(uuid_array); } - LOG(WARNING) << __func__ << ": Invalid size for UUID: " << size; + log::warn("Invalid size for UUID: {}", size); return ParseFail(); } @@ -191,7 +191,7 @@ DataElementReader::DataElement DataElementReader::ReadString( num_bytes = it_.extractBE<uint32_t>(); break; default: - LOG(WARNING) << __func__ << ": Invalid size for string: " << size; + log::warn("Invalid size for string: {}", size); return ParseFail(); } @@ -223,7 +223,7 @@ DataElementReader::DataElement DataElementReader::ReadSequence( num_bytes = it_.extractBE<uint32_t>(); break; default: - LOG(WARNING) << __func__ << ": Invalid size for string: " << size; + log::warn("Invalid size for string: {}", size); return ParseFail(); } diff --git a/system/profile/sdp/common/test/data_element_reader_test.cc b/system/profile/sdp/common/test/data_element_reader_test.cc index 167f7d191f..429eaba805 100644 --- a/system/profile/sdp/common/test/data_element_reader_test.cc +++ b/system/profile/sdp/common/test/data_element_reader_test.cc @@ -16,7 +16,6 @@ #include "common/data_element_reader.h" -#include <base/logging.h> #include <gtest/gtest.h> #include "types/bluetooth/uuid.h" diff --git a/system/profile/sdp/sdp_logging_helper.h b/system/profile/sdp/sdp_logging_helper.h index 253ce925c3..d556b6e536 100644 --- a/system/profile/sdp/sdp_logging_helper.h +++ b/system/profile/sdp/sdp_logging_helper.h @@ -16,6 +16,8 @@ #pragma once +#include <bluetooth/log.h> + #include <iomanip> #include <iostream> #include <sstream> @@ -116,3 +118,14 @@ inline std::ostream& operator<<(std::ostream& os, const DataElementSize& size) { } // namespace sdp } // namespace bluetooth + +namespace fmt { +template <> +struct formatter<bluetooth::sdp::PduId> : ostream_formatter {}; +template <> +struct formatter<bluetooth::sdp::AttributeId> : ostream_formatter {}; +template <> +struct formatter<bluetooth::sdp::DataElementType> : ostream_formatter {}; +template <> +struct formatter<bluetooth::sdp::DataElementSize> : ostream_formatter {}; +} // namespace fmt diff --git a/system/rust/Android.bp b/system/rust/Android.bp index e5314089f0..2c7f72a1d9 100644 --- a/system/rust/Android.bp +++ b/system/rust/Android.bp @@ -125,6 +125,7 @@ cc_library_static { export_include_dirs: ["."], static_libs: [ "libbluetooth_hci_pdl", + "libbluetooth_log", "libbt_shim_bridge", "libbt_shim_ffi", "libchrome", diff --git a/system/stack/Android.bp b/system/stack/Android.bp index c47e96c557..114c62a88e 100644 --- a/system/stack/Android.bp +++ b/system/stack/Android.bp @@ -20,6 +20,7 @@ cc_library_static { "packages/modules/Bluetooth/system/types", ], static_libs: [ + "libbluetooth_log", "libbt_shim_bridge", ], shared_libs: [ @@ -138,6 +139,7 @@ cc_library_static { static_libs: [ "libbluetooth_crypto_toolbox", "libbluetooth_hci_pdl", + "libbluetooth_log", "libbt-btu-main-thread", "libbt-hci", "libbt-platform-protos-lite", @@ -233,6 +235,7 @@ cc_library_static { "btm/btm_sec.cc", "btm/btm_sec_cb.cc", "btm/btm_security_client_interface.cc", + "btm/security_event_parser.cc", "btu/btu_event.cc", "btu/btu_hcif.cc", "eatt/eatt.cc", @@ -295,6 +298,7 @@ cc_library_static { "libbluetooth_crypto_toolbox", "libbluetooth_gd", "libbluetooth_hci_pdl", + "libbluetooth_log", "libbt-hci", "libbt-platform-protos-lite", "libbt_shim_bridge", @@ -403,6 +407,7 @@ cc_fuzz { ], static_libs: [ "libbluetooth-types", + "libbluetooth_log", "libbt-platform-protos-lite", "libbt_shim_bridge", "libbt_shim_ffi", @@ -444,11 +449,16 @@ cc_fuzz { "fuzzers/gatt_fuzzer.cc", "gatt/*.cc", ], + shared_libs: [ + "server_configurable_flags", + ], static_libs: [ + "bluetooth_flags_c_lib", "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_hci_pdl", "libbluetooth_l2cap_pdl", + "libbluetooth_log", "libbluetooth_smp_pdl", "libbt-platform-protos-lite", "libbt_shim_bridge", @@ -496,6 +506,7 @@ cc_fuzz { "libbluetooth_crypto_toolbox", "libbluetooth_hci_pdl", "libbluetooth_l2cap_pdl", + "libbluetooth_log", "libbluetooth_smp_pdl", "libbt-platform-protos-lite", "libbt_shim_bridge", @@ -538,6 +549,7 @@ cc_fuzz { "libbluetooth-types", "libbluetooth_hci_pdl", "libbluetooth_l2cap_pdl", + "libbluetooth_log", "libbluetooth_smp_pdl", "libbt-platform-protos-lite", "libbt_shim_bridge", @@ -583,6 +595,7 @@ cc_fuzz { "libbluetooth-types", "libbluetooth_hci_pdl", "libbluetooth_l2cap_pdl", + "libbluetooth_log", "libbluetooth_smp_pdl", "libbt-platform-protos-lite", "libbt_shim_bridge", @@ -625,6 +638,7 @@ cc_fuzz { "libbluetooth-types", "libbluetooth_hci_pdl", "libbluetooth_l2cap_pdl", + "libbluetooth_log", "libbluetooth_smp_pdl", "libbt-platform-protos-lite", "libbt_shim_bridge", @@ -695,6 +709,7 @@ cc_test { "libbluetooth-types", "libbluetooth_core_rs", "libbluetooth_crypto_toolbox", + "libbluetooth_log", "libbt-audio-hal-interface", "libbt-bta", "libbt-bta-core", @@ -783,6 +798,7 @@ cc_test { "libbluetooth_gd", "libbluetooth_hci_pdl", "libbluetooth_l2cap_pdl", + "libbluetooth_log", "libbluetooth_smp_pdl", "libbt-btu-main-thread", "libbt-common", @@ -868,6 +884,7 @@ cc_test { "libbluetooth_gd", "libbluetooth_hci_pdl", "libbluetooth_l2cap_pdl", + "libbluetooth_log", "libbluetooth_smp_pdl", "libbt-btu-main-thread", "libbt-common", @@ -913,6 +930,7 @@ cc_test { static_libs: [ "android.system.suspend.control-V1-ndk", "libbluetooth-types", + "libbluetooth_log", "libgmock", "liblog", ], @@ -948,6 +966,7 @@ cc_test { static_libs: [ "libbluetooth-types", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt_shim_bridge", "libbt_shim_ffi", @@ -1001,6 +1020,7 @@ cc_test { "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt_shim_bridge", "libbt_shim_ffi", @@ -1070,6 +1090,7 @@ cc_test { "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt_shim_bridge", "libbt_shim_ffi", @@ -1186,6 +1207,7 @@ cc_test { "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt-sbc-decoder", "libbt-sbc-encoder", @@ -1239,6 +1261,7 @@ cc_test { ], static_libs: [ "libbluetooth_crypto_toolbox", + "libbluetooth_log", "libbt-common", "libbt_shim_bridge", "libchrome", @@ -1296,6 +1319,7 @@ cc_test { "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt-platform-protos-lite", "libbt_shim_bridge", @@ -1353,6 +1377,7 @@ cc_test { static_libs: [ "libbluetooth-types", "libbluetooth_hci_pdl", + "libbluetooth_log", "libbt-common", "libbt-platform-protos-lite", "libbt_shim_bridge", @@ -1419,6 +1444,7 @@ cc_test { static_libs: [ "libbluetooth-types", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt_shim_bridge", "libbt_shim_ffi", @@ -1520,6 +1546,7 @@ cc_test { "btm/hfp_lc3_encoder.cc", "btm/hfp_msbc_decoder.cc", "btm/hfp_msbc_encoder.cc", + "btm/security_event_parser.cc", "metrics/stack_metrics_logging.cc", "test/btm/peer_packet_types_test.cc", "test/btm/sco_hci_test.cc", @@ -1537,6 +1564,7 @@ cc_test { "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt-platform-protos-lite", "libbt-sbc-decoder", @@ -1595,6 +1623,7 @@ cc_test { ], static_libs: [ "libbluetooth_crypto_toolbox", + "libbluetooth_log", "libbt-common", "libbt_shim_bridge", "libbtdevice", @@ -1652,6 +1681,7 @@ cc_test { static_libs: [ "libbluetooth-types", "libbluetooth_crypto_toolbox", + "libbluetooth_log", "libbt-common", "libbt-platform-protos-lite", "libbt_shim_bridge", @@ -1728,6 +1758,7 @@ cc_test { static_libs: [ "libbluetooth-types", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt-platform-protos-lite", "libbt_shim_bridge", @@ -1810,9 +1841,11 @@ cc_test { "test/gatt/stack_gatt_test.cc", ], static_libs: [ + "bluetooth_flags_c_lib", "libbluetooth-types", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt-platform-protos-lite", "libbt_shim_bridge", @@ -1820,6 +1853,7 @@ cc_test { "libbtdevice", "libchrome", "libevent", + "libflagtest", "libgmock", "liblog", "libosi", @@ -1827,9 +1861,11 @@ cc_test { "libstatslog_bt", ], shared_libs: [ + "libbase", "libbinder_ndk", "libcrypto", "libcutils", + "server_configurable_flags", ], target: { android: { @@ -1878,6 +1914,7 @@ cc_test { ":TestMockBta", ":TestMockBtif", ":TestMockHci", + ":TestMockJni", ":TestMockLegacyHciCommands", ":TestMockMainShim", ":TestMockStackAcl", @@ -1898,6 +1935,7 @@ cc_test { static_libs: [ "libbluetooth-types", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt-platform-protos-lite", "libbt_shim_bridge", @@ -1988,6 +2026,7 @@ cc_test { static_libs: [ "libbluetooth-types", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt-platform-protos-lite", "libbt_shim_bridge", @@ -2062,6 +2101,7 @@ cc_test { static_libs: [ "libbluetooth-types", "libbluetooth_gd", + "libbluetooth_log", "libbt-common", "libbt-platform-protos-lite", "libbt_shim_bridge", diff --git a/system/stack/BUILD.gn b/system/stack/BUILD.gn index 1dcba27a46..ddf8e05032 100644 --- a/system/stack/BUILD.gn +++ b/system/stack/BUILD.gn @@ -113,6 +113,7 @@ source_set("stack") { "btm/btm_sec.cc", "btm/btm_sec_cb.cc", "btm/btm_security_client_interface.cc", + "btm/security_event_parser.cc", "btm/hfp_lc3_encoder_linux.cc", "btm/hfp_lc3_decoder_linux.cc", "btm/hfp_msbc_encoder.cc", @@ -221,7 +222,6 @@ source_set("stack") { "//bt/system/gd/rust/shim:init_flags_bridge_header", "//bt/system/stack/mmc", "//bt/system/types", - "//bt/system/types", ] configs += [ @@ -281,6 +281,7 @@ if (defined(use.android) && use.android) { libs = [ "dl", + "fmt", "pthread", "resolv", "rt", @@ -334,6 +335,7 @@ if (defined(use.android) && use.android) { libs = [ "dl", + "fmt", "pthread", "resolv", "rt", diff --git a/system/stack/acl/acl.h b/system/stack/acl/acl.h index dd10be8e4f..818c27ad4a 100644 --- a/system/stack/acl/acl.h +++ b/system/stack/acl/acl.h @@ -360,3 +360,6 @@ struct tACL_CB { }; tACL_CONN* btm_acl_for_bda(const RawAddress& bd_addr, tBT_TRANSPORT transport); + +void btm_acl_encrypt_change(uint16_t handle, uint8_t status, + uint8_t encr_enable);
\ No newline at end of file diff --git a/system/stack/avrc/avrc_api.cc b/system/stack/avrc/avrc_api.cc index adaf6de61c..760d079ccf 100644 --- a/system/stack/avrc/avrc_api.cc +++ b/system/stack/avrc/avrc_api.cc @@ -39,6 +39,7 @@ #include "stack/include/bt_hdr.h" #include "stack/include/bt_types.h" #include "stack/include/bt_uuid16.h" +#include "storage/config_keys.h" #include "types/raw_address.h" /***************************************************************************** @@ -1433,12 +1434,12 @@ void AVRC_SaveControllerVersion(const RawAddress& bdaddr, uint16_t old_version = 0; size_t version_value_size = sizeof(old_version); if (btif_config_get_bin(bdaddr.ToString(), - AVRCP_CONTROLLER_VERSION_CONFIG_KEY, + BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION, (uint8_t*)&old_version, &version_value_size) && new_version == old_version) { LOG_INFO("AVRC controller version same as cached config"); } else if (btif_config_set_bin( - bdaddr.ToString(), AVRCP_CONTROLLER_VERSION_CONFIG_KEY, + bdaddr.ToString(), BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION, (const uint8_t*)&new_version, sizeof(new_version))) { LOG_INFO("store AVRC controller version %x for %s into config.", new_version, ADDRESS_TO_LOGGABLE_CSTR(bdaddr)); diff --git a/system/stack/btm/btm_sec.cc b/system/stack/btm/btm_sec.cc index cec28c4dbd..7c482c9c79 100644 --- a/system/stack/btm/btm_sec.cc +++ b/system/stack/btm/btm_sec.cc @@ -3346,6 +3346,80 @@ void btm_sec_encrypt_change(uint16_t handle, tHCI_STATUS status, btm_sec_dev_rec_cback_event(p_dev_rec, btm_status, false); } +constexpr uint8_t MIN_KEY_SIZE = 7; + +static void read_encryption_key_size_complete_after_encryption_change( + uint8_t status, uint16_t handle, uint8_t key_size) { + if (status == HCI_ERR_INSUFFCIENT_SECURITY) { + /* If remote device stop the encryption before we call "Read Encryption Key + * Size", we might receive Insufficient Security, which means that link is + * no longer encrypted. */ + LOG_INFO("encryption stopped on link:0x%x", handle); + return; + } + + if (status != HCI_SUCCESS) { + LOG_ERROR("disconnecting, status:0x%x", status); + acl_disconnect_from_handle(handle, HCI_ERR_PEER_USER, + "stack::btu::btu_hcif::read_encryption_key_size_" + "complete_after_encryption_change Bad key size"); + return; + } + + if (key_size < MIN_KEY_SIZE) { + LOG_ERROR( + "encryption key too short, disconnecting. handle:0x%x,key_size:%d", + handle, key_size); + + acl_disconnect_from_handle( + handle, HCI_ERR_HOST_REJECT_SECURITY, + "stack::btu::btu_hcif::read_encryption_key_size_complete_after_" + "encryption_change Key Too Short"); + return; + } + + // good key size - succeed + btm_acl_encrypt_change(handle, static_cast<tHCI_STATUS>(status), + 1 /* enable */); + btm_sec_encrypt_change(handle, static_cast<tHCI_STATUS>(status), + 1 /* enable */); +} + +// TODO: Remove +void smp_cancel_start_encryption_attempt(); + +/******************************************************************************* + * + * Function btm_encryption_change_evt + * + * Description Process event HCI_ENCRYPTION_CHANGE_EVT + * + * Returns void + * + ******************************************************************************/ +void btm_sec_encryption_change_evt(uint16_t handle, tHCI_STATUS status, + uint8_t encr_enable) { + if (status != HCI_SUCCESS || encr_enable == 0 || + BTM_IsBleConnection(handle) || + !controller_get_interface()->supports_read_encryption_key_size() || + // Skip encryption key size check when using set_min_encryption_key_size + (bluetooth::common::init_flags::set_min_encryption_is_enabled() && + controller_get_interface()->supports_set_min_encryption_key_size())) { + if (status == HCI_ERR_CONNECTION_TOUT) { + smp_cancel_start_encryption_attempt(); + return; + } + + btm_acl_encrypt_change(handle, static_cast<tHCI_STATUS>(status), + encr_enable); + btm_sec_encrypt_change(handle, static_cast<tHCI_STATUS>(status), + encr_enable); + } else { + btsnd_hcic_read_encryption_key_size( + handle, + base::Bind(&read_encryption_key_size_complete_after_encryption_change)); + } +} /******************************************************************************* * * Function btm_sec_connect_after_reject_timeout @@ -3829,8 +3903,6 @@ void btm_sec_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr, } } -constexpr uint8_t MIN_KEY_SIZE = 7; - static void read_encryption_key_size_complete_after_key_refresh( uint8_t status, uint16_t handle, uint8_t key_size) { if (status == HCI_ERR_INSUFFCIENT_SECURITY) { diff --git a/system/stack/btm/btm_sec.h b/system/stack/btm/btm_sec.h index caa4668b96..8760c81ece 100644 --- a/system/stack/btm/btm_sec.h +++ b/system/stack/btm/btm_sec.h @@ -593,6 +593,18 @@ void btm_sec_auth_complete(uint16_t handle, tHCI_STATUS status); /******************************************************************************* * + * Function btm_sec_encryption_change_evt + * + * Description This function is called to process an encryption change. + * + * Returns void + * + ******************************************************************************/ +void btm_sec_encryption_change_evt(uint16_t handle, tHCI_STATUS status, + uint8_t encr_enable); + +/******************************************************************************* + * * Function btm_sec_encrypt_change * * Description This function is when encryption of the connection is diff --git a/system/stack/btm/security_event_parser.cc b/system/stack/btm/security_event_parser.cc new file mode 100644 index 0000000000..38b11b7cc2 --- /dev/null +++ b/system/stack/btm/security_event_parser.cc @@ -0,0 +1,277 @@ +/* + * 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 "security_event_parser.h" + +#include <optional> +#include <string> + +#include "btm_sec.h" +#include "common/metrics.h" +#include "hci/hci_packets.h" +#include "main/shim/helpers.h" +#include "stack/include/btm_sec_api_types.h" +#include "stack/include/hci_error_code.h" +#include "stack/include/sec_hci_link_interface.h" +#include "stack/include/stack_metrics_logging.h" +#include "types/raw_address.h" + +using namespace bluetooth::hci; +using android::bluetooth::hci::CMD_UNKNOWN; +using android::bluetooth::hci::STATUS_UNKNOWN; +using bluetooth::common::kUnknownConnectionHandle; + +namespace bluetooth::stack::btm { +namespace { +static void log_address_and_status(const Address& bda, EventCode event_code, + ErrorCode event_status) { + uint32_t cmd = android::bluetooth::hci::CMD_UNKNOWN; + uint16_t status = static_cast<uint16_t>(event_status); + uint16_t reason = android::bluetooth::hci::STATUS_UNKNOWN; + uint16_t handle = bluetooth::common::kUnknownConnectionHandle; + int64_t value = 0; + log_classic_pairing_event(ToRawAddress(bda), handle, cmd, + static_cast<uint16_t>(event_code), status, reason, + value); +} +static void log_address(const Address& bda, EventCode event_code) { + uint32_t cmd = android::bluetooth::hci::CMD_UNKNOWN; + uint16_t status = android::bluetooth::hci::STATUS_UNKNOWN; + uint16_t reason = android::bluetooth::hci::STATUS_UNKNOWN; + uint16_t handle = bluetooth::common::kUnknownConnectionHandle; + int64_t value = 0; + log_classic_pairing_event(ToRawAddress(bda), handle, cmd, + static_cast<uint16_t>(event_code), status, reason, + value); +} +static void parse_encryption_change(const EventView event) { + auto change_opt = EncryptionChangeView::CreateOptional(event); + ASSERT(change_opt.has_value()); + auto change = change_opt.value(); + + ErrorCode status = change.GetStatus(); + uint16_t handle = change.GetConnectionHandle(); + EncryptionEnabled encr_enable = change.GetEncryptionEnabled(); + + btm_sec_encryption_change_evt(handle, static_cast<tHCI_STATUS>(status), + static_cast<uint8_t>(encr_enable)); + log_classic_pairing_event(ToRawAddress(Address::kEmpty), handle, + android::bluetooth::hci::CMD_UNKNOWN, + static_cast<uint32_t>(change.GetEventCode()), + static_cast<uint16_t>(status), + android::bluetooth::hci::STATUS_UNKNOWN, 0); +} +static void parse_change_connection_link_key_complete(const EventView event) { + auto complete_opt = + ChangeConnectionLinkKeyCompleteView::CreateOptional(event); + ASSERT(complete_opt.has_value()); + auto complete = complete_opt.value(); + + log_classic_pairing_event(ToRawAddress(Address::kEmpty), + complete.GetConnectionHandle(), + android::bluetooth::hci::CMD_UNKNOWN, + static_cast<uint32_t>(complete.GetEventCode()), + static_cast<uint16_t>(complete.GetStatus()), + android::bluetooth::hci::STATUS_UNKNOWN, 0); +} +static void parse_central_link_key_complete(const EventView event) { + auto event_opt = CentralLinkKeyCompleteView::CreateOptional(event); + ASSERT(event_opt.has_value()); + auto complete = event_opt.value(); + + LOG_INFO("Unhandled event: %s", EventCodeText(event.GetEventCode()).c_str()); +} +static void parse_return_link_keys(const EventView event) { + auto event_opt = ReturnLinkKeysView::CreateOptional(event); + ASSERT(event_opt.has_value()); + auto view = event_opt.value(); + + LOG_INFO("Unhandled event: %s", EventCodeText(event.GetEventCode()).c_str()); +} +static void parse_pin_code_request(const EventView event) { + auto event_opt = PinCodeRequestView::CreateOptional(event); + ASSERT(event_opt.has_value()); + auto request = event_opt.value(); + btm_sec_pin_code_request(ToRawAddress(request.GetBdAddr())); +} +static void parse_link_key_request(const EventView event) { + auto event_opt = LinkKeyRequestView::CreateOptional(event); + ASSERT(event_opt.has_value()); + auto request = event_opt.value(); + + btm_sec_link_key_request(ToRawAddress(request.GetBdAddr())); + log_address(request.GetBdAddr(), event.GetEventCode()); +} +static void parse_link_key_notification(const EventView event) { + auto event_opt = LinkKeyNotificationView::CreateOptional(event); + ASSERT(event_opt.has_value()); + auto notification = event_opt.value(); + + btm_sec_link_key_notification( + ToRawAddress(notification.GetBdAddr()), notification.GetLinkKey(), + static_cast<uint8_t>(notification.GetKeyType())); + log_address(notification.GetBdAddr(), event.GetEventCode()); +} +static void parse_encryption_key_refresh_complete(const EventView event) { + auto event_opt = EncryptionKeyRefreshCompleteView::CreateOptional(event); + ASSERT(event_opt.has_value()); + auto refresh = event_opt.value(); + + btm_sec_encryption_key_refresh_complete( + refresh.GetConnectionHandle(), + static_cast<tHCI_STATUS>(refresh.GetStatus())); +} +static void parse_io_capabilities_req(const EventView event) { + auto event_opt = IoCapabilityRequestView::CreateOptional(event); + ASSERT(event_opt.has_value()); + auto request = event_opt.value(); + + RawAddress peer = ToRawAddress(request.GetBdAddr()); + + btm_io_capabilities_req(peer); + log_address(request.GetBdAddr(), event.GetEventCode()); +} +static void parse_io_capabilities_rsp(const EventView event) { + auto response_opt = IoCapabilityResponseView::CreateOptional(event); + ASSERT(response_opt.has_value()); + auto response = response_opt.value(); + + tBTM_SP_IO_RSP evt_data{ + .bd_addr = ToRawAddress(response.GetBdAddr()), + .io_cap = static_cast<tBTM_IO_CAP>(response.GetIoCapability()), + .oob_data = static_cast<tBTM_OOB_DATA>(response.GetOobDataPresent()), + .auth_req = + static_cast<tBTM_AUTH_REQ>(response.GetAuthenticationRequirements()), + }; + + btm_io_capabilities_rsp(evt_data); + log_address(response.GetBdAddr(), event.GetEventCode()); +} +static void parse_remote_oob_data_request(const EventView event) { + auto event_opt = RemoteOobDataRequestView::CreateOptional(event); + ASSERT(event_opt.has_value()); + auto request = event_opt.value(); + + btm_rem_oob_req(ToRawAddress(request.GetBdAddr())); + log_address(request.GetBdAddr(), event.GetEventCode()); +} +static void parse_simple_pairing_complete(const EventView event) { + auto event_opt = SimplePairingCompleteView::CreateOptional(event); + ASSERT(event_opt.has_value()); + auto complete = event_opt.value(); + + btm_simple_pair_complete(ToRawAddress(complete.GetBdAddr()), + static_cast<uint8_t>(complete.GetStatus())); + log_address_and_status(complete.GetBdAddr(), event.GetEventCode(), + complete.GetStatus()); +} +static void parse_user_passkey_notification(const EventView event) { + auto event_opt = UserPasskeyNotificationView::CreateOptional(event); + ASSERT(event_opt.has_value()); + auto notification = event_opt.value(); + + btm_proc_sp_req_evt(BTM_SP_KEY_NOTIF_EVT, + ToRawAddress(notification.GetBdAddr()), + notification.GetPasskey()); + log_address(notification.GetBdAddr(), event.GetEventCode()); +} +static void parse_keypress_notification(const EventView event) { + auto event_opt = KeypressNotificationView::CreateOptional(event); + ASSERT(event_opt.has_value()); + auto notification = event_opt.value(); + + LOG_INFO("Unhandled event: %s", EventCodeText(event.GetEventCode()).c_str()); + log_address(notification.GetBdAddr(), event.GetEventCode()); +} +static void parse_user_confirmation_request(const EventView event) { + auto event_opt = UserConfirmationRequestView::CreateOptional(event); + ASSERT(event_opt.has_value()); + auto request = event_opt.value(); + + btm_proc_sp_req_evt(BTM_SP_CFM_REQ_EVT, ToRawAddress(request.GetBdAddr()), + request.GetNumericValue()); + log_address(request.GetBdAddr(), event.GetEventCode()); +} +static void parse_user_passkey_request(const EventView event) { + auto event_opt = UserPasskeyRequestView::CreateOptional(event); + ASSERT(event_opt.has_value()); + auto request = event_opt.value(); + + btm_proc_sp_req_evt(BTM_SP_KEY_REQ_EVT, ToRawAddress(request.GetBdAddr()), + 0 /* No value needed */); + log_address(request.GetBdAddr(), event.GetEventCode()); +} +} // namespace +} // namespace bluetooth::stack::btm + +namespace bluetooth::stack::btm { + +void SecurityEventParser::OnSecurityEvent(bluetooth::hci::EventView event) { + switch (event.GetEventCode()) { + case EventCode::ENCRYPTION_CHANGE: + parse_encryption_change(event); + break; + case EventCode::CHANGE_CONNECTION_LINK_KEY_COMPLETE: + parse_change_connection_link_key_complete(event); + break; + case EventCode::CENTRAL_LINK_KEY_COMPLETE: + parse_central_link_key_complete(event); + break; + case EventCode::RETURN_LINK_KEYS: + parse_return_link_keys(event); + break; + case EventCode::PIN_CODE_REQUEST: + parse_pin_code_request(event); + break; + case EventCode::LINK_KEY_REQUEST: + parse_link_key_request(event); + break; + case EventCode::LINK_KEY_NOTIFICATION: + parse_link_key_notification(event); + break; + case EventCode::ENCRYPTION_KEY_REFRESH_COMPLETE: + parse_encryption_key_refresh_complete(event); + break; + case EventCode::IO_CAPABILITY_REQUEST: + parse_io_capabilities_req(event); + break; + case EventCode::IO_CAPABILITY_RESPONSE: + parse_io_capabilities_rsp(event); + break; + case EventCode::REMOTE_OOB_DATA_REQUEST: + parse_remote_oob_data_request(event); + break; + case EventCode::SIMPLE_PAIRING_COMPLETE: + parse_simple_pairing_complete(event); + break; + case EventCode::USER_PASSKEY_NOTIFICATION: + parse_user_passkey_notification(event); + break; + case EventCode::KEYPRESS_NOTIFICATION: + parse_keypress_notification(event); + break; + case EventCode::USER_CONFIRMATION_REQUEST: + parse_user_confirmation_request(event); + break; + case EventCode::USER_PASSKEY_REQUEST: + parse_user_passkey_request(event); + break; + default: + LOG_ERROR("Unhandled event %s", + EventCodeText(event.GetEventCode()).c_str()); + } +} +} // namespace bluetooth::stack::btm diff --git a/system/stack/btm/security_event_parser.h b/system/stack/btm/security_event_parser.h new file mode 100644 index 0000000000..f29e3724e6 --- /dev/null +++ b/system/stack/btm/security_event_parser.h @@ -0,0 +1,30 @@ +/* + * 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. + */ + +#pragma once + +#include "hci/hci_packets.h" + +namespace bluetooth::stack::btm { + +class SecurityEventParser { + public: + SecurityEventParser() = default; + virtual ~SecurityEventParser() = default; + void OnSecurityEvent(bluetooth::hci::EventView event); +}; + +} // namespace bluetooth::stack::btm diff --git a/system/stack/btu/btu_hcif.cc b/system/stack/btu/btu_hcif.cc index dfbf086d69..c95e7e4ab1 100644 --- a/system/stack/btu/btu_hcif.cc +++ b/system/stack/btu/btu_hcif.cc @@ -86,7 +86,6 @@ static void btu_hcif_read_rmt_ext_features_comp_evt(uint8_t* p, static void btu_hcif_command_complete_evt(BT_HDR* response, void* context); static void btu_hcif_command_status_evt(uint8_t status, BT_HDR* command, void* context); -static void btu_hcif_hardware_error_evt(uint8_t* p); static void btu_hcif_mode_change_evt(uint8_t* p); static void btu_hcif_link_key_notification_evt(const uint8_t* p); static void btu_hcif_read_clock_off_comp_evt(uint8_t* p); @@ -275,9 +274,6 @@ void btu_hcif_process_event(UNUSED_ATTR uint8_t controller_id, "Someone didn't go through the hci transmit_command function.", __func__); break; - case HCI_HARDWARE_ERROR_EVT: - btu_hcif_hardware_error_evt(p); - break; case HCI_MODE_CHANGE_EVT: btu_hcif_mode_change_evt(p); break; @@ -399,6 +395,7 @@ void btu_hcif_process_event(UNUSED_ATTR uint8_t controller_id, break; // Events now captured by gd::hci_layer module + case HCI_HARDWARE_ERROR_EVT: case HCI_NUM_COMPL_DATA_PKTS_EVT: // EventCode::NUMBER_OF_COMPLETED_PACKETS case HCI_CONNECTION_COMP_EVT: // EventCode::CONNECTION_COMPLETE case HCI_CONNECTION_REQUEST_EVT: // EventCode::CONNECTION_REQUEST @@ -884,44 +881,6 @@ static void btu_hcif_rmt_name_request_comp_evt(const uint8_t* p, btm_sec_rmt_name_request_complete(&bd_addr, p, to_hci_status_code(status)); } -constexpr uint8_t MIN_KEY_SIZE = 7; - -static void read_encryption_key_size_complete_after_encryption_change(uint8_t status, uint16_t handle, - uint8_t key_size) { - if (status == HCI_ERR_INSUFFCIENT_SECURITY) { - /* If remote device stop the encryption before we call "Read Encryption Key - * Size", we might receive Insufficient Security, which means that link is - * no longer encrypted. */ - LOG_INFO("encryption stopped on link:0x%x", handle); - return; - } - - if (status != HCI_SUCCESS) { - LOG_ERROR("disconnecting, status:0x%x", status); - acl_disconnect_from_handle(handle, HCI_ERR_PEER_USER, - "stack::btu::btu_hcif::read_encryption_key_size_" - "complete_after_encryption_change Bad key size"); - return; - } - - if (key_size < MIN_KEY_SIZE) { - LOG_ERROR( - "encryption key too short, disconnecting. handle:0x%x,key_size:%d", - handle, key_size); - - acl_disconnect_from_handle( - handle, HCI_ERR_HOST_REJECT_SECURITY, - "stack::btu::btu_hcif::read_encryption_key_size_complete_after_" - "encryption_change Key Too Short"); - return; - } - - // good key size - succeed - btm_acl_encrypt_change(handle, static_cast<tHCI_STATUS>(status), - 1 /* enable */); - btm_sec_encrypt_change(handle, static_cast<tHCI_STATUS>(status), - 1 /* enable */); -} /******************************************************************************* * * Function btu_hcif_encryption_change_evt @@ -940,26 +899,8 @@ static void btu_hcif_encryption_change_evt(uint8_t* p) { STREAM_TO_UINT16(handle, p); STREAM_TO_UINT8(encr_enable, p); - if (status != HCI_SUCCESS || encr_enable == 0 || - BTM_IsBleConnection(handle) || - !controller_get_interface()->supports_read_encryption_key_size() || - // Skip encryption key size check when using set_min_encryption_key_size - (bluetooth::common::init_flags::set_min_encryption_is_enabled() && - controller_get_interface()->supports_set_min_encryption_key_size())) { - if (status == HCI_ERR_CONNECTION_TOUT) { - smp_cancel_start_encryption_attempt(); - return; - } - - btm_acl_encrypt_change(handle, static_cast<tHCI_STATUS>(status), - encr_enable); - btm_sec_encrypt_change(handle, static_cast<tHCI_STATUS>(status), - encr_enable); - } else { - btsnd_hcic_read_encryption_key_size( - handle, - base::Bind(&read_encryption_key_size_complete_after_encryption_change)); - } + btm_sec_encryption_change_evt(handle, static_cast<tHCI_STATUS>(status), + encr_enable); } /******************************************************************************* @@ -1355,20 +1296,6 @@ static void btu_hcif_command_status_evt(uint8_t status, BT_HDR* command, /******************************************************************************* * - * Function btu_hcif_hardware_error_evt - * - * Description Process event HCI_HARDWARE_ERROR_EVT - * - * Returns void - * - ******************************************************************************/ -static void btu_hcif_hardware_error_evt(uint8_t* p) { - LOG_ERROR("UNHANDLED Ctlr H/w error event - code:0x%x", *p); - BTA_sys_signal_hw_error(); -} - -/******************************************************************************* - * * Function btu_hcif_mode_change_evt * * Description Process event HCI_MODE_CHANGE_EVT diff --git a/system/stack/gatt/gatt_main.cc b/system/stack/gatt/gatt_main.cc index 815817e175..ac8f2ac332 100644 --- a/system/stack/gatt/gatt_main.cc +++ b/system/stack/gatt/gatt_main.cc @@ -22,6 +22,7 @@ * ******************************************************************************/ +#include <android_bluetooth_flags.h> #include <base/logging.h> #include "btif/include/btif_dm.h" @@ -463,7 +464,11 @@ bool gatt_act_connect(tGATT_REG* p_reg, const RawAddress& bd_addr, namespace connection_manager { void on_connection_timed_out(uint8_t app_id, const RawAddress& address) { - gatt_le_connect_cback(L2CAP_ATT_CID, address, false, 0xff, BT_TRANSPORT_LE); + if (IS_FLAG_ENABLED(enumerate_gatt_errors)) { + gatt_le_connect_cback(L2CAP_ATT_CID, address, false, 0x08, BT_TRANSPORT_LE); + } else { + gatt_le_connect_cback(L2CAP_ATT_CID, address, false, 0xff, BT_TRANSPORT_LE); + } } } // namespace connection_manager diff --git a/system/stack/include/acl_hci_link_interface.h b/system/stack/include/acl_hci_link_interface.h index 95cc23d847..8e3289424c 100644 --- a/system/stack/include/acl_hci_link_interface.h +++ b/system/stack/include/acl_hci_link_interface.h @@ -39,8 +39,6 @@ void on_acl_br_edr_failed(const RawAddress& bda, tHCI_STATUS status, bool locally_initiated); void btm_acl_disconnected(tHCI_STATUS status, uint16_t handle, tHCI_STATUS reason); -void btm_acl_encrypt_change(uint16_t handle, uint8_t status, - uint8_t encr_enable); void btm_acl_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr, tHCI_ROLE new_role); void btm_rejectlist_role_change_device(const RawAddress& bd_addr, diff --git a/system/stack/include/avdt_api.h b/system/stack/include/avdt_api.h index 6139d58818..301898893f 100644 --- a/system/stack/include/avdt_api.h +++ b/system/stack/include/avdt_api.h @@ -41,8 +41,6 @@ ****************************************************************************/ #define AVDT_VERSION_1_3 0x0103 -#define AVDTP_VERSION_CONFIG_KEY "AvdtpVersion" - /* Maximum size in bytes of the codec capabilities information element. */ #define AVDT_CODEC_SIZE 20 diff --git a/system/stack/include/avrc_api.h b/system/stack/include/avrc_api.h index 0404bb39a9..8aa6f500fe 100644 --- a/system/stack/include/avrc_api.h +++ b/system/stack/include/avrc_api.h @@ -150,15 +150,6 @@ "persist.bluetooth.dynamic_avrcp.enable" #endif -/* Avrcp controller version key for bt_config.conf */ -#ifndef AVRCP_CONTROLLER_VERSION_CONFIG_KEY -#define AVRCP_CONTROLLER_VERSION_CONFIG_KEY "AvrcpControllerVersion" -#endif - -#ifndef AV_REM_CTRL_FEATURES_CONFIG_KEY -#define AV_REM_CTRL_FEATURES_CONFIG_KEY "AvrcpPeerFeatures" -#endif - /* Supported categories */ #define AVRC_SUPF_CT_CAT1 0x0001 /* Category 1 */ #define AVRC_SUPF_CT_CAT2 0x0002 /* Category 2 */ diff --git a/system/stack/include/gatt_api.h b/system/stack/include/gatt_api.h index e585925153..d5d6189028 100644 --- a/system/stack/include/gatt_api.h +++ b/system/stack/include/gatt_api.h @@ -80,6 +80,7 @@ typedef enum GattStatus : uint8_t { GATT_DUP_REG = 0x90, /* 0x90 */ GATT_ALREADY_OPEN = 0x91, /* 0x91 */ GATT_CANCEL = 0x92, /* 0x92 */ + GATT_CONNECTION_TIMEOUT = 0x93, /* = 0xE0 ~ 0xFC reserved for future use */ /* Client Characteristic Configuration Descriptor Improperly Configured */ @@ -130,6 +131,7 @@ inline std::string gatt_status_text(const tGATT_STATUS& status) { CASE_RETURN_TEXT(GATT_DUP_REG); CASE_RETURN_TEXT(GATT_ALREADY_OPEN); CASE_RETURN_TEXT(GATT_CANCEL); + CASE_RETURN_TEXT(GATT_CONNECTION_TIMEOUT); CASE_RETURN_TEXT(GATT_CCC_CFG_ERR); CASE_RETURN_TEXT(GATT_PRC_IN_PROGRESS); CASE_RETURN_TEXT(GATT_OUT_OF_RANGE); diff --git a/system/stack/include/sec_hci_link_interface.h b/system/stack/include/sec_hci_link_interface.h index cc85265630..4b07e84f21 100644 --- a/system/stack/include/sec_hci_link_interface.h +++ b/system/stack/include/sec_hci_link_interface.h @@ -36,6 +36,8 @@ void btm_sec_auth_complete(uint16_t handle, tHCI_STATUS status); void btm_sec_disconnected(uint16_t handle, tHCI_STATUS reason, std::string); void btm_sec_encrypt_change(uint16_t handle, tHCI_STATUS status, uint8_t encr_enable); +void btm_sec_encryption_change_evt(uint16_t handle, tHCI_STATUS status, + uint8_t encr_enable); void btm_sec_encryption_key_refresh_complete(uint16_t handle, tHCI_STATUS status); void btm_sec_link_key_notification(const RawAddress& p_bda, diff --git a/system/stack/rfcomm/port_api.cc b/system/stack/rfcomm/port_api.cc index 239f1a306c..0ac308b079 100644 --- a/system/stack/rfcomm/port_api.cc +++ b/system/stack/rfcomm/port_api.cc @@ -330,7 +330,7 @@ int RFCOMM_RemoveServer(uint16_t handle) { p_port->p_mgmt_callback = nullptr; if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) { - VLOG(1) << __func__ << ": handle " << handle << " not opened"; + LOG_DEBUG("handle %u not opened", handle); return (PORT_SUCCESS); } LOG(INFO) << __func__ << ": handle=" << handle; diff --git a/system/stack/rfcomm/port_rfc.cc b/system/stack/rfcomm/port_rfc.cc index 5ceffd9b8c..2f5908766b 100644 --- a/system/stack/rfcomm/port_rfc.cc +++ b/system/stack/rfcomm/port_rfc.cc @@ -427,10 +427,8 @@ void PORT_ParNegCnf(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl, void PORT_DlcEstablishInd(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu) { tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci); - LOG_VERBOSE("PORT_DlcEstablishInd p_mcb:%p, dlci:%d mtu:%di, p_port:%p", - p_mcb, dlci, mtu, p_port); - VLOG(1) << __func__ - << " p_mcb addr:" << ADDRESS_TO_LOGGABLE_STR(p_mcb->bd_addr); + LOG_VERBOSE("p_mcb:%p, dlci:%d mtu:%di, p_port:%p, bd_addr:%s", p_mcb, dlci, + mtu, p_port, ADDRESS_TO_LOGGABLE_CSTR(p_mcb->bd_addr)); if (!p_port) { /* This can be a first request for this port */ @@ -710,8 +708,8 @@ void PORT_LineStatusInd(tRFC_MCB* p_mcb, uint8_t dlci, uint8_t line_status) { * ******************************************************************************/ void PORT_DlcReleaseInd(tRFC_MCB* p_mcb, uint8_t dlci) { - VLOG(1) << __func__ << ": dlci=" << std::to_string(dlci) - << ", bd_addr=" << p_mcb->bd_addr; + LOG_VERBOSE("dlci:%u, bd_addr:%s", dlci, + ADDRESS_TO_LOGGABLE_CSTR(p_mcb->bd_addr)); tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci); if (!p_port) return; port_rfc_closed(p_port, PORT_CLOSED); diff --git a/system/stack/rfcomm/port_utils.cc b/system/stack/rfcomm/port_utils.cc index ca7b439640..9023923897 100644 --- a/system/stack/rfcomm/port_utils.cc +++ b/system/stack/rfcomm/port_utils.cc @@ -287,14 +287,13 @@ tRFC_MCB* port_find_mcb(const RawAddress& bd_addr) { for (tRFC_MCB& mcb : rfc_cb.port.rfc_mcb) { if ((mcb.state != RFC_MX_STATE_IDLE) && (mcb.bd_addr == bd_addr)) { /* Multiplexer channel found do not change anything */ - VLOG(1) << __func__ - << ": found bd_addr=" << ADDRESS_TO_LOGGABLE_STR(bd_addr) - << ", rfc_mcb=" << &mcb << ", lcid=" << loghex(mcb.lcid); + LOG_VERBOSE("found, bd_addr:%s, rfc_mcb:%p, lcid:%s", + ADDRESS_TO_LOGGABLE_CSTR(bd_addr), &mcb, + loghex(mcb.lcid).c_str()); return &mcb; } } - VLOG(1) << __func__ - << ": not found, bd_addr:" << ADDRESS_TO_LOGGABLE_STR(bd_addr); + LOG_WARN("not found, bd_addr:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr)); return nullptr; } diff --git a/system/stack/rfcomm/rfc_l2cap_if.cc b/system/stack/rfcomm/rfc_l2cap_if.cc index 9f9b072448..5bc9301005 100644 --- a/system/stack/rfcomm/rfc_l2cap_if.cc +++ b/system/stack/rfcomm/rfc_l2cap_if.cc @@ -234,8 +234,8 @@ void RFCOMM_ConfigCnf(uint16_t lcid, UNUSED_ATTR uint16_t initiator, * ******************************************************************************/ void RFCOMM_DisconnectInd(uint16_t lcid, bool is_conf_needed) { - VLOG(1) << __func__ << ": lcid=" << loghex(lcid) - << ", is_conf_needed=" << is_conf_needed; + LOG_VERBOSE("lcid:%s, is_conf_needed:%d", loghex(lcid).c_str(), + is_conf_needed); tRFC_MCB* p_mcb = rfc_find_lcid_mcb(lcid); if (!p_mcb) { LOG(WARNING) << __func__ << ": no mcb for lcid " << loghex(lcid); diff --git a/system/stack/rfcomm/rfc_mx_fsm.cc b/system/stack/rfcomm/rfc_mx_fsm.cc index 06e68b056e..0d99fd32c0 100644 --- a/system/stack/rfcomm/rfc_mx_fsm.cc +++ b/system/stack/rfcomm/rfc_mx_fsm.cc @@ -65,7 +65,7 @@ static void rfc_mx_conf_cnf(tRFC_MCB* p_mcb, uint16_t result); * * Function rfc_mx_sm_execute * - * Description This function sends multiplexor events through the state + * Description This function sends multiplexer events through the state * machine. * * Returns void @@ -75,8 +75,8 @@ void rfc_mx_sm_execute(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, void* p_data) { CHECK(p_mcb != nullptr) << __func__ << ": NULL mcb for event " << event; LOG_INFO( - "RFCOMM peer:%s event:%d state:%s", ADDRESS_TO_LOGGABLE_CSTR(p_mcb->bd_addr), - event, + "RFCOMM peer:%s event:%d state:%s", + ADDRESS_TO_LOGGABLE_CSTR(p_mcb->bd_addr), event, rfcomm_mx_state_text(static_cast<tRFC_MX_STATE>(p_mcb->state)).c_str()); switch (p_mcb->state) { diff --git a/system/stack/rfcomm/rfc_port_fsm.cc b/system/stack/rfcomm/rfc_port_fsm.cc index 8acb491299..b9724c3671 100644 --- a/system/stack/rfcomm/rfc_port_fsm.cc +++ b/system/stack/rfcomm/rfc_port_fsm.cc @@ -81,11 +81,9 @@ static void rfc_set_port_state(tPORT_STATE* port_pars, MX_FRAME* p_frame); ******************************************************************************/ void rfc_port_sm_execute(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) { CHECK(p_port != nullptr) << __func__ << ": NULL port event " << event; - VLOG(1) << __func__ - << ": BD_ADDR=" << ADDRESS_TO_LOGGABLE_STR(p_port->bd_addr) - << ", PORT=" << std::to_string(p_port->handle) - << ", STATE=" << std::to_string(p_port->rfc.state) - << ", EVENT=" << event; + LOG_INFO("bd_addr:%s, port:%u, state:%u, event:%d", + ADDRESS_TO_LOGGABLE_CSTR(p_port->bd_addr), p_port->handle, + p_port->rfc.state, event); switch (p_port->rfc.state) { case RFC_STATE_CLOSED: rfc_port_sm_state_closed(p_port, event, p_data); diff --git a/system/stack/rfcomm/rfc_utils.cc b/system/stack/rfcomm/rfc_utils.cc index c25d58f653..16439f11b6 100644 --- a/system/stack/rfcomm/rfc_utils.cc +++ b/system/stack/rfcomm/rfc_utils.cc @@ -134,15 +134,13 @@ tRFC_MCB* rfc_alloc_multiplexer_channel(const RawAddress& bd_addr, bool is_initiator) { int i, j; tRFC_MCB* p_mcb = NULL; - VLOG(1) << __func__ << ": bd_addr:" << ADDRESS_TO_LOGGABLE_STR(bd_addr); - LOG_VERBOSE("rfc_alloc_multiplexer_channel:is_initiator:%d", is_initiator); + LOG_VERBOSE("bd_addr:%s, is_initiator:%d", ADDRESS_TO_LOGGABLE_CSTR(bd_addr), + is_initiator); for (i = 0; i < MAX_BD_CONNECTIONS; i++) { - LOG_VERBOSE( - "rfc_alloc_multiplexer_channel rfc_cb.port.rfc_mcb[%d].state:%d", i, - rfc_cb.port.rfc_mcb[i].state); - VLOG(1) << "(rfc_cb.port.rfc_mcb[i].bd_addr:" - << ADDRESS_TO_LOGGABLE_STR(rfc_cb.port.rfc_mcb[i].bd_addr); + LOG_VERBOSE("rfc_cb.port.rfc_mcb[%d] - state:%d, bd_addr:%s", i, + rfc_cb.port.rfc_mcb[i].state, + ADDRESS_TO_LOGGABLE_CSTR(rfc_cb.port.rfc_mcb[i].bd_addr)); if ((rfc_cb.port.rfc_mcb[i].state != RFC_MX_STATE_IDLE) && rfc_cb.port.rfc_mcb[i].bd_addr == bd_addr) { diff --git a/system/stack/sdp/sdp_utils.cc b/system/stack/sdp/sdp_utils.cc index fe29368168..2b7780ed7d 100644 --- a/system/stack/sdp/sdp_utils.cc +++ b/system/stack/sdp/sdp_utils.cc @@ -54,6 +54,7 @@ #include "stack/include/sdpdefs.h" #include "stack/include/stack_metrics_logging.h" #include "stack/sdp/sdpint.h" +#include "storage/config_keys.h" #include "types/bluetooth/uuid.h" #include "types/raw_address.h" @@ -320,13 +321,13 @@ void sdpu_log_attribute_metrics(const RawAddress& bda, std::string bda_string = bda.ToString(); // write manufacturer, model, HW version to config - btif_config_set_int(bda_string, BT_CONFIG_KEY_SDP_DI_MANUFACTURER, + btif_config_set_int(bda_string, BTIF_STORAGE_KEY_SDP_DI_MANUFACTURER, di_record.rec.vendor); - btif_config_set_int(bda_string, BT_CONFIG_KEY_SDP_DI_MODEL, + btif_config_set_int(bda_string, BTIF_STORAGE_KEY_SDP_DI_MODEL, di_record.rec.product); - btif_config_set_int(bda_string, BT_CONFIG_KEY_SDP_DI_HW_VERSION, + btif_config_set_int(bda_string, BTIF_STORAGE_KEY_SDP_DI_HW_VERSION, di_record.rec.version); - btif_config_set_int(bda_string, BT_CONFIG_KEY_SDP_DI_VENDOR_ID_SRC, + btif_config_set_int(bda_string, BTIF_STORAGE_KEY_SDP_DI_VENDOR_ID_SRC, di_record.rec.vendor_id_source); } } @@ -1497,7 +1498,7 @@ void sdpu_set_avrc_target_version(const tSDP_ATTRIBUTE* p_attr, // Read the remote device's AVRC Controller version from local storage uint16_t cached_version = 0; size_t version_value_size = btif_config_get_bin_length( - bdaddr->ToString(), AVRCP_CONTROLLER_VERSION_CONFIG_KEY); + bdaddr->ToString(), BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION); if (version_value_size != sizeof(cached_version)) { LOG_ERROR( "cached value len wrong, bdaddr=%s. Len is %zu but should be %zu.", @@ -1507,7 +1508,7 @@ void sdpu_set_avrc_target_version(const tSDP_ATTRIBUTE* p_attr, } if (!btif_config_get_bin(bdaddr->ToString(), - AVRCP_CONTROLLER_VERSION_CONFIG_KEY, + BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION, (uint8_t*)&cached_version, &version_value_size)) { LOG_INFO( "no cached AVRC Controller version for %s. " @@ -1582,7 +1583,7 @@ void sdpu_set_avrc_target_features(const tSDP_ATTRIBUTE* p_attr, // Read the remote device's AVRC Controller version from local storage uint16_t avrcp_peer_features = 0; size_t version_value_size = btif_config_get_bin_length( - bdaddr->ToString(), AV_REM_CTRL_FEATURES_CONFIG_KEY); + bdaddr->ToString(), BTIF_STORAGE_KEY_AV_REM_CTRL_FEATURES); if (version_value_size != sizeof(avrcp_peer_features)) { LOG_ERROR( "cached value len wrong, bdaddr=%s. Len is %zu but should be %zu.", @@ -1591,9 +1592,9 @@ void sdpu_set_avrc_target_features(const tSDP_ATTRIBUTE* p_attr, return; } - if (!btif_config_get_bin(bdaddr->ToString(), AV_REM_CTRL_FEATURES_CONFIG_KEY, - (uint8_t*)&avrcp_peer_features, - &version_value_size)) { + if (!btif_config_get_bin( + bdaddr->ToString(), BTIF_STORAGE_KEY_AV_REM_CTRL_FEATURES, + (uint8_t*)&avrcp_peer_features, &version_value_size)) { LOG_ERROR("Unable to fetch cached AVRC features"); return; } diff --git a/system/stack/smp/smp_keys.cc b/system/stack/smp/smp_keys.cc index 61d92c4847..d7468e748b 100644 --- a/system/stack/smp/smp_keys.cc +++ b/system/stack/smp/smp_keys.cc @@ -27,6 +27,7 @@ #include <base/functional/callback.h> #include <algorithm> +#include <cstdint> #include <cstring> #include "crypto_toolbox/crypto_toolbox.h" @@ -46,7 +47,8 @@ #include "stack/include/btm_ble_sec_api.h" #include "types/raw_address.h" -using base::Bind; +using bluetooth::common::BindOnce; +using bluetooth::common::OnceCallback; using crypto_toolbox::aes_128; #ifndef SMP_MAX_ENC_REPEAT @@ -57,7 +59,9 @@ static void smp_process_stk(tSMP_CB* p_cb, Octet16* p); static Octet16 smp_calculate_legacy_short_term_key(tSMP_CB* p_cb); static void smp_process_private_key(tSMP_CB* p_cb); -#define SMP_PASSKEY_MASK 0xfff00000 +static void send_ble_rand(OnceCallback<void(uint64_t)> callback); + +#define SMP_PASSKEY_MASK 0x000fffff // If there is data saved here, then use its info instead // This needs to be cleared on a successfult pairing using the oob data @@ -92,14 +96,11 @@ void smp_debug_print_nbyte_big_endian(uint8_t* p, const char* key_name, uint8_t len) {} /** This function is called to process a passkey. */ -void smp_proc_passkey(tSMP_CB* p_cb, BT_OCTET8 rand) { +void smp_proc_passkey(tSMP_CB* p_cb, uint64_t rand) { uint8_t* tt = p_cb->tk.data(); - uint32_t passkey; /* 19655 test number; */ - uint8_t* pp = rand; + uint32_t passkey = static_cast<uint32_t>(rand & SMP_PASSKEY_MASK); LOG_VERBOSE("addr:%s", ADDRESS_TO_LOGGABLE_CSTR(p_cb->pairing_bda)); - STREAM_TO_UINT32(passkey, pp); - passkey &= ~SMP_PASSKEY_MASK; /* truncate by maximum value */ while (passkey > BTM_MAX_PASSKEY_VAL) passkey >>= 1; @@ -142,7 +143,7 @@ void smp_proc_passkey(tSMP_CB* p_cb, BT_OCTET8 rand) { void smp_generate_passkey(tSMP_CB* p_cb, UNUSED_ATTR tSMP_INT_DATA* p_data) { LOG_VERBOSE("addr:%s", ADDRESS_TO_LOGGABLE_CSTR(p_cb->pairing_bda)); /* generate MRand or SRand */ - btsnd_hcic_ble_rand(Bind(&smp_proc_passkey, p_cb)); + send_ble_rand(BindOnce(&smp_proc_passkey, p_cb)); } /******************************************************************************* @@ -204,10 +205,9 @@ void smp_generate_csrk(tSMP_CB* p_cb, UNUSED_ATTR tSMP_INT_DATA* p_data) { smp_compute_csrk(p_cb->div, p_cb); } else { LOG_VERBOSE("Generate DIV for CSRK"); - btsnd_hcic_ble_rand(Bind( - [](tSMP_CB* p_cb, BT_OCTET8 rand) { - uint16_t div; - STREAM_TO_UINT16(div, rand); + send_ble_rand(BindOnce( + [](tSMP_CB* p_cb, uint64_t rand) { + uint16_t div = static_cast<uint16_t>(rand); smp_compute_csrk(div, p_cb); }, p_cb)); @@ -405,14 +405,14 @@ void smp_generate_srand_mrand_confirm(tSMP_CB* p_cb, UNUSED_ATTR tSMP_INT_DATA* p_data) { LOG_VERBOSE("addr:%s", ADDRESS_TO_LOGGABLE_CSTR(p_cb->pairing_bda)); /* generate MRand or SRand */ - btsnd_hcic_ble_rand(Bind( - [](tSMP_CB* p_cb, BT_OCTET8 rand) { - memcpy(p_cb->rand.data(), rand, 8); - + send_ble_rand(BindOnce( + [](tSMP_CB* p_cb, uint64_t rand) { + memcpy(p_cb->rand.data(), (uint8_t*)&rand, sizeof(uint64_t)); /* generate 64 MSB of MRand or SRand */ - btsnd_hcic_ble_rand(Bind( - [](tSMP_CB* p_cb, BT_OCTET8 rand) { - memcpy((void*)&p_cb->rand[8], rand, BT_OCTET8_LEN); + send_ble_rand(BindOnce( + [](tSMP_CB* p_cb, uint64_t rand) { + memcpy(p_cb->rand.data() + sizeof(uint64_t), (uint8_t*)&rand, + sizeof(uint64_t)); smp_generate_confirm(p_cb); }, p_cb)); @@ -492,14 +492,14 @@ static void smp_process_ediv(tSMP_CB* p_cb, Octet16& p) { /** * This function is to proceed generate Y = E(DHK, Rand) */ -static void smp_generate_y(tSMP_CB* p_cb, BT_OCTET8 rand) { +static void smp_generate_y(tSMP_CB* p_cb, uint64_t rand) { LOG_VERBOSE("addr:%s", ADDRESS_TO_LOGGABLE_CSTR(p_cb->pairing_bda)); const Octet16& dhk = BTM_GetDeviceDHK(); - memcpy(p_cb->enc_rand, rand, BT_OCTET8_LEN); + memcpy(p_cb->enc_rand, (uint8_t*)&rand, sizeof(uint64_t)); Octet16 rand16{}; - memcpy(rand16.data(), rand, BT_OCTET8_LEN); + memcpy(rand16.data(), (uint8_t*)&rand, sizeof(uint64_t)); Octet16 output = aes_128(dhk, rand16); smp_process_ediv(p_cb, output); } @@ -523,7 +523,7 @@ static void smp_generate_ltk_cont(uint16_t div, tSMP_CB* p_cb) { p_cb->ltk = ltk; /* generate EDIV and rand now */ - btsnd_hcic_ble_rand(Bind(&smp_generate_y, p_cb)); + send_ble_rand(BindOnce(&smp_generate_y, p_cb)); } /******************************************************************************* @@ -560,10 +560,9 @@ void smp_generate_ltk(tSMP_CB* p_cb, UNUSED_ATTR tSMP_INT_DATA* p_data) { LOG_VERBOSE("Generate DIV for LTK"); /* generate MRand or SRand */ - btsnd_hcic_ble_rand(Bind( - [](tSMP_CB* p_cb, BT_OCTET8 rand) { - uint16_t div; - STREAM_TO_UINT16(div, rand); + send_ble_rand(BindOnce( + [](tSMP_CB* p_cb, uint64_t rand) { + uint16_t div = static_cast<uint16_t>(rand); smp_generate_ltk_cont(div, p_cb); }, p_cb)); @@ -624,19 +623,20 @@ void smp_create_private_key(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { LOG_WARN("OOB Association Model with no saved data present"); } - btsnd_hcic_ble_rand(Bind( - [](tSMP_CB* p_cb, BT_OCTET8 rand) { - memcpy((void*)p_cb->private_key, rand, BT_OCTET8_LEN); - btsnd_hcic_ble_rand(Bind( - [](tSMP_CB* p_cb, BT_OCTET8 rand) { - memcpy((void*)&p_cb->private_key[8], rand, BT_OCTET8_LEN); - btsnd_hcic_ble_rand(Bind( - [](tSMP_CB* p_cb, BT_OCTET8 rand) { - memcpy((void*)&p_cb->private_key[16], rand, BT_OCTET8_LEN); - btsnd_hcic_ble_rand(Bind( - [](tSMP_CB* p_cb, BT_OCTET8 rand) { - memcpy((void*)&p_cb->private_key[24], rand, - BT_OCTET8_LEN); + send_ble_rand(BindOnce( + [](tSMP_CB* p_cb, uint64_t rand) { + memcpy(p_cb->private_key, (uint8_t*)&rand, sizeof(uint64_t)); + send_ble_rand(BindOnce( + [](tSMP_CB* p_cb, uint64_t rand) { + memcpy(&p_cb->private_key[8], (uint8_t*)&rand, sizeof(uint64_t)); + send_ble_rand(BindOnce( + [](tSMP_CB* p_cb, uint64_t rand) { + memcpy(&p_cb->private_key[16], (uint8_t*)&rand, + sizeof(uint64_t)); + send_ble_rand(BindOnce( + [](tSMP_CB* p_cb, uint64_t rand) { + memcpy(&p_cb->private_key[24], (uint8_t*)&rand, + sizeof(uint64_t)); smp_process_private_key(p_cb); }, p_cb)); @@ -1055,12 +1055,13 @@ bool smp_calculate_long_term_key_from_link_key(tSMP_CB* p_cb) { */ void smp_start_nonce_generation(tSMP_CB* p_cb) { LOG_VERBOSE("start generating nonce"); - btsnd_hcic_ble_rand(Bind( - [](tSMP_CB* p_cb, BT_OCTET8 rand) { - memcpy(p_cb->rand.data(), rand, BT_OCTET8_LEN); - btsnd_hcic_ble_rand(Bind( - [](tSMP_CB* p_cb, BT_OCTET8 rand) { - memcpy(p_cb->rand.data() + 8, rand, BT_OCTET8_LEN); + send_ble_rand(BindOnce( + [](tSMP_CB* p_cb, uint64_t rand) { + memcpy(p_cb->rand.data(), (uint8_t*)&rand, sizeof(uint64_t)); + send_ble_rand(BindOnce( + [](tSMP_CB* p_cb, uint64_t rand) { + memcpy(p_cb->rand.data() + sizeof(uint64_t), (uint8_t*)&rand, + sizeof(uint64_t)); LOG_VERBOSE("round %d, done", p_cb->round); /* notifies SM that it has new nonce. */ smp_sm_event(p_cb, SMP_HAVE_LOC_NONCE_EVT, NULL); @@ -1069,3 +1070,7 @@ void smp_start_nonce_generation(tSMP_CB* p_cb) { }, p_cb)); } + +static void send_ble_rand(OnceCallback<void(uint64_t)> callback) { + bluetooth::shim::GetController()->LeRand(std::move(callback)); +} diff --git a/system/stack/smp/smp_utils.cc b/system/stack/smp/smp_utils.cc index 8981f4f43f..acfb276f31 100644 --- a/system/stack/smp/smp_utils.cc +++ b/system/stack/smp/smp_utils.cc @@ -942,7 +942,8 @@ void tSMP_CB::reset() { alarm_cancel(this->smp_rsp_timer_ent); alarm_cancel(this->delayed_auth_timer_ent); - init(init_security_mode); + *this = {}; + this->init_security_mode = init_security_mode; this->p_callback = p_callback; this->init_security_mode = init_security_mode; diff --git a/system/stack/test/fuzzers/Android.bp b/system/stack/test/fuzzers/Android.bp index 4ab36a889c..991d012f6b 100644 --- a/system/stack/test/fuzzers/Android.bp +++ b/system/stack/test/fuzzers/Android.bp @@ -29,6 +29,7 @@ cc_defaults { "libbluetooth_core_rs", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbt-audio-hal-interface", "libbt-bta", "libbt-bta-core", diff --git a/system/stack/test/gatt/stack_gatt_test.cc b/system/stack/test/gatt/stack_gatt_test.cc index f75f57be07..0c65e66103 100644 --- a/system/stack/test/gatt/stack_gatt_test.cc +++ b/system/stack/test/gatt/stack_gatt_test.cc @@ -14,6 +14,8 @@ * limitations under the License. */ +#include <com_android_bluetooth_flags.h> +#include <flag_macros.h> #include <gtest/gtest.h> #include <string.h> @@ -33,6 +35,8 @@ #include "types/bluetooth/uuid.h" #include "types/raw_address.h" +#define TEST_BT com::android::bluetooth::flags + namespace bluetooth { namespace legacy { namespace testing { @@ -165,7 +169,9 @@ TEST_F(StackGattTest, GATT_Register_Deregister) { gatt_free(); } -TEST_F(StackGattTest, gatt_status_text) { +TEST_F_WITH_FLAGS(StackGattTest, gatt_status_text, + REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(TEST_BT, + enumerate_gatt_errors))) { std::vector<std::pair<tGATT_STATUS, std::string>> statuses = { std::make_pair(GATT_SUCCESS, "GATT_SUCCESS"), // Also GATT_ENCRYPED_MITM std::make_pair(GATT_INVALID_HANDLE, "GATT_INVALID_HANDLE"), @@ -205,6 +211,7 @@ TEST_F(StackGattTest, gatt_status_text) { std::make_pair(GATT_DUP_REG, "GATT_DUP_REG"), std::make_pair(GATT_ALREADY_OPEN, "GATT_ALREADY_OPEN"), std::make_pair(GATT_CANCEL, "GATT_CANCEL"), + std::make_pair(GATT_CONNECTION_TIMEOUT, "GATT_CONNECTION_TIMEOUT"), std::make_pair(GATT_CCC_CFG_ERR, "GATT_CCC_CFG_ERR"), std::make_pair(GATT_PRC_IN_PROGRESS, "GATT_PRC_IN_PROGRESS"), std::make_pair(GATT_OUT_OF_RANGE, "GATT_OUT_OF_RANGE"), diff --git a/system/test/Android.bp b/system/test/Android.bp index 96d40a651d..5271d952d0 100644 --- a/system/test/Android.bp +++ b/system/test/Android.bp @@ -339,6 +339,13 @@ filegroup { } filegroup { + name: "TestMockJni", + srcs: [ + "mock/mock_jni*.cc", + ], +} + +filegroup { name: "TestMockStackHid", srcs: [ "mock/mock_stack_hid*.cc", diff --git a/system/test/headless/Android.bp b/system/test/headless/Android.bp index 30385bdfcf..e8cd0d3a1d 100644 --- a/system/test/headless/Android.bp +++ b/system/test/headless/Android.bp @@ -41,7 +41,8 @@ cc_binary { "HeadlessBuildTimestamp", ], srcs: [ - "bt_property.cc", + "adapter/adapter.cc", + "bt_stack_info.cc", "connect/connect.cc", "discovery/discovery.cc", "dumpsys/dumpsys.cc", @@ -51,6 +52,7 @@ cc_binary { "log.cc", "main.cc", "messenger.cc", + "mode/mode.cc", "nop/nop.cc", "pairing/pairing.cc", "property.cc", @@ -59,11 +61,13 @@ cc_binary { "scan/scan.cc", "sdp/sdp.cc", "sdp/sdp_db.cc", + "text.cc", "util.cc", ], include_dirs: [ "packages/modules/Bluetooth/system", "packages/modules/Bluetooth/system/gd", + "packages/modules/Bluetooth/system/include", "packages/modules/Bluetooth/system/stack/include", ], static_libs: [ @@ -79,6 +83,7 @@ cc_binary { "libbluetooth_core_rs", "libbluetooth_crypto_toolbox", "libbluetooth_gd", + "libbluetooth_log", "libbluetooth_rust_interop", "libbt-audio-asrc", "libbt-audio-hal-interface", diff --git a/system/test/headless/adapter/adapter.cc b/system/test/headless/adapter/adapter.cc new file mode 100644 index 0000000000..7de75c7a4b --- /dev/null +++ b/system/test/headless/adapter/adapter.cc @@ -0,0 +1,90 @@ +/* + * 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_headless_scan" + +#include "test/headless/adapter/adapter.h" + +#include "base/logging.h" // LOG() stdout and android log +#include "gd/os/log.h" +#include "test/headless/headless.h" +#include "test/headless/interface.h" +#include "test/headless/log.h" +#include "test/headless/messenger.h" +#include "test/headless/stopwatch.h" + +using namespace bluetooth::test; +using namespace std::chrono_literals; + +namespace { + +unsigned kTimeoutMs = 5000; + +int get_adapter_info([[maybe_unused]] unsigned int num_loops) { + LOG(INFO) << "Started Device Adapter Properties"; + + ASSERT(bluetoothInterface.get_adapter_properties() == BT_STATUS_SUCCESS); + LOG_CONSOLE("Started get adapter properties"); + + headless::messenger::Context context{ + .stop_watch = Stopwatch(__func__), + .timeout = 1s, // Poll time + .check_point = {}, + .callbacks = {Callback::AdapterProperties}, + }; + + bool adapter_properties_found = false; + while (context.stop_watch.LapMs() < kTimeoutMs) { + // If we have received callback results within this timeframe... + if (headless::messenger::await_callback(context)) { + while (!context.callback_ready_q.empty()) { + std::shared_ptr<callback_params_t> p = context.callback_ready_q.front(); + context.callback_ready_q.pop_front(); + switch (p->CallbackType()) { + case Callback::AdapterProperties: { + adapter_properties_params_t* q = + static_cast<adapter_properties_params_t*>(p.get()); + for (const auto& p2 : q->properties()) { + LOG_CONSOLE(" %s prop:%s", p->Name().c_str(), + p2->ToString().c_str()); + } + adapter_properties_found = true; + } break; + default: + LOG_CONSOLE("WARN Received callback for unasked:%s", + p->Name().c_str()); + break; + } + } + } + if (adapter_properties_found) break; + } + + LOG_CONSOLE("Retrieved adapter properties"); + return 0; +} + +} // namespace + +int bluetooth::test::headless::Adapter::Run() { + if (options_.loop_ < 1) { + LOG_CONSOLE("This test requires at least a single loop"); + options_.Usage(); + return -1; + } + return RunOnHeadlessStack<int>( + [this]() { return get_adapter_info(options_.loop_); }); +} diff --git a/system/test/headless/adapter/adapter.h b/system/test/headless/adapter/adapter.h new file mode 100644 index 0000000000..b6b7e1c2a7 --- /dev/null +++ b/system/test/headless/adapter/adapter.h @@ -0,0 +1,37 @@ +/* + * 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. + */ + +#pragma once + +#include "test/headless/get_options.h" +#include "test/headless/headless.h" + +namespace bluetooth { +namespace test { +namespace headless { + +class Adapter : public HeadlessTest<int> { + public: + Adapter(const bluetooth::test::headless::GetOpt& options) + : HeadlessTest<int>(options) {} + virtual ~Adapter() = default; + + int Run() override; +}; + +} // namespace headless +} // namespace test +} // namespace bluetooth diff --git a/system/test/headless/android_namespace.cc b/system/test/headless/android_namespace.cc new file mode 100644 index 0000000000..4d4a1b1165 --- /dev/null +++ b/system/test/headless/android_namespace.cc @@ -0,0 +1,21 @@ +/* + * 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/bt_property.cc b/system/test/headless/bt_property.cc deleted file mode 100644 index 5b6c2d5397..0000000000 --- a/system/test/headless/bt_property.cc +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define LOG_TAG "bt_headless_property" - -#include "test/headless/bt_property.h" - -#include "base/logging.h" // LOG() stdout and android log -#include "btif/include/btif_api.h" -#include "osi/include/log.h" // android log only -#include "stack/include/sdp_api.h" -#include "test/headless/get_options.h" -#include "test/headless/headless.h" -#include "test/headless/interface.h" -#include "test/headless/log.h" -#include "test/headless/sdp/sdp.h" -#include "test/headless/stopwatch.h" -#include "types/bluetooth/uuid.h" -#include "types/raw_address.h" - -using namespace bluetooth::test::headless; -using namespace std::chrono_literals; - -namespace bluetooth { -namespace test { -namespace headless { - -void process_property(const RawAddress& bd_addr, const bt_property_t* prop) { - LOG_INFO("%s bt_property type:%d len:%d val:%p", - ADDRESS_TO_LOGGABLE_CSTR(bd_addr), prop->type, - prop->len, prop->val); - switch (prop->type) { - case BT_PROPERTY_BDNAME: { - ASSERT(prop->len >= 0); - std::string name(static_cast<const char*>(prop->val), - static_cast<size_t>(prop->len)); - LOG_CONSOLE("BT_PROPERTY_BDNAME NAME:%s", name.c_str()); - } break; - case BT_PROPERTY_BDADDR: - LOG_CONSOLE("BT_PROPERTY_BDADDR"); - break; - case BT_PROPERTY_UUIDS: { - const size_t remainder = prop->len % sizeof(bluetooth::Uuid); - ASSERT(remainder == 0); - bluetooth::Uuid* uuid = reinterpret_cast<bluetooth::Uuid*>(prop->val); - for (int len = prop->len; len > 0; len -= sizeof(*uuid)) { - LOG_CONSOLE("BT_PROPERTY_UUIDS UUID:%s", uuid->ToString().c_str()); - uuid++; - } - } break; - case BT_PROPERTY_CLASS_OF_DEVICE: { - ASSERT(prop->len == 4); - uint32_t cod = *(reinterpret_cast<uint32_t*>(prop->val)); - LOG_CONSOLE("BT_PROPERTY_CLASS_OF_DEVICE 0x%04x", cod); - } break; - case BT_PROPERTY_TYPE_OF_DEVICE: { - ASSERT(prop->len == 4); - uint32_t devtype = *(reinterpret_cast<uint32_t*>(prop->val)); - LOG_CONSOLE("BT_PROPERTY_TYPE_OF_DEVICE 0x%04x", devtype); - } break; - case BT_PROPERTY_SERVICE_RECORD: - LOG_CONSOLE("BT_PROPERTY_SERVICE_RECORD"); - break; - case BT_PROPERTY_ADAPTER_SCAN_MODE: - LOG_CONSOLE("BT_PROPERTY_ADAPTER_SCAN_MODE"); - break; - case BT_PROPERTY_ADAPTER_BONDED_DEVICES: - LOG_CONSOLE("BT_PROPERTY_ADAPTER_BONDED_DEVICES"); - break; - case BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT: - LOG_CONSOLE("BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT"); - break; - case BT_PROPERTY_REMOTE_FRIENDLY_NAME: - LOG_CONSOLE("BT_PROPERTY_REMOTE_FRIENDLY_NAME"); - break; - case BT_PROPERTY_REMOTE_RSSI: - LOG_CONSOLE("BT_PROPERTY_REMOTE_RSSI"); - break; - case BT_PROPERTY_REMOTE_VERSION_INFO: - LOG_CONSOLE("BT_PROPERTY_REMOTE_VERSION_INFO"); - break; - case BT_PROPERTY_LOCAL_LE_FEATURES: - LOG_CONSOLE("BT_PROPERTY_LOCAL_LE_FEATURES"); - break; - case BT_PROPERTY_LOCAL_IO_CAPS: - LOG_CONSOLE("BT_PROPERTY_LOCAL_IO_CAPS"); - break; - case BT_PROPERTY_DYNAMIC_AUDIO_BUFFER: - LOG_CONSOLE("BT_PROPERTY_DYNAMIC_AUDIO_BUFFER"); - break; - case BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER: - LOG_CONSOLE("BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER"); - break; - case BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP: - LOG_CONSOLE("BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER"); - break; - default: { - LOG_CONSOLE("Unable to find BT property bd_addr:%s type:%d ptr:%p", - ADDRESS_TO_LOGGABLE_CSTR(bd_addr), prop->type, prop); - const uint8_t* p = reinterpret_cast<const uint8_t*>(prop); - for (size_t i = 0; i < sizeof(bt_property_t); i++, p++) { - LOG_CONSOLE(" %p:0x%02x", p, *p); - } - } break; - } -} - -} // namespace headless -} // namespace test -} // namespace bluetooth diff --git a/system/test/headless/bt_property.h b/system/test/headless/bt_property.h index 75cbd0c9b6..cfec588929 100644 --- a/system/test/headless/bt_property.h +++ b/system/test/headless/bt_property.h @@ -9,6 +9,8 @@ namespace test { namespace headless { void process_property(const RawAddress& bd_addr, const bt_property_t* prop); -} +void process_property2(const bt_property_t* prop); + +} // namespace headless } // namespace test } // namespace bluetooth diff --git a/system/test/headless/bt_stack_info.cc b/system/test/headless/bt_stack_info.cc new file mode 100644 index 0000000000..943ab03d72 --- /dev/null +++ b/system/test/headless/bt_stack_info.cc @@ -0,0 +1,65 @@ +/* + * 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 "test/headless/bt_stack_info.h" + +#include <unistd.h> + +#include "btif/include/btif_common.h" // do_in_jni_thread +#include "btif/include/btif_hh.h" // DumpsysHid +#include "main/shim/dumpsys.h" +#include "stack/gatt/connection_manager.h" +#include "stack/include/main_thread.h" +#include "stack/include/pan_api.h" // PAN_Dumpsys +#include "test/headless/log.h" + +BtStackInfo::BtStackInfo() { + { + std::promise<pid_t> promise; + auto future = promise.get_future(); + do_in_main_thread(FROM_HERE, base::BindOnce( + [](std::promise<pid_t> promise) { + promise.set_value(getpid()); + }, + std::move(promise))); + main_pid_ = future.get(); + } + + { + std::promise<pid_t> promise; + auto future = promise.get_future(); + do_in_jni_thread(FROM_HERE, base::BindOnce( + [](std::promise<pid_t> promise) { + promise.set_value(getpid()); + }, + std::move(promise))); + jni_pid_ = future.get(); + } +} + +void BtStackInfo::DumpsysLite() { + LOG_CONSOLE("main_pid:%u", main_pid_); + LOG_CONSOLE("jni_pid:%u", jni_pid_); + + int fd = STDIN_FILENO; + const char** arguments = nullptr; + + connection_manager::dump(fd); + PAN_Dumpsys(fd); + DumpsysHid(fd); + DumpsysBtaDm(fd); + bluetooth::shim::Dump(fd, arguments); +} diff --git a/system/test/headless/bt_stack_info.h b/system/test/headless/bt_stack_info.h new file mode 100644 index 0000000000..19afe0d2c1 --- /dev/null +++ b/system/test/headless/bt_stack_info.h @@ -0,0 +1,33 @@ +/* + * 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. + */ + +#pragma once + +#include <sys/types.h> + +class BtStackInfo { + public: + BtStackInfo(); + + void DumpsysLite(); + + pid_t MainPid() const { return main_pid_; } + pid_t JniPid() const { return jni_pid_; } + + private: + pid_t main_pid_; + pid_t jni_pid_; +}; diff --git a/system/test/headless/config.cc b/system/test/headless/config.cc new file mode 100644 index 0000000000..10cb1b0fbf --- /dev/null +++ b/system/test/headless/config.cc @@ -0,0 +1,32 @@ +/* + * 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/connect/connect.cc b/system/test/headless/connect/connect.cc index 06897ecf4a..415501f441 100644 --- a/system/test/headless/connect/connect.cc +++ b/system/test/headless/connect/connect.cc @@ -24,12 +24,12 @@ #include <cstdint> #include <cstdio> #include <future> -#include <map> #include <string> #include "base/logging.h" // LOG() stdout and android log #include "btif/include/stack_manager_t.h" -#include "osi/include/log.h" // android log only +#include "os/log.h" // android log only +#include "stack/include/acl_api.h" #include "stack/include/btm_api.h" #include "stack/include/btm_api_types.h" #include "stack/include/hci_error_code.h" @@ -37,34 +37,18 @@ #include "test/headless/get_options.h" #include "test/headless/headless.h" #include "test/headless/interface.h" +#include "test/headless/messenger.h" #include "types/raw_address.h" -const stack_manager_t* stack_manager_get_interface(); - -void power_mode_callback([[maybe_unused]] const RawAddress& p_bda, - [[maybe_unused]] tBTM_PM_STATUS status, - [[maybe_unused]] uint16_t value, - [[maybe_unused]] tHCI_STATUS hci_status) { - fprintf(stdout, "Got callback\n"); -}; - -namespace connect { -std::promise<acl_state_changed_params_t> acl_state_changed_promise; +using namespace bluetooth::test; +using namespace std::chrono_literals; -} // namespace connect - -void callback_interface(callback_data_t* data) { - if (data->Name() == "acl_state_changed") { - LOG(INFO) << "Received acl state changed discovery"; - auto params = static_cast<acl_state_changed_params_t*>(data); - acl_state_changed_params_t p(*params); - connect::acl_state_changed_promise.set_value(p); - } - LOG(ERROR) << "Received unexpected interface callback"; -} +const stack_manager_t* stack_manager_get_interface(); namespace { +bool f_simulate_stack_crash = false; + int do_connect([[maybe_unused]] unsigned int num_loops, [[maybe_unused]] const RawAddress& bd_addr, [[maybe_unused]] std::list<std::string> options) { @@ -80,49 +64,91 @@ int do_connect([[maybe_unused]] unsigned int num_loops, } ASSERT_LOG(disconnect_wait_time >= 0, "Time cannot go backwards"); - headless_add_callback("acl_state_changed", callback_interface); - - connect::acl_state_changed_promise = - std::promise<acl_state_changed_params_t>(); - auto future = connect::acl_state_changed_promise.get_future(); + headless::messenger::Context context{ + .stop_watch = Stopwatch("Connect_timeout"), + .timeout = 3s, + .check_point = {}, + .callbacks = {Callback::AclStateChanged}, + }; - fprintf(stdout, "Creating connection to:%s\n", bd_addr.ToString().c_str()); + LOG_CONSOLE("Creating connection to:%s", bd_addr.ToString().c_str()); LOG(INFO) << "Creating classic connection to " << bd_addr.ToString(); acl_create_classic_connection(bd_addr, false, false); - auto result = future.get(); - LOG_CONSOLE("Connected created %s", result.ToString().c_str()); + std::shared_ptr<callback_params_t> acl{nullptr}; + while (context.stop_watch.LapMs() < 10000) { + // If we have received callback results within this timeframe... + if (headless::messenger::await_callback(context)) { + while (!context.callback_ready_q.empty()) { + std::shared_ptr<callback_params_t> p = context.callback_ready_q.front(); + context.callback_ready_q.pop_front(); + switch (p->CallbackType()) { + case Callback::AclStateChanged: { + acl = p; + } break; + default: + LOG_CONSOLE("WARN Received callback for unasked:%s", + p->Name().c_str()); + break; + } + } + } + if (acl != nullptr) break; + } - connect::acl_state_changed_promise = - std::promise<acl_state_changed_params_t>(); - future = connect::acl_state_changed_promise.get_future(); + if (acl != nullptr) { + LOG_CONSOLE("Acl state changed:%s", acl->ToString().c_str()); + } uint64_t connect = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch()) .count(); - fprintf(stdout, "Just crushing stack\n"); - LOG(INFO) << "Just crushing stack"; - bluetoothInterface.disable(); + if (f_simulate_stack_crash) { + LOG_CONSOLE("Just crushing stack"); + LOG(INFO) << "Just crushing stack"; + bluetoothInterface.disable(); + } + std::shared_ptr<callback_params_t> acl2{nullptr}; if (disconnect_wait_time == 0) { - fprintf(stdout, "Waiting to disconnect from supervision timeout\n"); - auto result = future.get(); + LOG_CONSOLE("Waiting to disconnect from supervision timeout\n"); + while (context.stop_watch.LapMs() < 10000) { + // If we have received callback results within this timeframe... + if (headless::messenger::await_callback(context)) { + while (!context.callback_ready_q.empty()) { + std::shared_ptr<callback_params_t> p = + context.callback_ready_q.front(); + context.callback_ready_q.pop_front(); + switch (p->CallbackType()) { + case Callback::AclStateChanged: { + acl2 = p; + } break; + default: + LOG_CONSOLE("WARN Received callback for unasked:%s", + p->Name().c_str()); + break; + } + } + } + if (acl2 != nullptr) break; + } uint64_t disconnect = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch()) .count(); - LOG_CONSOLE("Disconnected after:%" PRId64 "ms from:%s result:%s[%u]\n", + LOG_CONSOLE("Disconnected after:%" PRId64 "ms from:%s acl:%s", disconnect - connect, bd_addr.ToString().c_str(), - bt_status_text(result.status).c_str(), result.status); - headless_remove_callback("acl_state_changed", callback_interface); - } else { - fprintf(stdout, "Waiting %d seconds to just shutdown\n", - disconnect_wait_time); - bluetoothInterface.dump(1, nullptr); - bluetoothInterface.cleanup(); + acl->ToString().c_str()); } + + acl_disconnect_from_handle( + ((acl_state_changed_params_t*)(acl2.get()))->acl_handle, HCI_SUCCESS, + "BT headless disconnect"); + + sleep(3); + return 0; } diff --git a/system/test/headless/discovery/discovery.cc b/system/test/headless/discovery/discovery.cc index 7faf81ca48..5e18b64a24 100644 --- a/system/test/headless/discovery/discovery.cc +++ b/system/test/headless/discovery/discovery.cc @@ -48,113 +48,7 @@ int start_discovery([[maybe_unused]] unsigned int num_loops, Stopwatch acl_stopwatch("ACL_connection"); Stopwatch sdp_stopwatch("SDP_discovery"); - LOG_CONSOLE("Started service discovery"); - auto check_point = messenger::sdp::get_check_point(); - ASSERT(bluetoothInterface.get_remote_services(&bd_addr, 0) == - BT_STATUS_SUCCESS); - - if (!messenger::acl::await_connected(8s)) { - LOG_CONSOLE("TIMEOUT waiting for connection to %s", - raw_address.ToString().c_str()); - return -1; - } - LOG_CONSOLE("ACL connected to %s :%sms", STR(raw_address), - STR(acl_stopwatch)); - - if (!messenger::sdp::await_service_discovery(8s, check_point, 1UL)) { - LOG_CONSOLE("TIMEOUT waiting for service discovery to %s", - raw_address.ToString().c_str()); - return -1; - } - auto callback_queue = messenger::sdp::collect_from(check_point); - ASSERT_LOG(callback_queue.size() == 1, - "Received unexpected number of SDP queries"); - - auto params = callback_queue.front(); - callback_queue.pop_front(); - - LOG_CONSOLE("got remote services :%s", params.ToString().c_str()); - - for (int i = 0; i < params.num_properties; i++) { - process_property(params.bd_addr, params.properties + i); - } - - // Run a second fetch SDP - { - LOG_CONSOLE("Sending second SDP request"); - auto check_point = messenger::sdp::get_check_point(); - - ASSERT(bluetoothInterface.get_remote_services(&bd_addr, 0) == - BT_STATUS_SUCCESS); - - if (!messenger::acl::await_connected(8s)) { - LOG_CONSOLE("TIMEOUT waiting for connection to %s", - raw_address.ToString().c_str()); - return -1; - } - LOG_CONSOLE("ACL connected to %s :%sms", STR(raw_address), - STR(acl_stopwatch)); - - if (!messenger::sdp::await_service_discovery(8s, check_point, 1UL)) { - LOG_CONSOLE("TIMEOUT waiting for service discovery to %s", - raw_address.ToString().c_str()); - return -1; - } - auto callback_queue = messenger::sdp::collect_from(check_point); - ASSERT_LOG(callback_queue.size() == 1, - "Received unexpected number of SDP queries"); - - auto params = callback_queue.front(); - callback_queue.pop_front(); - - LOG_CONSOLE("got remote services :%s", params.ToString().c_str()); - - for (int i = 0; i < params.num_properties; i++) { - process_property(params.bd_addr, params.properties + i); - } - } - - // Run a third fetch SDP - { - LOG_CONSOLE("Sending third SDP request"); - auto check_point = messenger::sdp::get_check_point(); - - ASSERT(bluetoothInterface.get_remote_services(&bd_addr, 0) == - BT_STATUS_SUCCESS); - - if (!messenger::acl::await_connected(8s)) { - LOG_CONSOLE("TIMEOUT waiting for connection to %s", - raw_address.ToString().c_str()); - return -1; - } - LOG_CONSOLE("ACL connected to %s :%sms", STR(raw_address), - STR(acl_stopwatch)); - - if (!messenger::sdp::await_service_discovery(8s, check_point, 1UL)) { - LOG_CONSOLE("TIMEOUT waiting for service discovery to %s", - raw_address.ToString().c_str()); - return -1; - } - auto callback_queue = messenger::sdp::collect_from(check_point); - ASSERT_LOG(callback_queue.size() == 1, - "Received unexpected number of SDP queries"); - - auto params = callback_queue.front(); - callback_queue.pop_front(); - - LOG_CONSOLE("got remote services :%s", params.ToString().c_str()); - - for (int i = 0; i < params.num_properties; i++) { - process_property(params.bd_addr, params.properties + i); - } - } - - LOG_CONSOLE("Awaiting disconnect"); - if (!messenger::acl::await_disconnected(6s)) { - LOG_CONSOLE("TIMEOUT waiting for disconnection to %s", - raw_address.ToString().c_str()); - return -1; - } + LOG_CONSOLE("Started service discovery %s", bd_addr.ToString().c_str()); LOG_CONSOLE("Dumpsys system"); bluetoothInterface.dump(2, nullptr); diff --git a/system/test/headless/headless.cc b/system/test/headless/headless.cc index c6a3e7d00b..e364803cfd 100644 --- a/system/test/headless/headless.cc +++ b/system/test/headless/headless.cc @@ -22,17 +22,21 @@ #include <iostream> #include <map> +#include <memory> #include "base/logging.h" // LOG() stdout and android log +#include "gd/os/log.h" #include "include/check.h" #include "include/hardware/bluetooth.h" -#include "internal_include/bt_trace.h" -#include "osi/include/log.h" // android log only -#include "test/headless/get_options.h" +#include "test/headless/bt_stack_info.h" #include "test/headless/interface.h" #include "test/headless/log.h" +#include "test/headless/messenger.h" #include "types/raw_address.h" +// +// Aggregate disparate variables from callback API into unified single structure +// extern bt_interface_t bluetoothInterface; using namespace bluetooth::test::headless; @@ -56,14 +60,13 @@ void headless_add_callback(const std::string interface_name, interface_api_callback_map_[interface_name].push_back(function); } -void headless_remove_callback(const std::string interface_name, - callback_function_t function) { +void headless_remove_callback(const std::string interface_name) { if (interface_api_callback_map_.find(interface_name) == interface_api_callback_map_.end()) { ASSERT_LOG(false, "No callbacks registered for interface:%s", interface_name.c_str()); } - interface_api_callback_map_[interface_name].remove(function); + interface_api_callback_map_.erase(interface_name); } std::mutex adapter_state_mutex_; @@ -75,10 +78,21 @@ void adapter_state_changed(bt_state_t state) { bt_state_ = state; adapter_state_cv_.notify_all(); } -void adapter_properties([[maybe_unused]] bt_status_t status, - [[maybe_unused]] int num_properties, - [[maybe_unused]] ::bt_property_t* properties) { - LOG_INFO("%s", __func__); +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()) { + for (auto callback : callback_list->second) { + adapter_properties_params_t params(status, num_properties, properties); + (callback)(¶ms); + } + } + LOG_INFO( + "num_callbacks:%zu status:%s num_properties:%d " + "properties:%p", + num_callbacks, bt_status_text(status).c_str(), num_properties, + properties); } void remote_device_properties(bt_status_t status, RawAddress* bd_addr, @@ -96,15 +110,25 @@ void remote_device_properties(bt_status_t status, RawAddress* bd_addr, } } LOG_INFO( - "%s num_callbacks:%zu status:%s device:%s num_properties:%d " + "num_callbacks:%zu status:%s device:%s num_properties:%d " "properties:%p", - __func__, num_callbacks, bt_status_text(status).c_str(), STR(*bd_addr), + num_callbacks, bt_status_text(status).c_str(), STR(*bd_addr), num_properties, properties); } -void device_found([[maybe_unused]] int num_properties, - [[maybe_unused]] ::bt_property_t* properties) { - LOG_INFO("%s", __func__); +// Aggregate disparate variables from callback API into unified single structure +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()) { + for (auto callback : callback_list->second) { + device_found_params_t params(num_properties, properties); + (callback)(¶ms); + } + } + LOG_INFO("Device found callback: num_properties:%d properties:%p", + num_properties, properties); } void discovery_state_changed(bt_discovery_state_t state) { @@ -284,6 +308,8 @@ void HeadlessStack::SetUp() { while (bt_state_ != BT_STATE_ON) adapter_state_cv_.wait(lck); LOG_INFO("%s HeadlessStack stack is operational", __func__); + bt_stack_info_ = std::make_unique<BtStackInfo>(); + bluetooth::test::headless::start_messenger(); LOG_CONSOLE("%s Headless stack has started up successfully", kHeadlessIcon); diff --git a/system/test/headless/headless.h b/system/test/headless/headless.h index 78e7591032..37ad7c927a 100644 --- a/system/test/headless/headless.h +++ b/system/test/headless/headless.h @@ -22,8 +22,9 @@ #include "base/logging.h" // LOG() stdout and android log #include "include/hardware/bluetooth.h" +#include "test/headless/bt_stack_info.h" #include "test/headless/get_options.h" -#include "test/headless/messenger.h" +#include "test/headless/log.h" extern bt_interface_t bluetoothInterface; @@ -35,17 +36,13 @@ template <typename T> using ExecutionUnit = std::function<T()>; constexpr char kHeadlessInitialSentinel[] = - " INITIAL HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS " - "HEADLESS"; + " INITIAL HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS"; constexpr char kHeadlessStartSentinel[] = - " START HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS " - "HEADLESS"; + " START HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS"; constexpr char kHeadlessStopSentinel[] = - " STOP HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS " - "HEADLESS"; + " STOP HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS"; constexpr char kHeadlessFinalSentinel[] = - " FINAL HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS " - "HEADLESS"; + " FINAL HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS"; class HeadlessStack { protected: @@ -60,6 +57,7 @@ class HeadlessStack { private: const char** stack_init_flags_; + std::unique_ptr<BtStackInfo> bt_stack_info_; }; class HeadlessRun : public HeadlessStack { diff --git a/system/test/headless/interface.h b/system/test/headless/interface.h index 370d86138e..8b4c9efd07 100644 --- a/system/test/headless/interface.h +++ b/system/test/headless/interface.h @@ -1,38 +1,118 @@ - +/* + * 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. + */ #pragma once #include <base/strings/stringprintf.h> -#include <list> -#include <map> +#include <deque> #include <string> +#include "gd/os/log.h" #include "include/hardware/bluetooth.h" +#include "macros.h" #include "test/headless/log.h" +#include "test/headless/property.h" +#include "test/headless/text.h" #include "types/raw_address.h" +enum class Callback { + AclStateChanged, + AdapterProperties, + DeviceFound, + DiscoveryStateChanged, + RemoteDeviceProperties, +}; + +inline std::string callback_text(const Callback& callback) { + switch (callback) { + CASE_RETURN_TEXT(Callback::AclStateChanged); + CASE_RETURN_TEXT(Callback::AdapterProperties); + CASE_RETURN_TEXT(Callback::DeviceFound); + CASE_RETURN_TEXT(Callback::DiscoveryStateChanged); + CASE_RETURN_TEXT(Callback::RemoteDeviceProperties); + } +} + struct callback_data_t { std::string Name() const { return std::string(name_); } + Callback CallbackType() const { return callback_type_; } + uint64_t TimestampInMs() const { return static_cast<uint64_t>(timestamp_ms_); } + virtual ~callback_data_t() = default; + + virtual std::string ToString() const = 0; protected: - callback_data_t(const char* name) - : name_(name), timestamp_ms_(GetTimestampMs()) {} - virtual ~callback_data_t() = default; + callback_data_t(const char* name, Callback callback_type_) + : name_(name), + callback_type_(callback_type_), + timestamp_ms_(GetTimestampMs()) {} private: const char* name_; + const Callback callback_type_; const long long timestamp_ms_; }; struct callback_params_t : public callback_data_t { + virtual std::string ToString() const override { + return std::string("VIRTUAL"); + } + protected: - callback_params_t(const char* name) : callback_data_t(name) {} + callback_params_t(const char* name, Callback callback_type) + : callback_data_t(name, callback_type) {} virtual ~callback_params_t() = default; - virtual std::string ToString() const = 0; +}; + +// Specializes the callback parameter +template <typename T> +// std::shared_ptr<T> Cast(std::shared_ptr<callback_params_t> params) { return +// std::shared_ptr<T>(static_cast<T*>(params.get()));} +std::shared_ptr<T> Cast(std::shared_ptr<callback_params_t> params) { + return std::make_shared<T>(*(static_cast<T*>(params.get()))); +} + +struct callback_params_with_properties_t : public callback_params_t { + public: + std::deque<bluetooth::test::headless::bt_property_t*> properties() const { + return property_queue_; + } + size_t num_properties() const { return property_queue_.size(); } + + protected: + callback_params_with_properties_t(const char* name, Callback callback_type, + int num_properties, + ::bt_property_t* properties) + : callback_params_t(name, callback_type) { + for (int i = 0; i < num_properties; i++) { + LOG_DEBUG("Processing property %d/%d %p type:%d val:%p", i, + num_properties, &properties[i], properties[i].type, + properties[i].val); + property_queue_.push_back( + bluetooth::test::headless::property_factory(properties[i])); + } + } + virtual ~callback_params_with_properties_t() = default; + + private: + std::deque<bluetooth::test::headless::bt_property_t*> property_queue_; }; struct acl_state_changed_params_t : public callback_params_t { @@ -40,7 +120,7 @@ struct acl_state_changed_params_t : public callback_params_t { 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) - : callback_params_t("acl_state_changed"), + : callback_params_t("acl_state_changed", Callback::AclStateChanged), status(status), remote_bd_addr(remote_bd_addr), state(state), @@ -62,20 +142,22 @@ struct acl_state_changed_params_t : public callback_params_t { std::string ToString() const override { return base::StringPrintf( - "status:%s remote_bd_addr:%s state:%s transport:%s reason:%s " - "direction:%d handle:%d", + "status:%s remote_bd_addr:%s state:%s transport:%s reason:%s" + " direction:%s handle:%hu", bt_status_text(status).c_str(), remote_bd_addr.ToString().c_str(), (state == BT_ACL_STATE_CONNECTED) ? "CONNECTED" : "DISCONNECTED", bt_transport_text(static_cast<const tBT_TRANSPORT>(transport_link_type)) .c_str(), bt_status_text(static_cast<const bt_status_t>(hci_reason)).c_str(), - direction, acl_handle); + bt_conn_direction_text(direction).c_str(), acl_handle); } }; struct discovery_state_changed_params_t : public callback_params_t { discovery_state_changed_params_t(bt_discovery_state_t state) - : callback_params_t("discovery_state_changed"), state(state) {} + : callback_params_t("discovery_state_changed", + Callback::DiscoveryStateChanged), + state(state) {} discovery_state_changed_params_t( const discovery_state_changed_params_t& params) = default; @@ -83,33 +165,64 @@ struct discovery_state_changed_params_t : public callback_params_t { bt_discovery_state_t state; std::string ToString() const override { - return base::StringPrintf( - "state:%s", (state == BT_DISCOVERY_STOPPED) ? "STOPPED" : "STARTED"); + return base::StringPrintf("state:%s", + bt_discovery_state_text(state).c_str()); } }; -struct remote_device_properties_params_t : public callback_params_t { +struct adapter_properties_params_t : public callback_params_with_properties_t { + adapter_properties_params_t(bt_status_t status, int num_properties, + ::bt_property_t* properties) + : callback_params_with_properties_t("adapter_properties", + Callback::AdapterProperties, + num_properties, properties), + status(status) {} + adapter_properties_params_t(const adapter_properties_params_t& params) = + default; + + virtual ~adapter_properties_params_t() {} + bt_status_t status; + + std::string ToString() const override { + return base::StringPrintf("status:%s num_properties:%zu", + bt_status_text(status).c_str(), num_properties()); + } +}; + +struct remote_device_properties_params_t + : public callback_params_with_properties_t { remote_device_properties_params_t(bt_status_t status, RawAddress bd_addr, int num_properties, - bt_property_t* properties) - : callback_params_t("remote_device_properties"), + ::bt_property_t* properties) + : callback_params_with_properties_t("remote_device_properties", + Callback::RemoteDeviceProperties, + num_properties, properties), status(status), - bd_addr(bd_addr), - num_properties(num_properties), - properties(properties) {} + bd_addr(bd_addr) {} remote_device_properties_params_t( const remote_device_properties_params_t& params) = default; virtual ~remote_device_properties_params_t() {} bt_status_t status; RawAddress bd_addr; - int num_properties; - bt_property_t* properties; + std::string ToString() const override { - return base::StringPrintf( - "status:%s bd_addr:%s num_properties:%d properties:%p", - bt_status_text(status).c_str(), bd_addr.ToString().c_str(), - num_properties, properties); + return base::StringPrintf("status:%s bd_addr:%s num_properties:%zu", + bt_status_text(status).c_str(), + bd_addr.ToString().c_str(), num_properties()); + } +}; + +struct device_found_params_t : public callback_params_with_properties_t { + device_found_params_t(int num_properties, ::bt_property_t* properties) + : callback_params_with_properties_t("device_found", Callback::DeviceFound, + num_properties, properties) {} + + device_found_params_t(const device_found_params_t& params) = default; + virtual ~device_found_params_t() {} + + std::string ToString() const override { + return base::StringPrintf("num_properties:%zu", num_properties()); } }; @@ -117,5 +230,4 @@ using callback_function_t = void (*)(callback_data_t*); void headless_add_callback(const std::string interface_name, callback_function_t function); -void headless_remove_callback(const std::string interface_name, - callback_function_t function); +void headless_remove_callback(const std::string interface_name); diff --git a/system/test/headless/log.h b/system/test/headless/log.h index 303e220b44..4fb439e6bc 100644 --- a/system/test/headless/log.h +++ b/system/test/headless/log.h @@ -16,14 +16,11 @@ #pragma once -#include <assert.h> #include <log/log.h> -#include <stdio.h> #include <sys/syscall.h> /* Definition of SYS_* constants */ #include <unistd.h> #include <chrono> -#include <ctime> #include <string> #include "build_timestamp.h" // generated diff --git a/system/test/headless/main.cc b/system/test/headless/main.cc index f40ee53a7b..d54ed840f5 100644 --- a/system/test/headless/main.cc +++ b/system/test/headless/main.cc @@ -27,12 +27,14 @@ #include "base/logging.h" // LOG() stdout and android log #include "osi/include/log.h" // android log only +#include "test/headless/adapter/adapter.h" #include "test/headless/connect/connect.h" #include "test/headless/discovery/discovery.h" #include "test/headless/dumpsys/dumpsys.h" #include "test/headless/get_options.h" #include "test/headless/headless.h" #include "test/headless/log.h" +#include "test/headless/mode/mode.h" #include "test/headless/nop/nop.h" #include "test/headless/pairing/pairing.h" #include "test/headless/read/read.h" @@ -92,12 +94,17 @@ class Main : public HeadlessTest<int> { Main(const bluetooth::test::headless::GetOpt& options) : HeadlessTest<int>(options) { test_nodes_.emplace( + "adapter", + std::make_unique<bluetooth::test::headless::Adapter>(options)); + test_nodes_.emplace( "dumpsys", std::make_unique<bluetooth::test::headless::Dumpsys>(options)); test_nodes_.emplace( "connect", std::make_unique<bluetooth::test::headless::Connect>(options)); test_nodes_.emplace( + "mode", std::make_unique<bluetooth::test::headless::Mode>(options)); + test_nodes_.emplace( "nop", std::make_unique<bluetooth::test::headless::Nop>(options)); test_nodes_.emplace( "pairing", diff --git a/system/test/headless/messenger.cc b/system/test/headless/messenger.cc index 6231fb682d..604196b200 100644 --- a/system/test/headless/messenger.cc +++ b/system/test/headless/messenger.cc @@ -18,178 +18,125 @@ #include "test/headless/messenger.h" -#include <future> +#include <condition_variable> +#include <deque> +#include <memory> +#include <mutex> #include "base/logging.h" // LOG() stdout and android log -#include "btif/include/btif_api.h" -#include "osi/include/log.h" // android log only -#include "stack/include/sdp_api.h" -#include "test/headless/bt_property.h" -#include "test/headless/get_options.h" -#include "test/headless/headless.h" #include "test/headless/interface.h" #include "test/headless/log.h" -#include "test/headless/sdp/sdp.h" -#include "test/headless/stopwatch.h" -#include "test/headless/timeout.h" -#include "types/bluetooth/uuid.h" -#include "types/raw_address.h" using namespace bluetooth::test::headless; using namespace std::chrono_literals; template <typename T> +struct callback_queue_t { + callback_queue_t(const std::string name) : name_(name) {} + // Must be held with lock + size_t size() const { return callback_queue.size(); } + + private: + const std::string name_; + std::deque<T> callback_queue; + + public: + void Push(T elem) { callback_queue.push_back(elem); } + // Must be held with lock + T Pop() { + T p = callback_queue.front(); + callback_queue.pop_front(); + return p; + } + // Must be held with lock + bool empty() const { return callback_queue.empty(); } +}; + struct messenger_t { - std::mutex mutex; + mutable std::mutex mutex; std::condition_variable cv; - std::deque<T> params_queue; - void Notify() { cv.notify_all(); } + callback_queue_t<std::shared_ptr<callback_params_t>> callback_queue = + callback_queue_t<std::shared_ptr<callback_params_t>>("callbacks"); + void Push(std::shared_ptr<callback_params_t> elem) { + std::unique_lock<std::mutex> lk(mutex); + callback_queue.Push(elem); + cv.notify_all(); + } }; -namespace { - -namespace acl { -messenger_t<acl_state_changed_params_t> acl_state_changed_; - -void acl_state_changed_cb(callback_data_t* data) { - auto params = static_cast<acl_state_changed_params_t*>(data); - - acl_state_changed_.params_queue.push_back(*params); - acl_state_changed_.Notify(); -} +namespace bluetooth { +namespace test { +namespace headless { +namespace messenger { -bool await_event(const bt_acl_state_t& state, const Timeout& timeout) { - std::unique_lock<std::mutex> lk(acl_state_changed_.mutex); - if (!acl_state_changed_.params_queue.empty()) { - auto params = acl_state_changed_.params_queue.back(); - if (params.state == state) return true; +// Called by client to await any callback for the given callbacks +messenger_t callback_data_; + +bool await_callback(Context& context) { + std::unique_lock<std::mutex> lk(callback_data_.mutex); + while (!callback_data_.callback_queue.empty()) { + std::shared_ptr<callback_params_t> cb = callback_data_.callback_queue.Pop(); + if (std::find(context.callbacks.begin(), context.callbacks.end(), + cb->CallbackType()) != context.callbacks.end()) { + context.callback_ready_q.push_back(cb); + } } - return acl_state_changed_.cv.wait_for(lk, timeout, [=] { - return !acl_state_changed_.params_queue.empty() && - acl_state_changed_.params_queue.back().state == state; - }); -} - -} // namespace acl - -namespace sdp { -messenger_t<remote_device_properties_params_t> remote_device_properties_; - -void remote_device_properties_cb(callback_data_t* data) { - auto params = static_cast<remote_device_properties_params_t*>(data); - // TODO Save timestamp into queue - remote_device_properties_.params_queue.push_back(*params); - remote_device_properties_.Notify(); -} - -bool await_event(const Timeout& timeout, const CheckPoint& check_point, - const size_t count) { - std::unique_lock<std::mutex> lk(remote_device_properties_.mutex); - if (!remote_device_properties_.params_queue.empty()) { - if (remote_device_properties_.params_queue.size() - check_point > count) - return true; + if (context.callback_ready_q.size() == 0) { + callback_data_.cv.wait_for(lk, context.timeout); } - return remote_device_properties_.cv.wait_for(lk, timeout, [=] { - return !remote_device_properties_.params_queue.empty() && - remote_device_properties_.params_queue.size() - check_point >= count; - }); + return true; } -} // namespace sdp - -namespace inquiry {} // namespace inquiry - -} // namespace +} // namespace messenger +} // namespace headless +} // namespace test +} // namespace bluetooth namespace bluetooth::test::headless { -namespace messenger { -namespace acl { - -bool await_connected(const Timeout& timeout) { - return ::acl::await_event(BT_ACL_STATE_CONNECTED, timeout); -} - -bool await_disconnected(const Timeout& timeout) { - return ::acl::await_event(BT_ACL_STATE_DISCONNECTED, timeout); -} - -} // namespace acl - -namespace sdp { - -bool await_service_discovery(const Timeout& timeout, - const CheckPoint& check_point, - const size_t count) { - return ::sdp::await_event(timeout, check_point, count); +void messenger_stats() { + // LOG_CONSOLE("%30s cnt:%zu", "device_found", + // discovered::device_found_.size()); LOG_CONSOLE("%30s cnt:%zu", + // "remote_device_properties", + // properties::remote_device_properties_.size()); } -CheckPoint get_check_point() { - std::unique_lock<std::mutex> lk(::sdp::remote_device_properties_.mutex); - return ::sdp::remote_device_properties_.params_queue.size(); -} - -std::deque<remote_device_properties_params_t> collect_from( - CheckPoint& check_point) { - std::unique_lock<std::mutex> lk(::sdp::remote_device_properties_.mutex); - ASSERT_LOG( - !(check_point > ::sdp::remote_device_properties_.params_queue.size()), - "Checkpoint larger than size"); - std::deque<remote_device_properties_params_t> deque; - for (size_t size = check_point; - size < ::sdp::remote_device_properties_.params_queue.size(); ++size) { - deque.push_back(::sdp::remote_device_properties_.params_queue[size]); - } - return deque; -} - -} // namespace sdp - -namespace inquiry { - -CheckPoint get_check_point() { - std::unique_lock<std::mutex> lk(::sdp::remote_device_properties_.mutex); - return ::sdp::remote_device_properties_.params_queue.size(); -} - -bool await_inquiry_result(const Timeout& timeout, const CheckPoint& check_point, - const size_t count) { - return ::sdp::await_event(timeout, check_point, count); -} - -std::deque<remote_device_properties_params_t> collect_from( - CheckPoint& check_point) { - std::unique_lock<std::mutex> lk(::sdp::remote_device_properties_.mutex); - ASSERT_LOG( - !(check_point > ::sdp::remote_device_properties_.params_queue.size()), - "Checkpoint larger than size"); - std::deque<remote_device_properties_params_t> deque; - for (size_t size = check_point; - size < ::sdp::remote_device_properties_.params_queue.size(); ++size) { - deque.push_back(::sdp::remote_device_properties_.params_queue[size]); - } - check_point += - (::sdp::remote_device_properties_.params_queue.size() - check_point); - return deque; -} - -} // namespace inquiry -} // namespace messenger - +// Callbacks that the messenger will handle from the bluetooth stack void start_messenger() { - headless_add_callback("acl_state_changed", ::acl::acl_state_changed_cb); - headless_add_callback("remote_device_properties", - ::sdp::remote_device_properties_cb); - + headless_add_callback("acl_state_changed", [](callback_data_t* data) { + ASSERT_LOG(data != nullptr, "Received nullptr callback data:%s", __func__); + messenger::callback_data_.Push(std::make_shared<acl_state_changed_params_t>( + *(static_cast<acl_state_changed_params_t*>(data)))); + }); + headless_add_callback("adapter_properties", [](callback_data_t* data) { + ASSERT_LOG(data != nullptr, "Received nullptr callback data:%s", __func__); + messenger::callback_data_.Push( + std::make_shared<adapter_properties_params_t>( + *(static_cast<adapter_properties_params_t*>(data)))); + }); + headless_add_callback("device_found", [](callback_data_t* data) { + ASSERT_LOG(data != nullptr, "Received nullptr callback data:%s", __func__); + messenger::callback_data_.Push(std::make_shared<device_found_params_t>( + *(static_cast<device_found_params_t*>(data)))); + }); + headless_add_callback("remote_device_properties", [](callback_data_t* data) { + ASSERT_LOG(data != nullptr, "Received nullptr callback data:%s", __func__); + messenger::callback_data_.Push( + std::make_shared<remote_device_properties_params_t>( + *(static_cast<remote_device_properties_params_t*>(data)))); + }); LOG_CONSOLE("Started messenger service"); } void stop_messenger() { - headless_remove_callback("acl_state_changed", ::acl::acl_state_changed_cb); - headless_remove_callback("remote_device_properties", - ::sdp::remote_device_properties_cb); + headless_remove_callback("remote_device_properties"); + headless_remove_callback("device_found"); + headless_remove_callback("adapter_properties"); + headless_remove_callback("acl_state_changed"); LOG_CONSOLE("Stopped messenger service"); + + messenger_stats(); } } // namespace bluetooth::test::headless diff --git a/system/test/headless/messenger.h b/system/test/headless/messenger.h index f8c08ada84..67313124ed 100644 --- a/system/test/headless/messenger.h +++ b/system/test/headless/messenger.h @@ -1,11 +1,27 @@ - +/* + * 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. + */ #pragma once #include <cstddef> #include <deque> +#include <string> #include "test/headless/interface.h" +#include "test/headless/stopwatch.h" #include "test/headless/timeout.h" namespace bluetooth::test::headless { @@ -16,12 +32,18 @@ void start_messenger(); void stop_messenger(); namespace messenger { -namespace acl { -bool await_connected(const Timeout& timeout); -bool await_disconnected(const Timeout& timeout); +struct Context { + Stopwatch stop_watch; + Timeout timeout; + CheckPoint check_point; + bool SetCallbacks(const std::vector<std::string>& callbacks); + std::vector<Callback> callbacks; + std::deque<std::shared_ptr<callback_params_t>> callback_ready_q; +}; -} // namespace acl +// Called by client to await any callback for the given callbacks +bool await_callback(Context& context); namespace sdp { @@ -32,17 +54,6 @@ std::deque<remote_device_properties_params_t> collect_from( CheckPoint& check_point); } // namespace sdp - -namespace inquiry { - -CheckPoint get_check_point(); -bool await_inquiry_result(const Timeout& timeout, const CheckPoint& check_point, - const size_t count); -std::deque<remote_device_properties_params_t> collect_from( - CheckPoint& check_point); - -} // namespace inquiry - } // namespace messenger } // namespace bluetooth::test::headless diff --git a/system/test/headless/mode/mode.cc b/system/test/headless/mode/mode.cc new file mode 100644 index 0000000000..781beaefc1 --- /dev/null +++ b/system/test/headless/mode/mode.cc @@ -0,0 +1,153 @@ +/* + * 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 <memory> + +#include "btm_status.h" +#include "hci_error_code.h" +#define LOG_TAG "bt_headless_mode" + +#include <deque> +#include <future> + +#include "base/logging.h" // LOG() stdout and android log +#include "include/macros.h" +#include "stack/include/acl_api.h" +#include "stack/include/l2cap_acl_interface.h" +#include "test/headless/get_options.h" +#include "test/headless/headless.h" +#include "test/headless/messenger.h" +#include "test/headless/mode/mode.h" +#include "test/headless/utils/power_mode_client.h" +#include "types/raw_address.h" + +using namespace bluetooth::test; +using namespace std::chrono_literals; + +namespace { +int do_mode([[maybe_unused]] unsigned int num_loops, + [[maybe_unused]] const RawAddress& bd_addr, + [[maybe_unused]] std::list<std::string> options) { + LOG_CONSOLE("Starting mode change test"); + // Requires a BR_EDR connection to work + + headless::messenger::Context context{ + .stop_watch = Stopwatch("Connect_timeout"), + .timeout = 3s, + .check_point = {}, + .callbacks = {Callback::AclStateChanged}, + }; + + PowerMode power_mode; + + acl_create_classic_connection(bd_addr, false, false); + + std::shared_ptr<acl_state_changed_params_t> acl{nullptr}; + + while (context.stop_watch.LapMs() < 10000) { + // If we have received callback results within this timeframe... + if (headless::messenger::await_callback(context)) { + while (!context.callback_ready_q.empty()) { + std::shared_ptr<callback_params_t> p = context.callback_ready_q.front(); + context.callback_ready_q.pop_front(); + switch (p->CallbackType()) { + case Callback::AclStateChanged: { + acl = Cast<acl_state_changed_params_t>(p); + LOG_CONSOLE("Acl state changed:%s", acl->ToString().c_str()); + } break; + default: + LOG_CONSOLE("WARN Received callback for unasked:%s", + p->Name().c_str()); + break; + } + } + } + if (acl != nullptr) break; + } + + if (acl->state == BT_ACL_STATE_DISCONNECTED) { + LOG_CONSOLE("Connection failed"); + return 1; + } + + LOG_CONSOLE("Connection completed"); + PowerMode::Client client = power_mode.GetClient(bd_addr); + + { + pwr_command_t pwr_command; + pwr_result_t result = client.set_typical_sniff(std::move(pwr_command)); + LOG_CONSOLE("Sniff mode command sent"); + if (result.btm_status == BTM_CMD_STARTED) { + // This awaits the command status callback + power_mode_callback_t cmd_status = result.cmd_status_future.get(); + LOG_CONSOLE("Sniff mode command complete:%s", + cmd_status.ToString().c_str()); + if (cmd_status.status == BTM_PM_STS_PENDING) { + LOG_CONSOLE("Sniff mode command accepted; awaiting mode change event"); + power_mode_callback_t mode_event = result.mode_event_future.get(); + LOG_CONSOLE("Sniff mode command complete:%s", + mode_event.ToString().c_str()); + } else { + client.remove_mode_event_promise(); + LOG_CONSOLE("Command failed; no mode change event forthcoming"); + } + } else { + LOG_CONSOLE("Smiff mode command failed:%s", + btm_status_text(result.btm_status).c_str()); + } + } + + { + pwr_command_t pwr_command; + pwr_result_t result = client.set_active(std::move(pwr_command)); + LOG_CONSOLE("Active mode command sent"); + if (result.btm_status == BTM_CMD_STARTED) { + power_mode_callback_t cmd_status = result.cmd_status_future.get(); + LOG_CONSOLE("Active mode command complete:%s", + cmd_status.ToString().c_str()); + if (cmd_status.status == BTM_PM_STS_PENDING) { + LOG_CONSOLE("Active mode command accepted; awaiting mode change event"); + power_mode_callback_t mode_event = result.mode_event_future.get(); + LOG_CONSOLE("Active mode command complete:%s", + mode_event.ToString().c_str()); + } else { + client.remove_mode_event_promise(); + LOG_CONSOLE("Command failed; no mode change event forthcoming"); + } + } else { + LOG_CONSOLE("Active mode command failed:%s", + btm_status_text(result.btm_status).c_str()); + } + } + + LOG_CONSOLE("Disconnecting"); + acl_disconnect_from_handle(acl->acl_handle, HCI_SUCCESS, + "BT headless disconnect"); + LOG_CONSOLE("Waiting to disconnect"); + + sleep(3); + + return 0; +} + +} // namespace + // +int bluetooth::test::headless::Mode::Run() { + return RunOnHeadlessStack<int>([this]() { + return do_mode(options_.loop_, options_.device_.front(), + options_.non_options_); + }); +} diff --git a/system/test/headless/mode/mode.h b/system/test/headless/mode/mode.h new file mode 100644 index 0000000000..b75042c02f --- /dev/null +++ b/system/test/headless/mode/mode.h @@ -0,0 +1,35 @@ +/* + * 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. + */ + +#pragma once + +#include "test/headless/get_options.h" +#include "test/headless/headless.h" + +namespace bluetooth { +namespace test { +namespace headless { + +class Mode : public HeadlessTest<int> { + public: + Mode(const bluetooth::test::headless::GetOpt& options) + : HeadlessTest<int>(options) {} + int Run() override; +}; + +} // namespace headless +} // namespace test +} // namespace bluetooth diff --git a/system/test/headless/pairing/pairing.cc b/system/test/headless/pairing/pairing.cc index ed5c490d21..1f654ed189 100644 --- a/system/test/headless/pairing/pairing.cc +++ b/system/test/headless/pairing/pairing.cc @@ -16,14 +16,12 @@ #define LOG_TAG "bt_headless_sdp" -#include <future> +#include "test/headless/pairing/pairing.h" #include "base/logging.h" // LOG() stdout and android log #include "btif/include/btif_api.h" -#include "osi/include/log.h" // android log only #include "test/headless/get_options.h" #include "test/headless/headless.h" -#include "test/headless/pairing/pairing.h" #include "types/raw_address.h" int bluetooth::test::headless::Pairing::Run() { @@ -38,7 +36,7 @@ int bluetooth::test::headless::Pairing::Run() { return -1; } - RawAddress raw_address = options_.device_.front(); + [[maybe_unused]] RawAddress raw_address = options_.device_.front(); return RunOnHeadlessStack<int>([raw_address]() { btif_dm_create_bond(raw_address, BT_TRANSPORT_BR_EDR); diff --git a/system/test/headless/property.cc b/system/test/headless/property.cc index b0a098a84c..ad5485ae50 100644 --- a/system/test/headless/property.cc +++ b/system/test/headless/property.cc @@ -14,18 +14,22 @@ * limitations under the License. */ +#define LOG_TAG "bt_property" + #include "test/headless/property.h" #include <map> +#include "gd/os/log.h" #include "include/hardware/bluetooth.h" +#include "test/headless/log.h" using namespace bluetooth::test; namespace { // Map the bluetooth property names to the corresponding headless property -// structure +// structure factor std::map<::bt_property_type_t, std::function<headless::bt_property_t*( const uint8_t* data, const size_t len)>> property_map = { @@ -33,6 +37,10 @@ std::map<::bt_property_type_t, std::function<headless::bt_property_t*( [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { return new headless::property::name_t(data, len); }}, + {BT_PROPERTY_BDADDR, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::bdaddr_t(data, len); + }}, {BT_PROPERTY_UUIDS, [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { return new headless::property::uuid_t(data, len); @@ -45,6 +53,66 @@ std::map<::bt_property_type_t, std::function<headless::bt_property_t*( [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { return new headless::property::type_of_device_t(data, len); }}, + {BT_PROPERTY_SERVICE_RECORD, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t(data, len, + BT_PROPERTY_SERVICE_RECORD); + }}, + {BT_PROPERTY_ADAPTER_SCAN_MODE, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t(data, len, + BT_PROPERTY_ADAPTER_SCAN_MODE); + }}, + {BT_PROPERTY_ADAPTER_BONDED_DEVICES, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t( + data, len, BT_PROPERTY_ADAPTER_BONDED_DEVICES); + }}, + {BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t( + data, len, BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT); + }}, + {BT_PROPERTY_REMOTE_FRIENDLY_NAME, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t( + data, len, BT_PROPERTY_REMOTE_FRIENDLY_NAME); + }}, + {BT_PROPERTY_REMOTE_RSSI, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t(data, len, + BT_PROPERTY_REMOTE_RSSI); + }}, + {BT_PROPERTY_REMOTE_VERSION_INFO, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t( + data, len, BT_PROPERTY_REMOTE_VERSION_INFO); + }}, + {BT_PROPERTY_LOCAL_LE_FEATURES, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t(data, len, + BT_PROPERTY_LOCAL_LE_FEATURES); + }}, + {BT_PROPERTY_LOCAL_IO_CAPS, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t(data, len, + BT_PROPERTY_LOCAL_IO_CAPS); + }}, + {BT_PROPERTY_DYNAMIC_AUDIO_BUFFER, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t( + data, len, BT_PROPERTY_DYNAMIC_AUDIO_BUFFER); + }}, + {BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t( + data, len, BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER); + }}, + {BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP, + [](const uint8_t* data, const size_t len) -> headless::bt_property_t* { + return new headless::property::void_t( + data, len, BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP); + }}, }; } // namespace @@ -52,12 +120,13 @@ std::map<::bt_property_type_t, std::function<headless::bt_property_t*( // Caller owns the memory headless::bt_property_t* bluetooth::test::headless::property_factory( const ::bt_property_t& bt_property) { - ASSERT_LOG(bt_property.len > -1, "Property count is less than zero"); - ASSERT_LOG(bt_property.val != nullptr, "Property data value is null"); - const uint8_t* data = static_cast<uint8_t*>(bt_property.val); const size_t size = static_cast<size_t>(bt_property.len); + if (size > 0) { + ASSERT_LOG(data != nullptr, "Property value pointer is null"); + } + const auto factory = property_map.find(bt_property.type); if (factory != property_map.end()) { return factory->second(data, size); diff --git a/system/test/headless/property.h b/system/test/headless/property.h index bbc6d5a571..35d2f73f3e 100644 --- a/system/test/headless/property.h +++ b/system/test/headless/property.h @@ -20,21 +20,64 @@ #include <cstdint> #include <deque> #include <memory> +#include <sstream> #include <string> #include "include/hardware/bluetooth.h" +#include "macros.h" #include "test/headless/log.h" #include "types/bluetooth/uuid.h" +inline std::string bt_property_type_text(const ::bt_property_type_t type) { + switch (type) { + CASE_RETURN_TEXT(BT_PROPERTY_BDNAME); + CASE_RETURN_TEXT(BT_PROPERTY_BDADDR); + CASE_RETURN_TEXT(BT_PROPERTY_UUIDS); + CASE_RETURN_TEXT(BT_PROPERTY_CLASS_OF_DEVICE); + CASE_RETURN_TEXT(BT_PROPERTY_TYPE_OF_DEVICE); + CASE_RETURN_TEXT(BT_PROPERTY_SERVICE_RECORD); + CASE_RETURN_TEXT(BT_PROPERTY_ADAPTER_SCAN_MODE); + CASE_RETURN_TEXT(BT_PROPERTY_ADAPTER_BONDED_DEVICES); + CASE_RETURN_TEXT(BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT); + CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_FRIENDLY_NAME); + CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_RSSI); + CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_VERSION_INFO); + CASE_RETURN_TEXT(BT_PROPERTY_LOCAL_LE_FEATURES); + CASE_RETURN_TEXT(BT_PROPERTY_LOCAL_IO_CAPS); + CASE_RETURN_TEXT(BT_PROPERTY_RESERVED_0F); + CASE_RETURN_TEXT(BT_PROPERTY_DYNAMIC_AUDIO_BUFFER); + CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER); + CASE_RETURN_TEXT(BT_PROPERTY_APPEARANCE); + CASE_RETURN_TEXT(BT_PROPERTY_VENDOR_PRODUCT_INFO); + CASE_RETURN_TEXT(BT_PROPERTY_WL_MEDIA_PLAYERS_LIST); + CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_ASHA_CAPABILITY); + CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_ASHA_TRUNCATED_HISYNCID); + CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_MODEL_NUM); + CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP); + default: + return base::StringPrintf("UNKNOWN[%d]", type); + } +} + namespace bluetooth { namespace test { namespace headless { struct bt_property_t { - int Type() const { return type; } + ::bt_property_type_t Type() const { return type; } virtual std::string ToString() const = 0; + // TODO verify this prints as expected + std::string ToRaw() { + std::ostringstream oss; + const uint8_t* p = data.get(); + for (size_t i = 0; i < sizeof(bt_property_t); i++, p++) { + oss << "0x" << std::hex << *p << " "; + } + return oss.str(); + } + protected: bt_property_t(const uint8_t* data, const size_t len) { this->len = len; @@ -45,7 +88,7 @@ struct bt_property_t { std::unique_ptr<uint8_t[]> data; size_t len; - int type; + ::bt_property_type_t type; }; namespace property { @@ -53,12 +96,13 @@ namespace property { struct void_t : public bt_property_t { void_t(const uint8_t* data, const size_t len, int type) : bt_property_t(data, len) { - this->type = type; + this->type = (::bt_property_type_t)type; } public: virtual std::string ToString() const override { - return base::StringPrintf("void property type:%d", type); + return base::StringPrintf("Unimplemented property type:%d name:%s", type, + bt_property_type_text(type).c_str()); } }; @@ -100,6 +144,24 @@ struct name_t : public bt_property_t { } }; +struct bdaddr_t : public bt_property_t { + bdaddr_t(const uint8_t* data, const size_t len) : bt_property_t(data, len) { + type = BT_PROPERTY_BDNAME; + } + + RawAddress get_addr() const { + uint8_t* s = reinterpret_cast<uint8_t*>(data.get()); + // TODO This may need to be reversed + RawAddress bd_addr; + ASSERT_LOG(6U == bd_addr.FromOctets(s), "Mac address is not 6 bytes"); + return bd_addr; + } + + virtual std::string ToString() const override { + return base::StringPrintf("bd_addr:%s", get_addr().ToString().c_str()); + } +}; + struct class_of_device_t : public bt_property_t { class_of_device_t(const uint8_t* data, const size_t len) : bt_property_t(data, len) { diff --git a/system/test/headless/pushme.sh b/system/test/headless/pushme.sh new file mode 100755 index 0000000000..9aa24765b0 --- /dev/null +++ b/system/test/headless/pushme.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +## Cuttlefish 64 bit bt_headless installation +PRODUCT=vsoc_x86_64 + +## Ensure that the device storage has been remounted +adb root +adb remount -R +adb wait-for-device + +## Push various shared libraries where the executable expects to find them +adb push ${ANDROID_BUILD_TOP}/out/target/product/${PRODUCT}/symbols/system/bin/bt_headless /system/bin/bt_headless +adb push ${ANDROID_BUILD_TOP}/out/target/product/${PRODUCT}/symbols/system/lib64/android.hardware.bluetooth.audio@2.0.so /system/lib64/android.hardware.bluetooth.audio@2.0.so +adb push ${ANDROID_BUILD_TOP}/out/target/product/${PRODUCT}/symbols/system/lib64/android.hardware.bluetooth.audio@2.1.so /system/lib64/android.hardware.bluetooth.audio@2.1.so +adb push ${ANDROID_BUILD_TOP}/out/target/product/${PRODUCT}/symbols/system/lib64/android.hardware.bluetooth@1.0.so /system/lib64/android.hardware.bluetooth@1.0.so +adb push ${ANDROID_BUILD_TOP}/out/target/product/${PRODUCT}/symbols/system/lib64/android.hardware.bluetooth@1.1.so /system/lib64/android.hardware.bluetooth@1.1.so +adb push ${ANDROID_BUILD_TOP}/out/target/product/${PRODUCT}/symbols/system/lib64/android.hardware.bluetooth.audio-V4-ndk.so /system/lib64/android.hardware.bluetooth.audio-V4-ndk.so +adb push ${ANDROID_BUILD_TOP}/out/target/product/${PRODUCT}/symbols/system/lib64/android.hardware.audio.common-V3-ndk.so /system/lib64/android.hardware.audio.common-V3-ndk.so +adb push ${ANDROID_BUILD_TOP}/out/target/product/${PRODUCT}/symbols/system/lib64/android.media.audio.common.types-V3-ndk.so /system/lib64/android.media.audio.common.types-V3-ndk.so diff --git a/system/test/headless/scan/scan.cc b/system/test/headless/scan/scan.cc index 0c9e14fcdc..4cc674a09d 100644 --- a/system/test/headless/scan/scan.cc +++ b/system/test/headless/scan/scan.cc @@ -18,74 +18,61 @@ #include "test/headless/scan/scan.h" -#include <future> - #include "base/logging.h" // LOG() stdout and android log -#include "btif/include/btif_api.h" -#include "osi/include/log.h" // android log only -#include "stack/include/sdp_api.h" -#include "test/headless/bt_property.h" +#include "os/log.h" #include "test/headless/get_options.h" #include "test/headless/headless.h" #include "test/headless/interface.h" #include "test/headless/log.h" +#include "test/headless/messenger.h" +#include "test/headless/property.h" #include "test/headless/stopwatch.h" -#include "types/bluetooth/uuid.h" -#include "types/raw_address.h" -using namespace bluetooth::test::headless; +using namespace bluetooth::test; using namespace std::chrono_literals; -namespace scan { -std::promise<acl_state_changed_params_t> acl_state_changed_promise; -std::promise<remote_device_properties_params_t> - remote_device_properties_promise; - -std::mutex mutex; -std::condition_variable cv; - -std::queue<acl_state_changed_params_t> acl_state_changed_params_queue; -std::queue<discovery_state_changed_params_t> - discovery_state_changed_params_queue; -; - -// Callback from another thread -void callback_interface(callback_data_t* data) { - if (data->Name() == "discovery_state_changed") { - LOG(INFO) << "Received discovery_state_changed"; - auto params = static_cast<discovery_state_changed_params_t*>(data); - discovery_state_changed_params_queue.push(*params); - LOG_CONSOLE("Received discovery state change callback %s", - params->ToString().c_str()); - cv.notify_all(); - return; - } - LOG(ERROR) << "Received unexpected interface callback"; -} - -} // namespace scan - namespace { int start_scan([[maybe_unused]] unsigned int num_loops) { LOG(INFO) << "Started Device Scan"; - Stopwatch stop_watch("Inquiry_timeout"); - auto check_point = messenger::inquiry::get_check_point(); - ASSERT(bluetoothInterface.start_discovery() == BT_STATUS_SUCCESS); LOG_CONSOLE("Started inquiry - device discovery"); - while (stop_watch.LapMs() < 10000) { - if (messenger::inquiry::await_inquiry_result(1s, check_point, 1)) { - auto callback_queue = messenger::inquiry::collect_from(check_point); - while (!callback_queue.empty()) { - remote_device_properties_params_t params = callback_queue.front(); - callback_queue.pop_front(); - LOG_CONSOLE("Received remote inquiry :%s", STR(params)); - bt_property_t* prop = params.properties; - for (int i = 0; i < params.num_properties; ++i, prop++) { - process_property(params.bd_addr, prop); + headless::messenger::Context context{ + .stop_watch = Stopwatch("Inquiry_timeout"), + .timeout = 1s, + .check_point = {}, + .callbacks = {Callback::RemoteDeviceProperties, Callback::DeviceFound}, + }; + + while (context.stop_watch.LapMs() < 10000) { + // If we have received callback results within this timeframe... + if (headless::messenger::await_callback(context)) { + while (!context.callback_ready_q.empty()) { + std::shared_ptr<callback_params_t> p = context.callback_ready_q.front(); + context.callback_ready_q.pop_front(); + switch (p->CallbackType()) { + case Callback::RemoteDeviceProperties: { + remote_device_properties_params_t* q = + static_cast<remote_device_properties_params_t*>(p.get()); + for (const auto& p2 : q->properties()) { + LOG_CONSOLE(" %s prop:%s", p->Name().c_str(), + p2->ToString().c_str()); + } + } break; + case Callback::DeviceFound: { + device_found_params_t* q = + static_cast<device_found_params_t*>(p.get()); + for (const auto& p2 : q->properties()) { + LOG_CONSOLE(" %s prop:%s", p->Name().c_str(), + p2->ToString().c_str()); + } + } break; + default: + LOG_CONSOLE("WARN Received callback for unasked:%s", + p->Name().c_str()); + break; } } } diff --git a/system/test/headless/sdp/sdp.cc b/system/test/headless/sdp/sdp.cc index 6750f5a715..b975672395 100644 --- a/system/test/headless/sdp/sdp.cc +++ b/system/test/headless/sdp/sdp.cc @@ -21,7 +21,9 @@ #include <future> #include "base/logging.h" // LOG() stdout and android log -#include "osi/include/log.h" // android log only +#include "bta/dm/bta_dm_int.h" +#include "bta/include/bta_api.h" +#include "os/log.h" #include "osi/include/osi.h" // UNUSED_ATTR #include "stack/include/sdp_api.h" #include "test/headless/get_options.h" @@ -43,60 +45,23 @@ static void bta_jv_start_discovery_callback( namespace { -struct sdp_error_code_s { - const char* name; - uint16_t error_code; -} sdp_error_code[] = { - {"KsdpSuccess", 0}, - {"KsdpInvalidVersion", 0x0001}, - {"KsdpInvalidServRecHdl", 0x0002}, - {"KsdpInvalidReqSyntax", 0x0003}, - {"KsdpInvalidPduSize", 0x0004}, - {"KsdpInvalidContState", 0x0005}, - {"KsdpNoResources", 0x0006}, - {"KsdpDiRegFailed", 0x0007}, - {"KsdpDiDiscFailed", 0x0008}, - {"KsdpNoDiRecordFound", 0x0009}, - {"KsdpErrAttrNotPresent", 0x000a}, - {"KsdpIllegalParameter", 0x000b}, - {"KsdpNoRecsMatch", 0xFFF0}, - {"KsdpConnFailed", 0xFFF1}, - {"KsdpCfgFailed", 0xFFF2}, - {"KsdpGenericError", 0xFFF3}, - {"KsdpDbFull", 0xFFF4}, - {"KsdpInvalidPdu", 0xFFF5}, - {"KsdpSecurityErr", 0xFFF6}, - {"KsdpConnRejected", 0xFFF7}, - {"KsdpCancel", 0xFFF8}, -}; - -const char* kUnknownText = "Unknown"; - -const char* SdpErrorCodeToString(uint16_t code) { - for (size_t i = 0; i < sizeof(sdp_error_code) / sizeof(sdp_error_code_s); - ++i) { - if (sdp_error_code[i].error_code == code) { - return sdp_error_code[i].name; - } - } - return kUnknownText; -} - -constexpr size_t kMaxDiscoveryRecords = 64; +constexpr size_t kMaxDiscoveryRecords = 1024; int sdp_query_uuid([[maybe_unused]] unsigned int num_loops, - const RawAddress& raw_address, const bluetooth::Uuid& uuid) { + [[maybe_unused]] const RawAddress& raw_address, + [[maybe_unused]] const bluetooth::Uuid& uuid) { SdpDb sdp_discovery_db(kMaxDiscoveryRecords); if (!get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb( sdp_discovery_db.RawPointer(), sdp_discovery_db.Length(), 1, // num_uuid, &uuid, 0, nullptr)) { - fprintf(stdout, "%s Unable to initialize sdp discovery\n", __func__); + LOG_CONSOLE("Unable to initialize sdp discovery"); return -1; } + LOG_CONSOLE("Initialized sdp discovery database"); - std::promise<uint16_t> promise; + std::promise<tSDP_STATUS> promise; auto future = promise.get_future(); sdp_discovery_db.Print(stdout); @@ -107,24 +72,26 @@ int sdp_query_uuid([[maybe_unused]] unsigned int num_loops, fprintf(stdout, "%s Failed to start search attribute request\n", __func__); return -2; } + LOG_CONSOLE("Started service search for uuid:%s", uuid.ToString().c_str()); - uint16_t result = future.get(); - if (result != 0) { + const tSDP_STATUS result = future.get(); + if (result != SDP_SUCCESS) { fprintf(stdout, "Failed search discovery result:%s\n", - SdpErrorCodeToString(result)); + sdp_status_text(result).c_str()); return result; } - tSDP_DISC_REC* rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb( - sdp_discovery_db.RawPointer(), uuid.As16Bit(), nullptr); - if (rec == nullptr) { - fprintf(stdout, "discovery record is null from:%s uuid:%s\n", - raw_address.ToString().c_str(), uuid.ToString().c_str()); - } else { - fprintf(stdout, "result:%d attr_id:%x from:%s uuid:%s\n", result, - rec->p_first_attr->attr_id, rec->remote_bd_addr.ToString().c_str(), - uuid.ToString().c_str()); + LOG_CONSOLE("Found records peer:%s uuid:%s", raw_address.ToString().c_str(), + uuid.ToString().c_str()); + for (unsigned i = 0; i < BTA_MAX_SERVICE_ID; i++) { + uint16_t uuid_as16Bit = bta_service_id_to_uuid_lkup_tbl[i]; + tSDP_DISC_REC* rec = SDP_FindServiceInDb(sdp_discovery_db.RawPointer(), + uuid_as16Bit, nullptr); + if (rec != nullptr) { + LOG_CONSOLE(" uuid:0x%x", uuid_as16Bit); + } } + return 0; } diff --git a/system/test/headless/sdp/sdp_db.cc b/system/test/headless/sdp/sdp_db.cc index 023861b70b..d275b888c0 100644 --- a/system/test/headless/sdp/sdp_db.cc +++ b/system/test/headless/sdp/sdp_db.cc @@ -17,11 +17,10 @@ #define LOG_TAG "bt_headless" #include "test/headless/sdp/sdp_db.h" -#include "base/logging.h" // LOG() stdout and android log -#include "osi/include/log.h" // android log only + +#include "base/logging.h" // LOG() stdout and android log #include "stack/include/sdp_api.h" #include "types/bluetooth/uuid.h" -#include "types/raw_address.h" using namespace bluetooth::test::headless; diff --git a/system/test/headless/text.cc b/system/test/headless/text.cc new file mode 100644 index 0000000000..5a013ce1bb --- /dev/null +++ b/system/test/headless/text.cc @@ -0,0 +1,42 @@ +/* + * 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 "test/headless/text.h" + +#include <string> + +#include "include/hardware/bluetooth.h" +#include "macros.h" +#include "os/log.h" + +std::string bt_conn_direction_text(const bt_conn_direction_t& direction) { + switch (direction) { + CASE_RETURN_TEXT(BT_CONN_DIRECTION_UNKNOWN); + CASE_RETURN_TEXT(BT_CONN_DIRECTION_OUTGOING); + CASE_RETURN_TEXT(BT_CONN_DIRECTION_INCOMING); + default: + ASSERT_LOG(false, "Illegal bt_conn_direction:%d", direction); + } +} + +std::string bt_discovery_state_text(const bt_discovery_state_t& state) { + switch (state) { + CASE_RETURN_TEXT(BT_DISCOVERY_STOPPED); + CASE_RETURN_TEXT(BT_DISCOVERY_STARTED); + default: + ASSERT_LOG(false, "Illegal bt_discovery state:%d", state); + } +} diff --git a/system/test/headless/text.h b/system/test/headless/text.h new file mode 100644 index 0000000000..dac565d66d --- /dev/null +++ b/system/test/headless/text.h @@ -0,0 +1,22 @@ +/* + * 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 <string> + +#include "include/hardware/bluetooth.h" + +std::string bt_conn_direction_text(const bt_conn_direction_t& direction); +std::string bt_discovery_state_text(const bt_discovery_state_t& state); diff --git a/system/test/headless/util.cc b/system/test/headless/util.cc index d1231ca1ed..df3a15fd0e 100644 --- a/system/test/headless/util.cc +++ b/system/test/headless/util.cc @@ -16,6 +16,7 @@ #include <string> +#include "include/hardware/bluetooth.h" #include "osi/include/properties.h" bool is_android_running() { diff --git a/system/test/headless/utils/power_mode_client.h b/system/test/headless/utils/power_mode_client.h new file mode 100644 index 0000000000..e35d455625 --- /dev/null +++ b/system/test/headless/utils/power_mode_client.h @@ -0,0 +1,213 @@ +/* + * 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. + */ + +#pragma once + +#define LOG_TAG "bt_headless_mode" + +#include <base/strings/stringprintf.h> + +#include <future> +#include <mutex> + +#include "base/logging.h" // LOG() stdout and android log +#include "bta/dm/bta_dm_int.h" +#include "stack/include/btm_client_interface.h" +#include "stack/include/btm_status.h" +#include "stack/include/hci_error_code.h" +#include "types/raw_address.h" + +using namespace std::chrono_literals; + +namespace { +const tBTM_PM_PWR_MD default_mandatory_sniff_mode = { + .max = 0x0006, + .min = 0x0006, + .attempt = 0x0020, + .timeout = 0x7fff, + .mode = BTM_PM_MD_SNIFF, +}; + +const tBTM_PM_PWR_MD typical_sniff_mode = { + .max = 800, // 5 seconds + .min = 400, // 2.5 seconds + .attempt = 4, + .timeout = 1, + .mode = BTM_PM_MD_SNIFF, +}; + +const tBTM_PM_PWR_MD default_active_mode = { + .max = 0, // Unused + .min = 0, // Unused + .attempt = 0, // Unused + .timeout = 0, // Unused + .mode = BTM_PM_MD_ACTIVE, +}; +} // namespace + +// tBTM_PM_STATUS_CBACK +struct power_mode_callback_t { + const RawAddress bd_addr; + tBTM_PM_STATUS status; + uint16_t value; + tHCI_STATUS hci_status; + + std::string ToString() const { + return base::StringPrintf("bd_addr:%s pm_status:%s value:%hu hci_status:%s", + bd_addr.ToString().c_str(), + power_mode_status_text(status).c_str(), value, + hci_status_code_text(hci_status).c_str()); + } +}; + +struct pwr_command_t { + std::promise<power_mode_callback_t> cmd_status_promise; + std::promise<power_mode_callback_t> mode_event_promise; +}; + +struct pwr_result_t { + tBTM_STATUS btm_status; + std::future<power_mode_callback_t> cmd_status_future; + std::future<power_mode_callback_t> mode_event_future; +}; + +namespace { + +class Queue { + public: + void CallbackReceived(const power_mode_callback_t& data) { + LOG_INFO("Power mode callback cnt:%zu data:%s", cnt++, + data.ToString().c_str()); + std::unique_lock<std::mutex> lk(mutex); + if (promises_map_[data.bd_addr].empty()) { + LOG_INFO("Received unsolicited power mode callback: %s", + data.ToString().c_str()); + return; + } + promises_map_[data.bd_addr].front().set_value(data); + promises_map_[data.bd_addr].pop_front(); + } + + void CommandSent(const RawAddress& bd_addr, pwr_command_t&& pwr_command) { + std::unique_lock<std::mutex> lk(mutex); + promises_map_[bd_addr].push_back(std::move(pwr_command.cmd_status_promise)); + promises_map_[bd_addr].push_back(std::move(pwr_command.mode_event_promise)); + } + + void PopFront(const RawAddress& bd_addr) { + std::unique_lock<std::mutex> lk(mutex); + ASSERT_LOG(!promises_map_[bd_addr].empty(), + "Unable to remove promise from empty bag of promises"); + promises_map_[bd_addr].pop_front(); + } + + private: + mutable std::mutex mutex; + std::unordered_map<RawAddress, + std::deque<std::promise<power_mode_callback_t>>> + promises_map_; + size_t cnt = 0; + +} queue_; + +} // namespace + +class PowerMode { + public: + class Client { + public: + Client(const uint8_t pm_id, const RawAddress& bd_addr) + : pm_id_(pm_id), bd_addr_(bd_addr) {} + + // Used when the power mode command status is unsuccessful + // to prevent waiting for a mode event that will never arrive. + // Exposed to allow testing of these conditions. + void remove_mode_event_promise() { queue_.PopFront(bd_addr_); } + + pwr_result_t set_sniff(pwr_command_t&& pwr_command) { + return send_power_mode_command( + std::move(pwr_command), + get_btm_client_interface().link_policy.BTM_SetPowerMode( + pm_id_, bd_addr_, &default_mandatory_sniff_mode)); + } + pwr_result_t set_typical_sniff(pwr_command_t&& pwr_command) { + return send_power_mode_command( + std::move(pwr_command), + get_btm_client_interface().link_policy.BTM_SetPowerMode( + pm_id_, bd_addr_, &typical_sniff_mode)); + } + + pwr_result_t set_active(pwr_command_t&& pwr_command) { + return send_power_mode_command( + std::move(pwr_command), + get_btm_client_interface().link_policy.BTM_SetPowerMode( + pm_id_, bd_addr_, &default_active_mode)); + } + + private: + pwr_result_t send_power_mode_command(pwr_command_t&& pwr_command, + const tBTM_STATUS btm_status) { + pwr_result_t result = { + .btm_status = btm_status, + .cmd_status_future = pwr_command.cmd_status_promise.get_future(), + .mode_event_future = pwr_command.mode_event_promise.get_future(), + }; + queue_.CommandSent(bd_addr_, std::move(pwr_command)); + return result; + } + + const uint8_t pm_id_; + const RawAddress bd_addr_; + }; + + PowerMode() { + BTM_PmRegister(BTM_PM_DEREG, &bta_dm_cb.pm_id, + []([[maybe_unused]] const RawAddress& bd_addr, + [[maybe_unused]] tBTM_PM_STATUS status, + [[maybe_unused]] uint16_t value, + [[maybe_unused]] tHCI_STATUS hci_status) {}); + + tBTM_STATUS btm_status = + get_btm_client_interface().lifecycle.BTM_PmRegister( + BTM_PM_REG_SET, &pm_id_, + [](const RawAddress& bd_addr, tBTM_PM_STATUS status, uint16_t value, + tHCI_STATUS hci_status) { + queue_.CallbackReceived(power_mode_callback_t{ + .bd_addr = bd_addr, + .status = status, + .value = value, + .hci_status = hci_status, + }); + }); + + ASSERT_LOG(BTM_SUCCESS == btm_status, "Failed to register power mode:%s", + btm_status_text(btm_status).c_str()); + } + + ~PowerMode() { + ASSERT(BTM_SUCCESS == get_btm_client_interface().lifecycle.BTM_PmRegister( + BTM_PM_DEREG, &pm_id_, + []([[maybe_unused]] const RawAddress& bd_addr, + [[maybe_unused]] tBTM_PM_STATUS status, + [[maybe_unused]] uint16_t value, + [[maybe_unused]] tHCI_STATUS hci_status) {})); + } + + Client GetClient(const RawAddress bd_addr) { return Client(pm_id_, bd_addr); } + + private: + uint8_t pm_id_; +}; diff --git a/system/test/mock/mock_bluetooth_interface.cc b/system/test/mock/mock_bluetooth_interface.cc index f55d026ad2..86edb3faef 100644 --- a/system/test/mock/mock_bluetooth_interface.cc +++ b/system/test/mock/mock_bluetooth_interface.cc @@ -21,54 +21,66 @@ #include "stack/include/bt_octets.h" #include "types/raw_address.h" -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) {} -void invoke_remote_device_properties_cb(bt_status_t status, RawAddress bd_addr, - int num_properties, - bt_property_t* properties) {} -void invoke_device_found_cb(int num_properties, bt_property_t* properties) {} -void invoke_discovery_state_changed_cb(bt_discovery_state_t state) {} -void invoke_pin_request_cb(RawAddress bd_addr, bt_bdname_t bd_name, - uint32_t cod, bool min_16_digit) {} -void invoke_ssp_request_cb(RawAddress bd_addr, bt_bdname_t bd_name, - uint32_t cod, bt_ssp_variant_t pairing_variant, - uint32_t pass_key) {} -void invoke_oob_data_request_cb(tBT_TRANSPORT t, bool valid, Octet16 c, - Octet16 r, RawAddress raw_address, - uint8_t address_type) {} -void invoke_bond_state_changed_cb(bt_status_t status, RawAddress bd_addr, - bt_bond_state_t state, int fail_reason) {} -void invoke_address_consolidate_cb(RawAddress main_bd_addr, - RawAddress secondary_bd_addr) {} -void invoke_le_address_associate_cb(RawAddress main_bd_addr, - RawAddress secondary_bd_addr) {} -void invoke_acl_state_changed_cb(bt_status_t status, RawAddress 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) {} -void invoke_thread_evt_cb(bt_cb_thread_evt event) {} +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 */) {} +void invoke_remote_device_properties_cb(bt_status_t /* status */, + RawAddress /* bd_addr */, + int /* num_properties */, + bt_property_t* /* properties */) {} +void invoke_device_found_cb(int /* num_properties */, + bt_property_t* /* properties */) {} +void invoke_discovery_state_changed_cb(bt_discovery_state_t /* state */) {} +void invoke_pin_request_cb(RawAddress /* bd_addr */, bt_bdname_t /* bd_name */, + uint32_t /* cod */, bool /* min_16_digit */) {} +void invoke_ssp_request_cb(RawAddress /* bd_addr */, bt_bdname_t /* bd_name */, + uint32_t /* cod */, + bt_ssp_variant_t /* pairing_variant */, + uint32_t /* pass_key */) {} +void invoke_oob_data_request_cb(tBT_TRANSPORT /* t */, bool /* valid */, + Octet16 /* c */, Octet16 /* r */, + RawAddress /* raw_address */, + uint8_t /* address_type */) {} +void invoke_bond_state_changed_cb(bt_status_t /* status */, + RawAddress /* bd_addr */, + bt_bond_state_t /* state */, + int /* fail_reason */) {} +void invoke_address_consolidate_cb(RawAddress /* main_bd_addr */, + RawAddress /* secondary_bd_addr */) {} +void invoke_le_address_associate_cb(RawAddress /* main_bd_addr */, + RawAddress /* secondary_bd_addr */) {} +void invoke_acl_state_changed_cb(bt_status_t /* status */, + RawAddress /* 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 */) {} +void invoke_thread_evt_cb(bt_cb_thread_evt /* event */) {} -void invoke_le_test_mode_cb(bt_status_t status, uint16_t count) {} +void invoke_le_test_mode_cb(bt_status_t /* status */, uint16_t /* count */) {} -void invoke_energy_info_cb(bt_activity_energy_info energy_info, - bt_uid_traffic_t* uid_data) {} -void invoke_link_quality_report_cb(uint64_t timestamp, int report_id, int rssi, - int snr, int retransmission_count, - int packets_not_receive_count, - int negative_acknowledgement_count) {} -void invoke_key_missing_cb(const RawAddress bd_addr) {} +void invoke_energy_info_cb(bt_activity_energy_info /* energy_info */, + bt_uid_traffic_t* /* uid_data */) {} +void invoke_link_quality_report_cb(uint64_t /* timestamp */, + int /* report_id */, int /* rssi */, + int /* snr */, + int /* retransmission_count */, + int /* packets_not_receive_count */, + int /* negative_acknowledgement_count */) {} +void invoke_key_missing_cb(const RawAddress /* bd_addr */) {} -static void init_stack(bluetooth::core::CoreInterface* interface) {} +static void init_stack(bluetooth::core::CoreInterface* /* interface */) {} -static void start_up_stack_async(bluetooth::core::CoreInterface* interface, - ProfileStartCallback startProfiles, - ProfileStopCallback stopProfiles) {} +static void start_up_stack_async( + bluetooth::core::CoreInterface* /* interface */, + ProfileStartCallback /* startProfiles */, + ProfileStopCallback /* stopProfiles */) {} -static void shut_down_stack_async(ProfileStopCallback stopProfiles) {} +static void shut_down_stack_async(ProfileStopCallback /* stopProfiles */) {} -static void clean_up_stack(ProfileStopCallback stopProfiles) {} +static void clean_up_stack(ProfileStopCallback /* stopProfiles */) {} static bool get_stack_is_running() { return true; } diff --git a/system/test/mock/mock_bta_csis.cc b/system/test/mock/mock_bta_csis.cc index 6ec2761d88..3280acb2f9 100644 --- a/system/test/mock/mock_bta_csis.cc +++ b/system/test/mock/mock_bta_csis.cc @@ -25,8 +25,7 @@ using bluetooth::csis::CsisClient; using bluetooth::csis::CsisClientCallbacks; void CsisClient::AddFromStorage(const RawAddress& addr, - const std::vector<uint8_t>& in, - bool autoconnect) { + const std::vector<uint8_t>& in) { inc_func_call_count(__func__); } bool CsisClient::GetForStorage(const RawAddress& addr, diff --git a/system/test/mock/mock_bta_sys_main.cc b/system/test/mock/mock_bta_sys_main.cc index 2b023e3ceb..c081c01a95 100644 --- a/system/test/mock/mock_bta_sys_main.cc +++ b/system/test/mock/mock_bta_sys_main.cc @@ -36,7 +36,6 @@ namespace bta_sys_main { // Function state capture and return values, if needed struct BTA_sys_signal_hw_error BTA_sys_signal_hw_error; -struct bta_set_forward_hw_failures bta_set_forward_hw_failures; struct bta_sys_deregister bta_sys_deregister; struct bta_sys_disable bta_sys_disable; struct bta_sys_init bta_sys_init; @@ -55,10 +54,6 @@ void BTA_sys_signal_hw_error() { inc_func_call_count(__func__); test::mock::bta_sys_main::BTA_sys_signal_hw_error(); } -void bta_set_forward_hw_failures(bool value) { - inc_func_call_count(__func__); - test::mock::bta_sys_main::bta_set_forward_hw_failures(value); -} void bta_sys_deregister(uint8_t id) { inc_func_call_count(__func__); test::mock::bta_sys_main::bta_sys_deregister(id); diff --git a/system/test/mock/mock_bta_sys_main.h b/system/test/mock/mock_bta_sys_main.h index 0659ded844..ba82977b4f 100644 --- a/system/test/mock/mock_bta_sys_main.h +++ b/system/test/mock/mock_bta_sys_main.h @@ -44,15 +44,6 @@ struct BTA_sys_signal_hw_error { }; extern struct BTA_sys_signal_hw_error BTA_sys_signal_hw_error; -// Name: bta_set_forward_hw_failures -// Params: bool value -// Return: void -struct bta_set_forward_hw_failures { - std::function<void(bool value)> body{[](bool value) {}}; - void operator()(bool value) { body(value); }; -}; -extern struct bta_set_forward_hw_failures bta_set_forward_hw_failures; - // Name: bta_sys_deregister // Params: uint8_t id // Return: void diff --git a/system/test/mock/mock_btif_av.h b/system/test/mock/mock_btif_av.h index ee2fa23a1f..519c394d96 100644 --- a/system/test/mock/mock_btif_av.h +++ b/system/test/mock/mock_btif_av.h @@ -60,7 +60,7 @@ namespace btif_av { // Return: void struct btif_av_acl_disconnected { std::function<void(const RawAddress& peer_address)> body{ - [](const RawAddress& peer_address) {}}; + [](const RawAddress& /* peer_address */) {}}; void operator()(const RawAddress& peer_address) { body(peer_address); }; }; extern struct btif_av_acl_disconnected btif_av_acl_disconnected; @@ -81,7 +81,7 @@ extern struct btif_av_clear_remote_suspend_flag struct btif_av_find_by_handle { static const RawAddress& return_value; std::function<const RawAddress&(tBTA_AV_HNDL bta_handle)> body{ - [](tBTA_AV_HNDL bta_handle) { return return_value; }}; + [](tBTA_AV_HNDL /* bta_handle */) { return return_value; }}; const RawAddress& operator()(tBTA_AV_HNDL bta_handle) { return body(bta_handle); }; @@ -166,7 +166,7 @@ extern struct btif_av_is_connected btif_av_is_connected; struct btif_av_is_connected_addr { static bool return_value; std::function<bool(const RawAddress& peer_address)> body{ - [](const RawAddress& peer_address) { return return_value; }}; + [](const RawAddress& /* peer_address */) { return return_value; }}; bool operator()(const RawAddress& peer_address) { return body(peer_address); }; @@ -179,7 +179,7 @@ extern struct btif_av_is_connected_addr btif_av_is_connected_addr; struct btif_av_is_peer_edr { static bool return_value; std::function<bool(const RawAddress& peer_address)> body{ - [](const RawAddress& peer_address) { return return_value; }}; + [](const RawAddress& /* peer_address */) { return return_value; }}; bool operator()(const RawAddress& peer_address) { return body(peer_address); }; @@ -192,7 +192,7 @@ extern struct btif_av_is_peer_edr btif_av_is_peer_edr; struct btif_av_is_peer_silenced { static bool return_value; std::function<bool(const RawAddress& peer_address)> body{ - [](const RawAddress& peer_address) { return return_value; }}; + [](const RawAddress& /* peer_address */) { return return_value; }}; bool operator()(const RawAddress& peer_address) { return body(peer_address); }; @@ -225,7 +225,7 @@ extern struct btif_av_is_source_enabled btif_av_is_source_enabled; struct btif_av_peer_is_connected_sink { static bool return_value; std::function<bool(const RawAddress& peer_address)> body{ - [](const RawAddress& peer_address) { return return_value; }}; + [](const RawAddress& /* peer_address */) { return return_value; }}; bool operator()(const RawAddress& peer_address) { return body(peer_address); }; @@ -238,7 +238,7 @@ extern struct btif_av_peer_is_connected_sink btif_av_peer_is_connected_sink; struct btif_av_peer_is_connected_source { static bool return_value; std::function<bool(const RawAddress& peer_address)> body{ - [](const RawAddress& peer_address) { return return_value; }}; + [](const RawAddress& /* peer_address */) { return return_value; }}; bool operator()(const RawAddress& peer_address) { return body(peer_address); }; @@ -251,7 +251,7 @@ extern struct btif_av_peer_is_connected_source btif_av_peer_is_connected_source; struct btif_av_peer_is_sink { static bool return_value; std::function<bool(const RawAddress& peer_address)> body{ - [](const RawAddress& peer_address) { return return_value; }}; + [](const RawAddress& /* peer_address */) { return return_value; }}; bool operator()(const RawAddress& peer_address) { return body(peer_address); }; @@ -264,7 +264,7 @@ extern struct btif_av_peer_is_sink btif_av_peer_is_sink; struct btif_av_peer_is_source { static bool return_value; std::function<bool(const RawAddress& peer_address)> body{ - [](const RawAddress& peer_address) { return return_value; }}; + [](const RawAddress& /* peer_address */) { return return_value; }}; bool operator()(const RawAddress& peer_address) { return body(peer_address); }; @@ -277,7 +277,7 @@ extern struct btif_av_peer_is_source btif_av_peer_is_source; struct btif_av_peer_prefers_mandatory_codec { static bool return_value; std::function<bool(const RawAddress& peer_address)> body{ - [](const RawAddress& peer_address) { return return_value; }}; + [](const RawAddress& /* peer_address */) { return return_value; }}; bool operator()(const RawAddress& peer_address) { return body(peer_address); }; @@ -291,7 +291,7 @@ extern struct btif_av_peer_prefers_mandatory_codec struct btif_av_peer_supports_3mbps { static bool return_value; std::function<bool(const RawAddress& peer_address)> body{ - [](const RawAddress& peer_address) { return return_value; }}; + [](const RawAddress& /* peer_address */) { return return_value; }}; bool operator()(const RawAddress& peer_address) { return body(peer_address); }; @@ -310,12 +310,12 @@ struct btif_av_report_source_codec_state { const std::vector<btav_a2dp_codec_config_t>& codecs_local_capabilities, const std::vector<btav_a2dp_codec_config_t>& codecs_selectable_capabilities)> - body{[](const RawAddress& peer_address, - const btav_a2dp_codec_config_t& codec_config, + body{[](const RawAddress& /* peer_address */, + const btav_a2dp_codec_config_t& /* codec_config */, const std::vector<btav_a2dp_codec_config_t>& - codecs_local_capabilities, + /* codecs_local_capabilities */, const std::vector<btav_a2dp_codec_config_t>& - codecs_selectable_capabilities) {}}; + /* codecs_selectable_capabilities */) {}}; void operator()( const RawAddress& peer_address, const btav_a2dp_codec_config_t& codec_config, @@ -343,7 +343,7 @@ extern struct btif_av_reset_audio_delay btif_av_reset_audio_delay; // Return: void struct btif_av_set_audio_delay { std::function<void(const RawAddress& peer_address, uint16_t delay)> body{ - [](const RawAddress& peer_address, uint16_t delay) {}}; + [](const RawAddress& /* peer_address */, uint16_t /* delay */) {}}; void operator()(const RawAddress& peer_address, uint16_t delay) { body(peer_address, delay); }; @@ -355,7 +355,7 @@ extern struct btif_av_set_audio_delay btif_av_set_audio_delay; // Return: void struct btif_av_set_dynamic_audio_buffer_size { std::function<void(uint8_t dynamic_audio_buffer_size)> body{ - [](uint8_t dynamic_audio_buffer_size) {}}; + [](uint8_t /* dynamic_audio_buffer_size */) {}}; void operator()(uint8_t dynamic_audio_buffer_size) { body(dynamic_audio_buffer_size); }; @@ -367,7 +367,8 @@ extern struct btif_av_set_dynamic_audio_buffer_size // Params: bool is_low_latency // Return: void struct btif_av_set_low_latency { - std::function<void(bool is_low_latency)> body{[](bool is_low_latency) {}}; + std::function<void(bool is_low_latency)> body{ + [](bool /* is_low_latency */) {}}; void operator()(bool is_low_latency) { body(is_low_latency); }; }; extern struct btif_av_set_low_latency btif_av_set_low_latency; @@ -388,7 +389,7 @@ extern struct btif_av_sink_active_peer btif_av_sink_active_peer; struct btif_av_sink_execute_service { static bt_status_t return_value; std::function<bt_status_t(bool enable)> body{ - [](bool enable) { return return_value; }}; + [](bool /* enable */) { return return_value; }}; bt_status_t operator()(bool enable) { return body(enable); }; }; extern struct btif_av_sink_execute_service btif_av_sink_execute_service; @@ -409,7 +410,7 @@ extern struct btif_av_source_active_peer btif_av_source_active_peer; struct btif_av_source_execute_service { static bt_status_t return_value; std::function<bt_status_t(bool enable)> body{ - [](bool enable) { return return_value; }}; + [](bool /* enable */) { return return_value; }}; bt_status_t operator()(bool enable) { return body(enable); }; }; extern struct btif_av_source_execute_service btif_av_source_execute_service; @@ -419,7 +420,7 @@ extern struct btif_av_source_execute_service btif_av_source_execute_service; // Return: void struct btif_av_src_disconnect_sink { std::function<void(const RawAddress& peer_address)> body{ - [](const RawAddress& peer_address) {}}; + [](const RawAddress& /* peer_address */) {}}; void operator()(const RawAddress& peer_address) { body(peer_address); }; }; extern struct btif_av_src_disconnect_sink btif_av_src_disconnect_sink; @@ -466,7 +467,8 @@ extern struct btif_av_stream_start_offload btif_av_stream_start_offload; // Params: bool use_latency_mode // Return: void struct btif_av_stream_start_with_latency { - std::function<void(bool use_latency_mode)> body{[](bool use_latency_mode) {}}; + std::function<void(bool use_latency_mode)> body{ + [](bool /* use_latency_mode */) {}}; void operator()(bool use_latency_mode) { body(use_latency_mode); }; }; extern struct btif_av_stream_start_with_latency @@ -487,7 +489,7 @@ extern struct btif_av_stream_started_ready btif_av_stream_started_ready; // Return: void struct btif_av_stream_stop { std::function<void(const RawAddress& peer_address)> body{ - [](const RawAddress& peer_address) {}}; + [](const RawAddress& /* peer_address */) {}}; void operator()(const RawAddress& peer_address) { body(peer_address); }; }; extern struct btif_av_stream_stop btif_av_stream_stop; @@ -505,7 +507,7 @@ extern struct btif_av_stream_suspend btif_av_stream_suspend; // Params: int fd // Return: void struct btif_debug_av_dump { - std::function<void(int fd)> body{[](int fd) {}}; + std::function<void(int fd)> body{[](int /* fd */) {}}; void operator()(int fd) { body(fd); }; }; extern struct btif_debug_av_dump btif_debug_av_dump; @@ -516,7 +518,7 @@ extern struct btif_debug_av_dump btif_debug_av_dump; struct dump_av_sm_event_name { static const char* return_value; std::function<const char*(int event)> body{ - [](int event) { return return_value; }}; + [](int /* event */) { return return_value; }}; const char* operator()(int event) { return body(event); }; }; extern struct dump_av_sm_event_name dump_av_sm_event_name; @@ -526,7 +528,7 @@ extern struct dump_av_sm_event_name dump_av_sm_event_name; // Return: void struct src_do_suspend_in_main_thread { std::function<void(btif_av_sm_event_t event)> body{ - [](btif_av_sm_event_t event) {}}; + [](btif_av_sm_event_t /* event */) {}}; void operator()(btif_av_sm_event_t event) { body(event); }; }; extern struct src_do_suspend_in_main_thread src_do_suspend_in_main_thread; diff --git a/system/test/mock/mock_btif_avrcp_service.h b/system/test/mock/mock_btif_avrcp_service.h index 3ba33f735c..a0484d3b5b 100644 --- a/system/test/mock/mock_btif_avrcp_service.h +++ b/system/test/mock/mock_btif_avrcp_service.h @@ -41,7 +41,7 @@ namespace btif_avrcp_service { // Return: void struct do_in_avrcp_jni { std::function<void(const base::Closure& task)> body{ - [](const base::Closure& task) {}}; + [](const base::Closure& /* task */) {}}; void operator()(const base::Closure& task) { body(task); }; }; extern struct do_in_avrcp_jni do_in_avrcp_jni; diff --git a/system/test/mock/mock_btif_bluetooth.h b/system/test/mock/mock_btif_bluetooth.h index 7f1fad0fd2..fb06c563a1 100644 --- a/system/test/mock/mock_btif_bluetooth.h +++ b/system/test/mock/mock_btif_bluetooth.h @@ -62,7 +62,8 @@ extern struct is_restricted_mode is_restricted_mode; // Params: uint8_t enable // Returns: int struct dut_mode_configure { - std::function<int(uint8_t enable)> body{[](uint8_t enable) { return 0; }}; + 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; @@ -70,8 +71,11 @@ extern struct dut_mode_configure dut_mode_configure; // 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; }}; + 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); }; @@ -91,7 +95,7 @@ extern struct get_common_criteria_config_compare_result // Returns: int struct get_remote_device_properties { std::function<int(RawAddress* remote_addr)> body{ - [](RawAddress* remote_addr) { return 0; }}; + [](RawAddress* /* remote_addr */) { return 0; }}; int operator()(RawAddress* remote_addr) { return body(remote_addr); }; }; extern struct get_remote_device_properties get_remote_device_properties; @@ -100,7 +104,9 @@ extern struct get_remote_device_properties get_remote_device_properties; // 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; }}; + [](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); }; @@ -111,7 +117,7 @@ extern struct get_remote_device_property get_remote_device_property; // Returns: int struct get_remote_services { std::function<int(RawAddress* remote_addr)> body{ - [](RawAddress* remote_addr) { return 0; }}; + [](RawAddress* /* remote_addr */) { return 0; }}; int operator()(RawAddress* remote_addr) { return body(remote_addr); }; }; extern struct get_remote_services get_remote_services; @@ -120,7 +126,9 @@ extern struct get_remote_services get_remote_services; // 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; }}; + [](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); }; @@ -131,9 +139,8 @@ extern struct le_test_mode le_test_mode; // 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; - }}; + 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); }; @@ -144,7 +151,7 @@ extern struct set_remote_device_property set_remote_device_property; // Returns: void struct set_hal_cbacks { std::function<void(bt_callbacks_t* callbacks)> body{ - [](bt_callbacks_t* callbacks) { ; }}; + [](bt_callbacks_t* /* callbacks */) { ; }}; void operator()(bt_callbacks_t* callbacks) { body(callbacks); }; }; extern struct set_hal_cbacks set_hal_cbacks; diff --git a/system/test/mock/mock_btif_bqr.cc b/system/test/mock/mock_btif_bqr.cc index 8e2ffb38ba..b634704373 100644 --- a/system/test/mock/mock_btif_bqr.cc +++ b/system/test/mock/mock_btif_bqr.cc @@ -26,11 +26,11 @@ namespace bluetooth { namespace bqr { -void DumpLmpLlMessage(uint8_t length, const uint8_t* p_event) { +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) { +void DumpBtScheduling(uint8_t /* length */, const uint8_t* /* p_event */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_btif_bta_pan_co_rx.h b/system/test/mock/mock_btif_bta_pan_co_rx.h index 9f5e90e45c..d9059c5427 100644 --- a/system/test/mock/mock_btif_bta_pan_co_rx.h +++ b/system/test/mock/mock_btif_bta_pan_co_rx.h @@ -37,7 +37,7 @@ namespace btif_bta_pan_co_rx { // Returns: uint8_t struct bta_pan_co_init { std::function<uint8_t(uint8_t* q_level)> body{ - [](uint8_t* q_level) { return 0; }}; + [](uint8_t* /* q_level */) { return 0; }}; uint8_t operator()(uint8_t* q_level) { return body(q_level); }; }; extern struct bta_pan_co_init bta_pan_co_init; @@ -46,7 +46,7 @@ extern struct bta_pan_co_init bta_pan_co_init; // Returns: void struct bta_pan_co_close { std::function<void(uint16_t handle, uint8_t app_id)> body{ - [](uint16_t handle, uint8_t app_id) { ; }}; + [](uint16_t /* handle */, uint8_t /* app_id */) { ; }}; void operator()(uint16_t handle, uint8_t app_id) { body(handle, app_id); }; }; extern struct bta_pan_co_close bta_pan_co_close; @@ -57,8 +57,9 @@ extern struct bta_pan_co_close bta_pan_co_close; struct bta_pan_co_mfilt_ind { std::function<void(uint16_t handle, bool indication, tBTA_PAN_STATUS result, uint16_t len, uint8_t* p_filters)> - body{[](uint16_t handle, bool indication, tBTA_PAN_STATUS result, - uint16_t len, uint8_t* p_filters) { ; }}; + body{[](uint16_t /* handle */, bool /* indication */, + tBTA_PAN_STATUS /* result */, uint16_t /* len */, + uint8_t* /* p_filters */) { ; }}; void operator()(uint16_t handle, bool indication, tBTA_PAN_STATUS result, uint16_t len, uint8_t* p_filters) { body(handle, indication, result, len, p_filters); @@ -72,8 +73,9 @@ extern struct bta_pan_co_mfilt_ind bta_pan_co_mfilt_ind; struct bta_pan_co_pfilt_ind { std::function<void(uint16_t handle, bool indication, tBTA_PAN_STATUS result, uint16_t len, uint8_t* p_filters)> - body{[](uint16_t handle, bool indication, tBTA_PAN_STATUS result, - uint16_t len, uint8_t* p_filters) { ; }}; + body{[](uint16_t /* handle */, bool /* indication */, + tBTA_PAN_STATUS /* result */, uint16_t /* len */, + uint8_t* /* p_filters */) { ; }}; void operator()(uint16_t handle, bool indication, tBTA_PAN_STATUS result, uint16_t len, uint8_t* p_filters) { body(handle, indication, result, len, p_filters); @@ -85,7 +87,7 @@ extern struct bta_pan_co_pfilt_ind bta_pan_co_pfilt_ind; // bool enable Returns: void struct bta_pan_co_rx_flow { std::function<void(uint16_t handle, uint8_t app_id, bool enable)> body{ - [](uint16_t handle, uint8_t app_id, bool enable) { ; }}; + [](uint16_t /* handle */, uint8_t /* app_id */, bool /* enable */) { ; }}; void operator()(uint16_t handle, uint8_t app_id, bool enable) { body(handle, app_id, enable); }; @@ -96,7 +98,7 @@ extern struct bta_pan_co_rx_flow bta_pan_co_rx_flow; // Returns: void struct bta_pan_co_rx_path { std::function<void(uint16_t handle, uint8_t app_id)> body{ - [](uint16_t handle, uint8_t app_id) { ; }}; + [](uint16_t /* handle */, uint8_t /* app_id */) { ; }}; void operator()(uint16_t handle, uint8_t app_id) { body(handle, app_id); }; }; extern struct bta_pan_co_rx_path bta_pan_co_rx_path; @@ -105,7 +107,7 @@ extern struct bta_pan_co_rx_path bta_pan_co_rx_path; // Returns: void struct bta_pan_co_tx_path { std::function<void(uint16_t handle, uint8_t app_id)> body{ - [](uint16_t handle, uint8_t app_id) { ; }}; + [](uint16_t /* handle */, uint8_t /* app_id */) { ; }}; void operator()(uint16_t handle, uint8_t app_id) { body(handle, app_id); }; }; extern struct bta_pan_co_tx_path bta_pan_co_tx_path; diff --git a/system/test/mock/mock_btif_co_bta_av_co.h b/system/test/mock/mock_btif_co_bta_av_co.h index e463e61034..69de9c7779 100644 --- a/system/test/mock/mock_btif_co_bta_av_co.h +++ b/system/test/mock/mock_btif_co_bta_av_co.h @@ -51,7 +51,8 @@ namespace btif_co_bta_av_co { struct bta_av_co_audio_close { std::function<void(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address)> - body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) {}}; + body{[](tBTA_AV_HNDL /* bta_av_handle */, + const RawAddress& /* peer_address */) {}}; void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) { body(bta_av_handle, peer_address); }; @@ -64,8 +65,8 @@ extern struct bta_av_co_audio_close bta_av_co_audio_close; struct bta_av_co_audio_delay { std::function<void(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint16_t delay)> - body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, - uint16_t delay) {}}; + body{[](tBTA_AV_HNDL /* bta_av_handle */, + const RawAddress& /* peer_address */, uint16_t /* delay */) {}}; void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint16_t delay) { body(bta_av_handle, peer_address, delay); @@ -81,9 +82,10 @@ struct bta_av_co_audio_disc_res { std::function<void(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint8_t num_seps, uint8_t num_sinks, uint8_t num_sources, uint16_t uuid_local)> - body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, - uint8_t num_seps, uint8_t num_sinks, uint8_t num_sources, - uint16_t uuid_local) {}}; + body{[](tBTA_AV_HNDL /* bta_av_handle */, + const RawAddress& /* peer_address */, uint8_t /* num_seps */, + uint8_t /* num_sinks */, uint8_t /* num_sources */, + uint16_t /* uuid_local */) {}}; void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint8_t num_seps, uint8_t num_sinks, uint8_t num_sources, uint16_t uuid_local) { @@ -99,7 +101,8 @@ extern struct bta_av_co_audio_disc_res bta_av_co_audio_disc_res; struct bta_av_co_audio_drop { std::function<void(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address)> - body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) {}}; + body{[](tBTA_AV_HNDL /* bta_av_handle */, + const RawAddress& /* peer_address */) {}}; void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) { body(bta_av_handle, peer_address); }; @@ -116,10 +119,11 @@ struct bta_av_co_audio_getconfig { tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint8_t* p_codec_info, uint8_t* p_sep_info_idx, uint8_t seid, uint8_t* p_num_protect, uint8_t* p_protect_info)> - body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, - uint8_t* p_codec_info, uint8_t* p_sep_info_idx, uint8_t seid, - uint8_t* p_num_protect, - uint8_t* p_protect_info) { return return_value; }}; + body{[](tBTA_AV_HNDL /* bta_av_handle */, + const RawAddress& /* peer_address */, uint8_t* /* p_codec_info */, + uint8_t* /* p_sep_info_idx */, uint8_t /* seid */, + uint8_t* /* p_num_protect */, + uint8_t* /* p_protect_info */) { return return_value; }}; tA2DP_STATUS operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint8_t* p_codec_info, uint8_t* p_sep_info_idx, uint8_t seid, @@ -137,9 +141,8 @@ struct bta_av_co_audio_init { static bool return_value; std::function<bool(btav_a2dp_codec_index_t codec_index, AvdtpSepConfig* p_cfg)> - body{[](btav_a2dp_codec_index_t codec_index, AvdtpSepConfig* p_cfg) { - return return_value; - }}; + body{[](btav_a2dp_codec_index_t /* codec_index */, + AvdtpSepConfig* /* p_cfg */) { return return_value; }}; bool operator()(btav_a2dp_codec_index_t codec_index, AvdtpSepConfig* p_cfg) { return body(codec_index, p_cfg); }; @@ -152,8 +155,8 @@ extern struct bta_av_co_audio_init bta_av_co_audio_init; struct bta_av_co_audio_open { std::function<void(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint16_t mtu)> - body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, - uint16_t mtu) {}}; + body{[](tBTA_AV_HNDL /* bta_av_handle */, + const RawAddress& /* peer_address */, uint16_t /* mtu */) {}}; void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint16_t mtu) { body(bta_av_handle, peer_address, mtu); @@ -170,10 +173,11 @@ struct bta_av_co_audio_setconfig { const uint8_t* p_codec_info, uint8_t seid, uint8_t num_protect, const uint8_t* p_protect_info, uint8_t t_local_sep, uint8_t avdt_handle)> - body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, - const uint8_t* p_codec_info, uint8_t seid, uint8_t num_protect, - const uint8_t* p_protect_info, uint8_t t_local_sep, - uint8_t avdt_handle) {}}; + body{[](tBTA_AV_HNDL /* bta_av_handle */, + const RawAddress& /* peer_address */, + const uint8_t* /* p_codec_info */, uint8_t /* seid */, + uint8_t /* num_protect */, const uint8_t* /* p_protect_info */, + uint8_t /* t_local_sep */, uint8_t /* avdt_handle */) {}}; void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, const uint8_t* p_codec_info, uint8_t seid, uint8_t num_protect, const uint8_t* p_protect_info, @@ -190,7 +194,7 @@ extern struct bta_av_co_audio_setconfig bta_av_co_audio_setconfig; struct bta_av_co_audio_source_data_path { static BT_HDR* return_value; std::function<BT_HDR*(const uint8_t* p_codec_info, uint32_t* p_timestamp)> - body{[](const uint8_t* p_codec_info, uint32_t* p_timestamp) { + body{[](const uint8_t* /* p_codec_info */, uint32_t* /* p_timestamp */) { return return_value; }}; BT_HDR* operator()(const uint8_t* p_codec_info, uint32_t* p_timestamp) { @@ -205,8 +209,10 @@ extern struct bta_av_co_audio_source_data_path bta_av_co_audio_source_data_path; struct bta_av_co_audio_start { std::function<void(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, const uint8_t* p_codec_info, bool* p_no_rtp_header)> - body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, - const uint8_t* p_codec_info, bool* p_no_rtp_header) {}}; + body{[](tBTA_AV_HNDL /* bta_av_handle */, + const RawAddress& /* peer_address */, + const uint8_t* /* p_codec_info */, + bool* /* p_no_rtp_header */) {}}; void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, const uint8_t* p_codec_info, bool* p_no_rtp_header) { body(bta_av_handle, peer_address, p_codec_info, p_no_rtp_header); @@ -220,7 +226,8 @@ extern struct bta_av_co_audio_start bta_av_co_audio_start; struct bta_av_co_audio_stop { std::function<void(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address)> - body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) {}}; + body{[](tBTA_AV_HNDL /* bta_av_handle */, + const RawAddress& /* peer_address */) {}}; void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) { body(bta_av_handle, peer_address); }; @@ -233,8 +240,8 @@ extern struct bta_av_co_audio_stop bta_av_co_audio_stop; struct bta_av_co_audio_update_mtu { std::function<void(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint16_t mtu)> - body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, - uint16_t mtu) {}}; + body{[](tBTA_AV_HNDL /* bta_av_handle */, + const RawAddress& /* peer_address */, uint16_t /* mtu */) {}}; void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address, uint16_t mtu) { body(bta_av_handle, peer_address, mtu); @@ -270,8 +277,8 @@ extern struct bta_av_co_get_encoder_interface bta_av_co_get_encoder_interface; struct bta_av_co_get_peer_params { std::function<void(const RawAddress& peer_address, tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params)> - body{[](const RawAddress& peer_address, - tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params) {}}; + body{[](const RawAddress& /* peer_address */, + tA2DP_ENCODER_INIT_PEER_PARAMS* /* p_peer_params */) {}}; void operator()(const RawAddress& peer_address, tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params) { body(peer_address, p_peer_params); @@ -285,7 +292,7 @@ extern struct bta_av_co_get_peer_params bta_av_co_get_peer_params; struct bta_av_co_get_scmst_info { static btav_a2dp_scmst_info_t return_value; std::function<btav_a2dp_scmst_info_t(const RawAddress& peer_address)> body{ - [](const RawAddress& peer_address) { return return_value; }}; + [](const RawAddress& /* peer_address */) { return return_value; }}; btav_a2dp_scmst_info_t operator()(const RawAddress& peer_address) { return body(peer_address); }; @@ -299,8 +306,9 @@ struct bta_av_co_init { std::function<void( const std::vector<btav_a2dp_codec_config_t>& codec_priorities, std::vector<btav_a2dp_codec_info_t>* supported_codecs)> - body{[](const std::vector<btav_a2dp_codec_config_t>& codec_priorities, - std::vector<btav_a2dp_codec_info_t>* supported_codecs) {}}; + body{[](const std::vector< + btav_a2dp_codec_config_t>& /* codec_priorities */, + std::vector<btav_a2dp_codec_info_t>* /* supported_codecs */) {}}; void operator()(const std::vector<btav_a2dp_codec_config_t>& codec_priorities, std::vector<btav_a2dp_codec_info_t>* supported_codecs) { body(codec_priorities, supported_codecs); @@ -314,7 +322,7 @@ extern struct bta_av_co_init bta_av_co_init; struct bta_av_co_is_supported_codec { static bool return_value; std::function<bool(btav_a2dp_codec_index_t codec_index)> body{ - [](btav_a2dp_codec_index_t codec_index) { return return_value; }}; + [](btav_a2dp_codec_index_t /* codec_index */) { return return_value; }}; bool operator()(btav_a2dp_codec_index_t codec_index) { return body(codec_index); }; @@ -327,7 +335,7 @@ extern struct bta_av_co_is_supported_codec bta_av_co_is_supported_codec; struct bta_av_co_set_active_peer { static bool return_value; std::function<bool(const RawAddress& peer_address)> body{ - [](const RawAddress& peer_address) { return return_value; }}; + [](const RawAddress& /* peer_address */) { return return_value; }}; bool operator()(const RawAddress& peer_address) { return body(peer_address); }; @@ -340,7 +348,7 @@ extern struct bta_av_co_set_active_peer bta_av_co_set_active_peer; struct bta_av_co_set_codec_audio_config { static bool return_value; std::function<bool(const btav_a2dp_codec_config_t& codec_audio_config)> body{ - [](const btav_a2dp_codec_config_t& codec_audio_config) { + [](const btav_a2dp_codec_config_t& /* codec_audio_config */) { return return_value; }}; bool operator()(const btav_a2dp_codec_config_t& codec_audio_config) { @@ -357,9 +365,9 @@ struct bta_av_co_set_codec_user_config { std::function<bool(const RawAddress& peer_address, const btav_a2dp_codec_config_t& codec_user_config, bool* p_restart_output)> - body{[](const RawAddress& peer_address, - const btav_a2dp_codec_config_t& codec_user_config, - bool* p_restart_output) { return return_value; }}; + body{[](const RawAddress& /* peer_address */, + const btav_a2dp_codec_config_t& /* codec_user_config */, + bool* /* p_restart_output */) { return return_value; }}; bool operator()(const RawAddress& peer_address, const btav_a2dp_codec_config_t& codec_user_config, bool* p_restart_output) { @@ -384,7 +392,7 @@ extern struct bta_av_get_a2dp_current_codec bta_av_get_a2dp_current_codec; struct bta_av_get_a2dp_peer_current_codec { static A2dpCodecConfig* return_value; std::function<A2dpCodecConfig*(const RawAddress& peer_address)> body{ - [](const RawAddress& peer_address) { return return_value; }}; + [](const RawAddress& /* peer_address */) { return return_value; }}; A2dpCodecConfig* operator()(const RawAddress& peer_address) { return body(peer_address); }; @@ -396,7 +404,7 @@ extern struct bta_av_get_a2dp_peer_current_codec // Params: int fd // Return: void struct btif_a2dp_codec_debug_dump { - std::function<void(int fd)> body{[](int fd) {}}; + std::function<void(int fd)> body{[](int /* fd */) {}}; void operator()(int fd) { body(fd); }; }; extern struct btif_a2dp_codec_debug_dump btif_a2dp_codec_debug_dump; 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 0437f45bee..d7ccf69a36 100644 --- a/system/test/mock/mock_btif_co_bta_dm_co.cc +++ b/system/test/mock/mock_btif_co_bta_dm_co.cc @@ -29,7 +29,8 @@ tBTE_APPL_CFG bte_appl_cfg = { 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) { +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 35c20aeb39..19ef1d38a2 100644 --- a/system/test/mock/mock_btif_co_bta_hh_co.cc +++ b/system/test/mock/mock_btif_co_bta_hh_co.cc @@ -27,47 +27,52 @@ #include "test/common/mock_functions.h" #include "types/raw_address.h" -int bta_hh_co_write(int fd, uint8_t* rpt, uint16_t len) { +int bta_hh_co_write(int /* fd */, uint8_t* /* rpt */, uint16_t /* len */) { inc_func_call_count(__func__); return 0; } -tBTA_HH_RPT_CACHE_ENTRY* bta_hh_le_co_cache_load(const RawAddress& remote_bda, - uint8_t* p_num_rpt, - uint8_t app_id) { +tBTA_HH_RPT_CACHE_ENTRY* bta_hh_le_co_cache_load( + const RawAddress& /* remote_bda */, uint8_t* /* p_num_rpt */, + uint8_t /* app_id */) { inc_func_call_count(__func__); return nullptr; } -void bta_hh_co_close(btif_hh_device_t* p_dev) { inc_func_call_count(__func__); } -void bta_hh_co_data(uint8_t dev_handle, uint8_t* p_rpt, uint16_t len, - tBTA_HH_PROTO_MODE mode, uint8_t sub_class, - uint8_t ctry_code, const RawAddress& peer_addr, - uint8_t app_id) { +void bta_hh_co_close(btif_hh_device_t* /* p_dev */) { inc_func_call_count(__func__); } -void bta_hh_co_get_rpt_rsp(uint8_t dev_handle, uint8_t status, - const uint8_t* p_rpt, uint16_t len) { +void bta_hh_co_data(uint8_t /* dev_handle */, uint8_t* /* p_rpt */, + uint16_t /* len */, tBTA_HH_PROTO_MODE /* mode */, + uint8_t /* sub_class */, uint8_t /* ctry_code */, + const RawAddress& /* peer_addr */, uint8_t /* app_id */) { inc_func_call_count(__func__); } -bool bta_hh_co_open(uint8_t dev_handle, uint8_t sub_class, - tBTA_HH_ATTR_MASK attr_mask, uint8_t app_id) { +void bta_hh_co_get_rpt_rsp(uint8_t /* dev_handle */, uint8_t /* status */, + const uint8_t* /* p_rpt */, uint16_t /* len */) { + inc_func_call_count(__func__); +} +bool bta_hh_co_open(uint8_t /* dev_handle */, uint8_t /* sub_class */, + tBTA_HH_ATTR_MASK /* attr_mask */, uint8_t /* app_id */) { inc_func_call_count(__func__); return true; } -void bta_hh_co_send_hid_info(btif_hh_device_t* p_dev, const char* dev_name, - uint16_t vendor_id, uint16_t product_id, - uint16_t version, uint8_t ctry_code, int dscp_len, - uint8_t* p_dscp) { +void bta_hh_co_send_hid_info(btif_hh_device_t* /* p_dev */, + const char* /* dev_name */, + uint16_t /* vendor_id */, + uint16_t /* product_id */, uint16_t /* version */, + uint8_t /* ctry_code */, int /* dscp_len */, + uint8_t* /* p_dscp */) { inc_func_call_count(__func__); } -void bta_hh_co_set_rpt_rsp(uint8_t dev_handle, uint8_t status) { +void bta_hh_co_set_rpt_rsp(uint8_t /* dev_handle */, uint8_t /* status */) { inc_func_call_count(__func__); } -void bta_hh_le_co_reset_rpt_cache(const RawAddress& remote_bda, - uint8_t app_id) { +void bta_hh_le_co_reset_rpt_cache(const RawAddress& /* remote_bda */, + uint8_t /* app_id */) { inc_func_call_count(__func__); } -void bta_hh_le_co_rpt_info(const RawAddress& remote_bda, - tBTA_HH_RPT_CACHE_ENTRY* p_entry, uint8_t app_id) { +void bta_hh_le_co_rpt_info(const RawAddress& /* remote_bda */, + tBTA_HH_RPT_CACHE_ENTRY* /* p_entry */, + uint8_t /* app_id */) { inc_func_call_count(__func__); } -void uhid_set_non_blocking(int fd) { inc_func_call_count(__func__); } +void uhid_set_non_blocking(int /* fd */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_btif_config.h b/system/test/mock/mock_btif_config.h index 78c1b21db8..68466fa62c 100644 --- a/system/test/mock/mock_btif_config.h +++ b/system/test/mock/mock_btif_config.h @@ -42,7 +42,9 @@ namespace btif_config { // Returns: bool struct btif_get_device_clockoffset { std::function<bool(const RawAddress& bda, int* p_clock_offset)> body{ - [](const RawAddress& bda, int* p_clock_offset) { return false; }}; + [](const RawAddress& /* bda */, int* /* p_clock_offset */) { + return false; + }}; bool operator()(const RawAddress& bda, int* p_clock_offset) { return body(bda, p_clock_offset); }; @@ -52,7 +54,9 @@ struct btif_get_device_clockoffset { // Returns: bool struct btif_set_device_clockoffset { std::function<bool(const RawAddress& bda, int clock_offset)> body{ - [](const RawAddress& bda, int clock_offset) { return false; }}; + [](const RawAddress& /* bda */, int /* clock_offset */) { + return false; + }}; bool operator()(const RawAddress& bda, int clock_offset) { return body(bda, clock_offset); }; @@ -62,7 +66,9 @@ struct btif_set_device_clockoffset { // Returns: bool struct btif_config_exist { std::function<bool(const std::string& section, const std::string& key)> body{ - [](const std::string& section, const std::string& key) { return false; }}; + [](const std::string& /* section */, const std::string& /* key */) { + return false; + }}; bool operator()(const std::string& section, const std::string& key) { return body(section, key); }; @@ -74,9 +80,8 @@ extern struct btif_config_exist btif_config_exist; struct btif_config_get_int { std::function<bool(const std::string& section, const std::string& key, int* value)> - body{[](const std::string& section, const std::string& key, int* value) { - return false; - }}; + body{[](const std::string& /* section */, const std::string& /* key */, + int* /* value */) { return false; }}; bool operator()(const std::string& section, const std::string& key, int* value) { return body(section, key, value); @@ -89,9 +94,8 @@ extern struct btif_config_get_int btif_config_get_int; struct btif_config_set_int { std::function<bool(const std::string& section, const std::string& key, int value)> - body{[](const std::string& section, const std::string& key, int value) { - return false; - }}; + body{[](const std::string& /* section */, const std::string& /* key */, + int /* value */) { return false; }}; bool operator()(const std::string& section, const std::string& key, int value) { return body(section, key, value); @@ -104,8 +108,8 @@ extern struct btif_config_set_int btif_config_set_int; struct btif_config_get_uint64 { std::function<bool(const std::string& section, const std::string& key, uint64_t* value)> - body{[](const std::string& section, const std::string& key, - uint64_t* value) { return false; }}; + body{[](const std::string& /* section */, const std::string& /* key */, + uint64_t* /* value */) { return false; }}; bool operator()(const std::string& section, const std::string& key, uint64_t* value) { return body(section, key, value); @@ -118,8 +122,8 @@ extern struct btif_config_get_uint64 btif_config_get_uint64; struct btif_config_set_uint64 { std::function<bool(const std::string& section, const std::string& key, uint64_t value)> - body{[](const std::string& section, const std::string& key, - uint64_t value) { return false; }}; + body{[](const std::string& /* section */, const std::string& /* key */, + uint64_t /* value */) { return false; }}; bool operator()(const std::string& section, const std::string& key, uint64_t value) { return body(section, key, value); @@ -132,8 +136,8 @@ extern struct btif_config_set_uint64 btif_config_set_uint64; struct btif_config_get_str { std::function<bool(const std::string& section, const std::string& key, char* value, int* size_bytes)> - body{[](const std::string& section, const std::string& key, char* value, - int* size_bytes) { return false; }}; + body{[](const std::string& /* section */, const std::string& /* key */, + char* /* value */, int* /* size_bytes */) { return false; }}; bool operator()(const std::string& section, const std::string& key, char* value, int* size_bytes) { return body(section, key, value, size_bytes); @@ -146,8 +150,8 @@ extern struct btif_config_get_str btif_config_get_str; struct btif_config_set_str { std::function<bool(const std::string& section, const std::string& key, const std::string& value)> - body{[](const std::string& section, const std::string& key, - const std::string& value) { return false; }}; + body{[](const std::string& /* section */, const std::string& /* key */, + const std::string& /* value */) { return false; }}; bool operator()(const std::string& section, const std::string& key, const std::string& value) { return body(section, key, value); @@ -160,8 +164,8 @@ extern struct btif_config_set_str btif_config_set_str; struct btif_config_get_bin { std::function<bool(const std::string& section, const std::string& key, uint8_t* value, size_t* length)> - body{[](const std::string& section, const std::string& key, - uint8_t* value, size_t* length) { return false; }}; + body{[](const std::string& /* section */, const std::string& /* key */, + uint8_t* /* value */, size_t* /* length */) { return false; }}; bool operator()(const std::string& section, const std::string& key, uint8_t* value, size_t* length) { return body(section, key, value, length); @@ -173,8 +177,9 @@ extern struct btif_config_get_bin btif_config_get_bin; // Returns: size_t struct btif_config_get_bin_length { std::function<size_t(const std::string& section, const std::string& key)> - body{ - [](const std::string& section, const std::string& key) { return 0; }}; + body{[](const std::string& /* section */, const std::string& /* key */) { + return 0; + }}; size_t operator()(const std::string& section, const std::string& key) { return body(section, key); }; @@ -186,8 +191,9 @@ extern struct btif_config_get_bin_length btif_config_get_bin_length; struct btif_config_set_bin { std::function<bool(const std::string& section, const std::string& key, const uint8_t* value, size_t length)> - body{[](const std::string& section, const std::string& key, - const uint8_t* value, size_t length) { return false; }}; + body{[](const std::string& /* section */, const std::string& /* key */, + const uint8_t* /* value */, + size_t /* length */) { return false; }}; bool operator()(const std::string& section, const std::string& key, const uint8_t* value, size_t length) { return body(section, key, value, length); @@ -209,7 +215,9 @@ extern struct btif_config_get_paired_devices btif_config_get_paired_devices; // Returns: bool struct btif_config_remove { std::function<bool(const std::string& section, const std::string& key)> body{ - [](const std::string& section, const std::string& key) { return false; }}; + [](const std::string& /* section */, const std::string& /* key */) { + return false; + }}; bool operator()(const std::string& section, const std::string& key) { return body(section, key); }; @@ -220,10 +228,8 @@ extern struct btif_config_remove btif_config_remove; // Returns: void struct btif_config_remove_device { std::function<void(const std::string& section)> body{ - [](const std::string& section) { return; }}; - void operator()(const std::string& section) { - return; - }; + [](const std::string& /* section */) { return; }}; + void operator()(const std::string& /* section */) { return; }; }; extern struct btif_config_remove_device btif_config_remove_device; // Name: btif_config_clear @@ -238,7 +244,7 @@ extern struct btif_config_clear btif_config_clear; // Params: int fd // Returns: void struct btif_debug_config_dump { - std::function<void(int fd)> body{[](int fd) {}}; + std::function<void(int fd)> body{[](int /* fd */) {}}; void operator()(int fd) { body(fd); }; }; extern struct btif_debug_config_dump btif_debug_config_dump; diff --git a/system/test/mock/mock_btif_core.cc b/system/test/mock/mock_btif_core.cc index bb625e35ae..7c90eab5ef 100644 --- a/system/test/mock/mock_btif_core.cc +++ b/system/test/mock/mock_btif_core.cc @@ -26,7 +26,6 @@ #include "bta/include/bta_api.h" #include "btif/include/btif_common.h" #include "include/hardware/bluetooth.h" -#include "test/common/jni_thread.h" #include "test/common/mock_functions.h" #include "types/raw_address.h" @@ -34,11 +33,7 @@ bool btif_is_dut_mode() { inc_func_call_count(__func__); return false; } -bool is_on_jni_thread() { - inc_func_call_count(__func__); - return false; -} -bt_property_t* property_deep_copy(const bt_property_t* prop) { +bt_property_t* property_deep_copy(const bt_property_t* /* prop */) { inc_func_call_count(__func__); return nullptr; } @@ -50,25 +45,9 @@ bt_status_t btif_init_bluetooth() { inc_func_call_count(__func__); return BT_STATUS_SUCCESS; } -bt_status_t btif_set_dynamic_audio_buffer_size(int codec, int size) { - inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; -} -bt_status_t btif_transfer_context(tBTIF_CBACK* p_cback, uint16_t event, - char* p_params, int param_len, - tBTIF_COPY_CBACK* p_copy_cback) { - inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; -} -bt_status_t do_in_jni_thread(base::OnceClosure task) { +bt_status_t btif_set_dynamic_audio_buffer_size(int /* codec */, + int /* size */) { inc_func_call_count(__func__); - 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; } int btif_is_enabled(void) { @@ -79,41 +58,47 @@ tBTA_SERVICE_MASK btif_get_enabled_services_mask(void) { inc_func_call_count(__func__); return 0; } -void btif_adapter_properties_evt(bt_status_t status, uint32_t num_props, - bt_property_t* p_props) { +void btif_adapter_properties_evt(bt_status_t /* status */, + uint32_t /* num_props */, + bt_property_t* /* p_props */) { + inc_func_call_count(__func__); +} +void btif_disable_service(tBTA_SERVICE_ID /* service_id */) { inc_func_call_count(__func__); } -void btif_disable_service(tBTA_SERVICE_ID service_id) { +void btif_dut_mode_configure(uint8_t /* enable */) { inc_func_call_count(__func__); } -void btif_dut_mode_configure(uint8_t enable) { inc_func_call_count(__func__); } -void btif_dut_mode_send(uint16_t opcode, uint8_t* buf, uint8_t len) { +void btif_dut_mode_send(uint16_t /* opcode */, uint8_t* /* buf */, + uint8_t /* len */) { inc_func_call_count(__func__); } void btif_enable_bluetooth_evt() { inc_func_call_count(__func__); } -void btif_enable_service(tBTA_SERVICE_ID service_id) { +void btif_enable_service(tBTA_SERVICE_ID /* service_id */) { inc_func_call_count(__func__); } void btif_get_adapter_properties(void) { inc_func_call_count(__func__); } -void btif_get_adapter_property(bt_property_type_t type) { +void btif_get_adapter_property(bt_property_type_t /* type */) { inc_func_call_count(__func__); } -void btif_get_remote_device_properties(RawAddress remote_addr) { +void btif_get_remote_device_properties(RawAddress /* remote_addr */) { inc_func_call_count(__func__); } -void btif_get_remote_device_property(RawAddress remote_addr, - bt_property_type_t type) { +void btif_get_remote_device_property(RawAddress /* remote_addr */, + bt_property_type_t /* type */) { inc_func_call_count(__func__); } void btif_init_ok() { inc_func_call_count(__func__); } -void btif_remote_properties_evt(bt_status_t status, RawAddress* remote_addr, - uint32_t num_props, bt_property_t* p_props) { +void btif_remote_properties_evt(bt_status_t /* status */, + RawAddress* /* remote_addr */, + uint32_t /* num_props */, + bt_property_t* /* p_props */) { inc_func_call_count(__func__); } -void btif_set_adapter_property(bt_property_t* property) { +void btif_set_adapter_property(bt_property_t* /* property */) { inc_func_call_count(__func__); } -void btif_set_remote_device_property(RawAddress* remote_addr, - bt_property_t* property) { +void btif_set_remote_device_property(RawAddress* /* remote_addr */, + bt_property_t* /* property */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_btif_debug_conn.cc b/system/test/mock/mock_btif_debug_conn.cc index 1427ffd3d7..666e8a813a 100644 --- a/system/test/mock/mock_btif_debug_conn.cc +++ b/system/test/mock/mock_btif_debug_conn.cc @@ -24,9 +24,9 @@ #include "test/common/mock_functions.h" #include "types/raw_address.h" -void btif_debug_conn_dump(int fd) { inc_func_call_count(__func__); } -void btif_debug_conn_state(const RawAddress& bda, - const btif_debug_conn_state_t state, - const tGATT_DISCONN_REASON disconnect_reason) { +void btif_debug_conn_dump(int /* fd */) { inc_func_call_count(__func__); } +void btif_debug_conn_state(const RawAddress& /* bda */, + const btif_debug_conn_state_t /* state */, + const tGATT_DISCONN_REASON /* disconnect_reason */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_btif_dm.cc b/system/test/mock/mock_btif_dm.cc index 0d35351269..26bca649db 100644 --- a/system/test/mock/mock_btif_dm.cc +++ b/system/test/mock/mock_btif_dm.cc @@ -36,137 +36,147 @@ bool btif_dm_pairing_is_busy() { inc_func_call_count(__func__); return false; } -bool check_cod(const RawAddress* remote_bdaddr, uint32_t cod) { +bool check_cod(const RawAddress* /* remote_bdaddr */, uint32_t /* cod */) { inc_func_call_count(__func__); return false; } -bool check_cod_hid(const RawAddress* remote_bdaddr) { +bool check_cod_hid(const RawAddress* /* remote_bdaddr */) { inc_func_call_count(__func__); return false; } -bool check_cod_hid(const RawAddress& remote_bdaddr) { +bool check_cod_hid(const RawAddress& /* remote_bdaddr */) { inc_func_call_count(__func__); return false; } -bool is_device_le_audio_capable(const RawAddress bd_addr) { +bool is_device_le_audio_capable(const RawAddress /* bd_addr */) { inc_func_call_count(__func__); return false; } -uint16_t btif_dm_get_connection_state(const RawAddress& bd_addr) { +uint16_t btif_dm_get_connection_state(const RawAddress& /* bd_addr */) { inc_func_call_count(__func__); return 0; } void BTIF_dm_disable() { inc_func_call_count(__func__); } void BTIF_dm_enable() { inc_func_call_count(__func__); } -void BTIF_dm_on_hw_error() { inc_func_call_count(__func__); } -void BTIF_dm_report_inquiry_status_change(tBTM_INQUIRY_STATE state) { +void BTIF_dm_report_inquiry_status_change(tBTM_INQUIRY_STATE /* state */) { inc_func_call_count(__func__); } -void btif_dm_sec_evt(tBTA_DM_SEC_EVT event, tBTA_DM_SEC* p_data) { +void btif_dm_sec_evt(tBTA_DM_SEC_EVT /* event */, tBTA_DM_SEC* /* p_data */) { + inc_func_call_count(__func__); +} +void btif_ble_receiver_test(uint8_t /* rx_freq */) { inc_func_call_count(__func__); } -void btif_ble_receiver_test(uint8_t rx_freq) { inc_func_call_count(__func__); } void btif_ble_test_end() { inc_func_call_count(__func__); } -void btif_ble_transmitter_test(uint8_t tx_freq, uint8_t test_data_len, - uint8_t packet_payload) { +void btif_ble_transmitter_test(uint8_t /* tx_freq */, + uint8_t /* test_data_len */, + uint8_t /* packet_payload */) { 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) { +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) { +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 */, int /* transport */) { inc_func_call_count(__func__); } -void btif_dm_create_bond_le(const RawAddress bd_addr, - tBLE_ADDR_TYPE addr_type) { +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, - const bt_oob_data_t p192_data, - const bt_oob_data_t p256_data) { +void btif_dm_create_bond_out_of_band(const RawAddress /* bd_addr */, + int /* transport */, + const bt_oob_data_t /* p192_data */, + const bt_oob_data_t /* p256_data */) { inc_func_call_count(__func__); } -void btif_dm_enable_service(tBTA_SERVICE_ID service_id, bool enable) { +void btif_dm_enable_service(tBTA_SERVICE_ID /* service_id */, + bool /* enable */) { inc_func_call_count(__func__); } -void btif_dm_get_ble_local_keys(tBTA_DM_BLE_LOCAL_KEY_MASK* p_key_mask, - Octet16* p_er, - tBTA_BLE_LOCAL_ID_KEYS* p_id_keys) { +void btif_dm_get_ble_local_keys(tBTA_DM_BLE_LOCAL_KEY_MASK* /* p_key_mask */, + Octet16* /* p_er */, + 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 */, + const int /* transport */) { inc_func_call_count(__func__); } -void btif_dm_hh_open_failed(RawAddress* bdaddr) { +void btif_dm_hh_open_failed(RawAddress* /* bdaddr */) { inc_func_call_count(__func__); } -void btif_dm_init(uid_set_t* set) { inc_func_call_count(__func__); } -void btif_dm_get_local_class_of_device(DEV_CLASS device_class) { +void btif_dm_init(uid_set_t* /* set */) { inc_func_call_count(__func__); } +void btif_dm_get_local_class_of_device(DEV_CLASS /* device_class */) { inc_func_call_count(__func__); } void btif_dm_load_ble_local_keys(void) { inc_func_call_count(__func__); } void btif_dm_on_disable() { inc_func_call_count(__func__); } -void btif_dm_pin_reply(const RawAddress bd_addr, uint8_t accept, - uint8_t pin_len, bt_pin_code_t pin_code) { +void btif_dm_pin_reply(const RawAddress /* bd_addr */, uint8_t /* accept */, + uint8_t /* pin_len */, bt_pin_code_t /* pin_code */) { inc_func_call_count(__func__); } -void btif_dm_proc_io_req(tBTM_AUTH_REQ* p_auth_req, bool is_orig) { +void btif_dm_proc_io_req(tBTM_AUTH_REQ* /* p_auth_req */, bool /* is_orig */) { inc_func_call_count(__func__); } -void btif_dm_proc_io_rsp(const RawAddress& bd_addr, tBTM_IO_CAP io_cap, - tBTM_OOB_DATA oob_data, tBTM_AUTH_REQ auth_req) { +void btif_dm_proc_io_rsp(const RawAddress& /* bd_addr */, + tBTM_IO_CAP /* io_cap */, tBTM_OOB_DATA /* oob_data */, + tBTM_AUTH_REQ /* auth_req */) { 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) { +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) { +void btif_dm_set_oob_for_io_req(tBTM_OOB_DATA* /* p_has_oob_data */) { inc_func_call_count(__func__); } -void btif_dm_set_oob_for_le_io_req(const RawAddress& bd_addr, - tBTM_OOB_DATA* p_has_oob_data, - tBTM_LE_AUTH_REQ* p_auth_req) { +void btif_dm_set_oob_for_le_io_req(const RawAddress& /* bd_addr */, + tBTM_OOB_DATA* /* p_has_oob_data */, + tBTM_LE_AUTH_REQ* /* p_auth_req */) { inc_func_call_count(__func__); } -void btif_dm_ssp_reply(const RawAddress bd_addr, bt_ssp_variant_t variant, - uint8_t accept) { +void btif_dm_ssp_reply(const RawAddress /* bd_addr */, + bt_ssp_variant_t /* variant */, uint8_t /* accept */) { inc_func_call_count(__func__); } void btif_dm_start_discovery(void) { inc_func_call_count(__func__); } -void btif_dm_update_ble_remote_properties(const RawAddress& bd_addr, - BD_NAME bd_name, DEV_CLASS dev_class, - tBT_DEVICE_TYPE dev_type) { +void btif_dm_update_ble_remote_properties(const RawAddress& /* bd_addr */, + BD_NAME /* bd_name */, + DEV_CLASS /* dev_class */, + tBT_DEVICE_TYPE /* dev_type */) { inc_func_call_count(__func__); } -bool btif_dm_get_smp_config(tBTE_APPL_CFG* p_cfg) { +bool btif_dm_get_smp_config(tBTE_APPL_CFG* /* p_cfg */) { inc_func_call_count(__func__); return true; } -bool btif_dm_proc_rmt_oob(const RawAddress& bd_addr, Octet16* p_c, - Octet16* p_r) { +bool btif_dm_proc_rmt_oob(const RawAddress& /* bd_addr */, Octet16* /* p_c */, + Octet16* /* p_r */) { inc_func_call_count(__func__); return false; } -void btif_dm_proc_loc_oob(tBT_TRANSPORT transport, bool is_valid, - const Octet16& c, const Octet16& r) { +void btif_dm_proc_loc_oob(tBT_TRANSPORT /* transport */, bool /* is_valid */, + const Octet16& /* c */, const Octet16& /* r */) { inc_func_call_count(__func__); } -bool btif_get_device_type(const RawAddress& bda, int* p_device_type) { +bool btif_get_device_type(const RawAddress& /* bda */, + int* /* p_device_type */) { inc_func_call_count(__func__); return false; } -bool btif_get_address_type(const RawAddress& bda, tBLE_ADDR_TYPE* p_addr_type) { +bool btif_get_address_type(const RawAddress& /* bda */, + tBLE_ADDR_TYPE* /* p_addr_type */) { inc_func_call_count(__func__); return false; } diff --git a/system/test/mock/mock_btif_hf.cc b/system/test/mock/mock_btif_hf.cc index 1bc7efbe0a..e49f8f09fc 100644 --- a/system/test/mock/mock_btif_hf.cc +++ b/system/test/mock/mock_btif_hf.cc @@ -23,8 +23,6 @@ // Mock include file to share data between tests and mock #include "test/mock/mock_btif_hf.h" -#include <cstdint> - #include "test/common/mock_functions.h" // Original usings diff --git a/system/test/mock/mock_btif_hf.h b/system/test/mock/mock_btif_hf.h index 1921f42705..92c8bff07b 100644 --- a/system/test/mock/mock_btif_hf.h +++ b/system/test/mock/mock_btif_hf.h @@ -22,7 +22,6 @@ * mockcify.pl ver 0.7.0 */ -#include <cstdint> #include <functional> #include "include/hardware/bluetooth_headset_interface.h" @@ -59,4 +58,4 @@ extern struct GetInterface GetInterface; } // namespace mock } // namespace test -// END mockcify generation
\ No newline at end of file +// END mockcify generation diff --git a/system/test/mock/mock_btif_profile_queue.h b/system/test/mock/mock_btif_profile_queue.h index 7576690908..fd1635dcb5 100644 --- a/system/test/mock/mock_btif_profile_queue.h +++ b/system/test/mock/mock_btif_profile_queue.h @@ -51,7 +51,7 @@ extern struct btif_queue_advance btif_queue_advance; // Params: uint16_t uuid // Return: void struct btif_queue_cleanup { - std::function<void(uint16_t uuid)> body{[](uint16_t uuid) {}}; + std::function<void(uint16_t uuid)> body{[](uint16_t /* uuid */) {}}; void operator()(uint16_t uuid) { body(uuid); }; }; extern struct btif_queue_cleanup btif_queue_cleanup; @@ -63,8 +63,8 @@ struct btif_queue_connect { static bt_status_t return_value; std::function<bt_status_t(uint16_t uuid, const RawAddress* bda, btif_connect_cb_t connect_cb)> - body{[](uint16_t uuid, const RawAddress* bda, - btif_connect_cb_t connect_cb) { return return_value; }}; + body{[](uint16_t /* uuid */, const RawAddress* /* bda */, + btif_connect_cb_t /* connect_cb */) { return return_value; }}; bt_status_t operator()(uint16_t uuid, const RawAddress* bda, btif_connect_cb_t connect_cb) { return body(uuid, bda, connect_cb); diff --git a/system/test/mock/mock_btif_profile_storage.cc b/system/test/mock/mock_btif_profile_storage.cc new file mode 100644 index 0000000000..1390f39a23 --- /dev/null +++ b/system/test/mock/mock_btif_profile_storage.cc @@ -0,0 +1,341 @@ +/* + * 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. + */ +/* + * Generated mock file from original source file + * Functions generated:40 + * + * mockcify.pl ver 0.7.0 + */ + +// Mock include file to share data between tests and mock +#include "test/mock/mock_btif_profile_storage.h" + +#include <cstdint> + +#include "test/common/mock_functions.h" + +// Original usings +using bluetooth::Uuid; + +// Mocked internal structures, if any + +namespace test { +namespace mock { +namespace btif_profile_storage { + +// Function state capture and return values, if needed +struct btif_storage_add_groups btif_storage_add_groups; +struct btif_storage_add_hearing_aid btif_storage_add_hearing_aid; +struct btif_storage_add_hid_device_info btif_storage_add_hid_device_info; +struct btif_storage_add_leaudio_has_device btif_storage_add_leaudio_has_device; +struct btif_storage_get_hearing_aid_prop btif_storage_get_hearing_aid_prop; +struct btif_storage_get_le_hid_devices btif_storage_get_le_hid_devices; +struct btif_storage_get_leaudio_has_features + btif_storage_get_leaudio_has_features; +struct btif_storage_get_leaudio_has_presets + btif_storage_get_leaudio_has_presets; +struct btif_storage_get_wake_capable_classic_hid_devices + btif_storage_get_wake_capable_classic_hid_devices; +struct btif_storage_is_pce_version_102 btif_storage_is_pce_version_102; +struct btif_storage_leaudio_clear_service_data + btif_storage_leaudio_clear_service_data; +struct btif_storage_leaudio_update_ase_bin btif_storage_leaudio_update_ase_bin; +struct btif_storage_leaudio_update_handles_bin + btif_storage_leaudio_update_handles_bin; +struct btif_storage_leaudio_update_pacs_bin + btif_storage_leaudio_update_pacs_bin; +struct btif_storage_load_bonded_csis_devices + btif_storage_load_bonded_csis_devices; +struct btif_storage_load_bonded_groups btif_storage_load_bonded_groups; +struct btif_storage_load_bonded_hearing_aids + btif_storage_load_bonded_hearing_aids; +struct btif_storage_load_bonded_hid_info btif_storage_load_bonded_hid_info; +struct btif_storage_load_bonded_leaudio btif_storage_load_bonded_leaudio; +struct btif_storage_load_bonded_leaudio_has_devices + btif_storage_load_bonded_leaudio_has_devices; +struct btif_storage_load_bonded_volume_control_devices + btif_storage_load_bonded_volume_control_devices; +struct btif_storage_load_hidd btif_storage_load_hidd; +struct btif_storage_remove_csis_device btif_storage_remove_csis_device; +struct btif_storage_remove_groups btif_storage_remove_groups; +struct btif_storage_remove_hearing_aid btif_storage_remove_hearing_aid; +struct btif_storage_remove_hid_info btif_storage_remove_hid_info; +struct btif_storage_remove_hidd btif_storage_remove_hidd; +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_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; +struct btif_storage_set_leaudio_has_features + btif_storage_set_leaudio_has_features; +struct btif_storage_set_leaudio_has_presets + btif_storage_set_leaudio_has_presets; +struct btif_storage_set_leaudio_supported_context_types + btif_storage_set_leaudio_supported_context_types; +struct btif_storage_set_pce_profile_version + btif_storage_set_pce_profile_version; +struct btif_storage_update_csis_info btif_storage_update_csis_info; + +} // namespace btif_profile_storage +} // namespace mock +} // namespace test + +// Mocked function return values, if any +namespace test { +namespace mock { +namespace btif_profile_storage { + +bt_status_t btif_storage_add_hid_device_info::return_value = BT_STATUS_SUCCESS; +bool btif_storage_get_hearing_aid_prop::return_value = false; +std::vector<std::pair<RawAddress, uint8_t>> + btif_storage_get_le_hid_devices::return_value = {}; +bool btif_storage_get_leaudio_has_features::return_value = false; +bool btif_storage_get_leaudio_has_presets::return_value = false; +std::vector<RawAddress> + btif_storage_get_wake_capable_classic_hid_devices::return_value = {}; +bool btif_storage_is_pce_version_102::return_value = false; +bt_status_t btif_storage_load_bonded_hid_info::return_value = BT_STATUS_SUCCESS; +bt_status_t btif_storage_load_hidd::return_value = BT_STATUS_SUCCESS; +bt_status_t btif_storage_remove_hid_info::return_value = BT_STATUS_SUCCESS; +bt_status_t btif_storage_remove_hidd::return_value = BT_STATUS_SUCCESS; +bt_status_t btif_storage_set_hidd::return_value = BT_STATUS_SUCCESS; + +} // namespace btif_profile_storage +} // namespace mock +} // namespace test + +// Mocked functions, if any +void btif_storage_add_groups(const RawAddress& addr) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_add_groups(addr); +} +void btif_storage_add_hearing_aid(const HearingDevice& dev_info) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_add_hearing_aid(dev_info); +} +bt_status_t btif_storage_add_hid_device_info( + RawAddress* remote_bd_addr, uint16_t attr_mask, uint8_t sub_class, + uint8_t app_id, uint16_t vendor_id, uint16_t product_id, uint16_t version, + uint8_t ctry_code, uint16_t ssr_max_latency, uint16_t ssr_min_tout, + uint16_t dl_len, uint8_t* dsc_list) { + inc_func_call_count(__func__); + return test::mock::btif_profile_storage::btif_storage_add_hid_device_info( + remote_bd_addr, attr_mask, sub_class, app_id, vendor_id, product_id, + version, ctry_code, ssr_max_latency, ssr_min_tout, dl_len, dsc_list); +} +void btif_storage_add_leaudio_has_device(const RawAddress& address, + std::vector<uint8_t> presets_bin, + uint8_t features, + uint8_t active_preset) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_add_leaudio_has_device( + address, presets_bin, features, active_preset); +} +bool btif_storage_get_hearing_aid_prop( + const RawAddress& address, uint8_t* capabilities, uint64_t* hi_sync_id, + uint16_t* render_delay, uint16_t* preparation_delay, uint16_t* codecs) { + inc_func_call_count(__func__); + return test::mock::btif_profile_storage::btif_storage_get_hearing_aid_prop( + address, capabilities, hi_sync_id, render_delay, preparation_delay, + codecs); +} +std::vector<std::pair<RawAddress, uint8_t>> btif_storage_get_le_hid_devices( + void) { + inc_func_call_count(__func__); + return test::mock::btif_profile_storage::btif_storage_get_le_hid_devices(); +} +bool btif_storage_get_leaudio_has_features(const RawAddress& address, + uint8_t& features) { + inc_func_call_count(__func__); + return test::mock::btif_profile_storage:: + btif_storage_get_leaudio_has_features(address, features); +} +bool btif_storage_get_leaudio_has_presets(const RawAddress& address, + std::vector<uint8_t>& presets_bin, + uint8_t& active_preset) { + inc_func_call_count(__func__); + return test::mock::btif_profile_storage::btif_storage_get_leaudio_has_presets( + address, presets_bin, active_preset); +} +std::vector<RawAddress> btif_storage_get_wake_capable_classic_hid_devices( + void) { + inc_func_call_count(__func__); + return test::mock::btif_profile_storage:: + btif_storage_get_wake_capable_classic_hid_devices(); +} +bool btif_storage_is_pce_version_102(const RawAddress& remote_bd_addr) { + inc_func_call_count(__func__); + return test::mock::btif_profile_storage::btif_storage_is_pce_version_102( + remote_bd_addr); +} +void btif_storage_leaudio_clear_service_data(const RawAddress& address) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_leaudio_clear_service_data( + address); +} +void btif_storage_leaudio_update_ase_bin(const RawAddress& addr) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_leaudio_update_ase_bin(addr); +} +void btif_storage_leaudio_update_handles_bin(const RawAddress& addr) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_leaudio_update_handles_bin( + addr); +} +void btif_storage_leaudio_update_pacs_bin(const RawAddress& addr) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_leaudio_update_pacs_bin(addr); +} +void btif_storage_load_bonded_csis_devices(void) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_load_bonded_csis_devices(); +} +void btif_storage_load_bonded_groups(void) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_load_bonded_groups(); +} +void btif_storage_load_bonded_hearing_aids() { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_load_bonded_hearing_aids(); +} +bt_status_t btif_storage_load_bonded_hid_info(void) { + inc_func_call_count(__func__); + return test::mock::btif_profile_storage::btif_storage_load_bonded_hid_info(); +} +void btif_storage_load_bonded_leaudio() { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_load_bonded_leaudio(); +} +void btif_storage_load_bonded_leaudio_has_devices() { + inc_func_call_count(__func__); + test::mock::btif_profile_storage:: + btif_storage_load_bonded_leaudio_has_devices(); +} +void btif_storage_load_bonded_volume_control_devices(void) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage:: + btif_storage_load_bonded_volume_control_devices(); +} +bt_status_t btif_storage_load_hidd(void) { + inc_func_call_count(__func__); + return test::mock::btif_profile_storage::btif_storage_load_hidd(); +} +void btif_storage_remove_csis_device(const RawAddress& address) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_remove_csis_device(address); +} +void btif_storage_remove_groups(const RawAddress& address) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_remove_groups(address); +} +void btif_storage_remove_hearing_aid(const RawAddress& address) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_remove_hearing_aid(address); +} +bt_status_t btif_storage_remove_hid_info(const RawAddress& remote_bd_addr) { + inc_func_call_count(__func__); + return test::mock::btif_profile_storage::btif_storage_remove_hid_info( + remote_bd_addr); +} +bt_status_t btif_storage_remove_hidd(RawAddress* remote_bd_addr) { + inc_func_call_count(__func__); + return test::mock::btif_profile_storage::btif_storage_remove_hidd( + remote_bd_addr); +} +void btif_storage_remove_leaudio(const RawAddress& address) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_remove_leaudio(address); +} +void btif_storage_remove_leaudio_has(const RawAddress& address) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_remove_leaudio_has(address); +} +void btif_storage_set_hearing_aid_acceptlist(const RawAddress& address, + bool add_to_acceptlist) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_set_hearing_aid_acceptlist( + address, add_to_acceptlist); +} +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) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_set_leaudio_audio_location( + addr, sink_location, source_location); +} +void btif_storage_set_leaudio_autoconnect(const RawAddress& addr, + bool autoconnect) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_set_leaudio_autoconnect( + addr, autoconnect); +} +void btif_storage_set_leaudio_has_acceptlist(const RawAddress& address, + bool add_to_acceptlist) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_set_leaudio_has_acceptlist( + address, add_to_acceptlist); +} +void btif_storage_set_leaudio_has_active_preset(const RawAddress& address, + uint8_t active_preset) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_set_leaudio_has_active_preset( + address, active_preset); +} +void btif_storage_set_leaudio_has_features(const RawAddress& address, + uint8_t features) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_set_leaudio_has_features( + address, features); +} +void btif_storage_set_leaudio_has_presets(const RawAddress& address, + std::vector<uint8_t> presets_bin) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_set_leaudio_has_presets( + address, presets_bin); +} +void btif_storage_set_leaudio_supported_context_types( + const RawAddress& addr, uint16_t sink_supported_context_type, + uint16_t source_supported_context_type) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage:: + btif_storage_set_leaudio_supported_context_types( + addr, sink_supported_context_type, source_supported_context_type); +} +void btif_storage_set_pce_profile_version(const RawAddress& remote_bd_addr, + uint16_t peer_pce_version) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_set_pce_profile_version( + remote_bd_addr, peer_pce_version); +} +void btif_storage_update_csis_info(const RawAddress& addr) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_update_csis_info(addr); +} +// Mocked functions complete +// END mockcify generation diff --git a/system/test/mock/mock_btif_profile_storage.h b/system/test/mock/mock_btif_profile_storage.h new file mode 100644 index 0000000000..66e61ae821 --- /dev/null +++ b/system/test/mock/mock_btif_profile_storage.h @@ -0,0 +1,574 @@ +/* + * 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. + */ +#pragma once + +/* + * Generated mock file from original source file + * Functions generated:40 + * + * mockcify.pl ver 0.7.0 + */ + +#include <cstdint> +#include <functional> + +// Original included files, if any +// NOTE: Since this is a mock file with mock definitions some number of +// include files may not be required. The include-what-you-use +// still applies, but crafting proper inclusion is out of scope +// for this effort. This compilation unit may compile as-is, or +// may need attention to prune from (or add to ) the inclusion set. +#include <alloca.h> +#include <base/logging.h> +#include <stdlib.h> + +#include <vector> + +#include "bta/include/bta_hearing_aid_api.h" +#include "types/bluetooth/uuid.h" +#include "types/raw_address.h" + +// Original usings +using bluetooth::Uuid; + +// Mocked compile conditionals, if any + +namespace test { +namespace mock { +namespace btif_profile_storage { + +// Shared state between mocked functions and tests +// Name: btif_storage_add_groups +// Params: const RawAddress& addr +// Return: void +struct btif_storage_add_groups { + std::function<void(const RawAddress& addr)> body{ + [](const RawAddress& /* addr */) {}}; + void operator()(const RawAddress& addr) { body(addr); }; +}; +extern struct btif_storage_add_groups btif_storage_add_groups; + +// Name: btif_storage_add_hearing_aid +// Params: const HearingDevice& dev_info +// Return: void +struct btif_storage_add_hearing_aid { + std::function<void(const HearingDevice& dev_info)> body{ + [](const HearingDevice& /* dev_info */) {}}; + void operator()(const HearingDevice& dev_info) { body(dev_info); }; +}; +extern struct btif_storage_add_hearing_aid btif_storage_add_hearing_aid; + +// Name: btif_storage_add_hid_device_info +// Params: RawAddress* remote_bd_addr, uint16_t attr_mask, uint8_t sub_class, +// uint8_t app_id, uint16_t vendor_id, uint16_t product_id, uint16_t version, +// uint8_t ctry_code, uint16_t ssr_max_latency, uint16_t ssr_min_tout, uint16_t +// dl_len, uint8_t* dsc_list Return: bt_status_t +struct btif_storage_add_hid_device_info { + static bt_status_t return_value; + std::function<bt_status_t( + RawAddress* remote_bd_addr, uint16_t attr_mask, uint8_t sub_class, + uint8_t app_id, uint16_t vendor_id, uint16_t product_id, uint16_t version, + uint8_t ctry_code, uint16_t ssr_max_latency, uint16_t ssr_min_tout, + uint16_t dl_len, uint8_t* dsc_list)> + body{[](RawAddress* /* remote_bd_addr */, uint16_t /* attr_mask */, + uint8_t /* sub_class */, uint8_t /* app_id */, + uint16_t /* vendor_id */, uint16_t /* product_id */, + uint16_t /* version */, uint8_t /* ctry_code */, + uint16_t /* ssr_max_latency */, uint16_t /* ssr_min_tout */, + uint16_t /* dl_len */, + uint8_t* /* dsc_list */) { return return_value; }}; + bt_status_t operator()(RawAddress* remote_bd_addr, uint16_t attr_mask, + uint8_t sub_class, uint8_t app_id, uint16_t vendor_id, + uint16_t product_id, uint16_t version, + uint8_t ctry_code, uint16_t ssr_max_latency, + uint16_t ssr_min_tout, uint16_t dl_len, + uint8_t* dsc_list) { + return body(remote_bd_addr, attr_mask, sub_class, app_id, vendor_id, + product_id, version, ctry_code, ssr_max_latency, ssr_min_tout, + dl_len, dsc_list); + }; +}; +extern struct btif_storage_add_hid_device_info btif_storage_add_hid_device_info; + +// Name: btif_storage_add_leaudio_has_device +// Params: const RawAddress& address, std::vector<uint8_t> presets_bin, uint8_t +// features, uint8_t active_preset Return: void +struct btif_storage_add_leaudio_has_device { + std::function<void(const RawAddress& address, + std::vector<uint8_t> presets_bin, uint8_t features, + uint8_t active_preset)> + body{[](const RawAddress& /* address */, + std::vector<uint8_t> /* presets_bin */, uint8_t /* features */, + uint8_t /* active_preset */) {}}; + void operator()(const RawAddress& address, std::vector<uint8_t> presets_bin, + uint8_t features, uint8_t active_preset) { + body(address, presets_bin, features, active_preset); + }; +}; +extern struct btif_storage_add_leaudio_has_device + btif_storage_add_leaudio_has_device; + +// Name: btif_storage_get_hearing_aid_prop +// Params: const RawAddress& address, uint8_t* capabilities, uint64_t* +// hi_sync_id, uint16_t* render_delay, uint16_t* preparation_delay, uint16_t* +// codecs Return: bool +struct btif_storage_get_hearing_aid_prop { + static bool return_value; + std::function<bool(const RawAddress& address, uint8_t* capabilities, + uint64_t* hi_sync_id, uint16_t* render_delay, + uint16_t* preparation_delay, uint16_t* codecs)> + body{[](const RawAddress& /* address */, uint8_t* /* capabilities */, + uint64_t* /* hi_sync_id */, uint16_t* /* render_delay */, + uint16_t* /* preparation_delay */, + uint16_t* /* codecs */) { return return_value; }}; + bool operator()(const RawAddress& address, uint8_t* capabilities, + uint64_t* hi_sync_id, uint16_t* render_delay, + uint16_t* preparation_delay, uint16_t* codecs) { + return body(address, capabilities, hi_sync_id, render_delay, + preparation_delay, codecs); + }; +}; +extern struct btif_storage_get_hearing_aid_prop + btif_storage_get_hearing_aid_prop; + +// Name: btif_storage_get_le_hid_devices +// Params: void +// Return: std::vector<std::pair<RawAddress, uint8_t>> +struct btif_storage_get_le_hid_devices { + static std::vector<std::pair<RawAddress, uint8_t>> return_value; + std::function<std::vector<std::pair<RawAddress, uint8_t>>(void)> body{ + [](void) { return return_value; }}; + std::vector<std::pair<RawAddress, uint8_t>> operator()(void) { + return body(); + }; +}; +extern struct btif_storage_get_le_hid_devices btif_storage_get_le_hid_devices; + +// Name: btif_storage_get_leaudio_has_features +// Params: const RawAddress& address, uint8_t& features +// Return: bool +struct btif_storage_get_leaudio_has_features { + static bool return_value; + std::function<bool(const RawAddress& address, uint8_t& features)> body{ + [](const RawAddress& /* address */, uint8_t& /* features */) { + return return_value; + }}; + bool operator()(const RawAddress& address, uint8_t& features) { + return body(address, features); + }; +}; +extern struct btif_storage_get_leaudio_has_features + btif_storage_get_leaudio_has_features; + +// Name: btif_storage_get_leaudio_has_presets +// Params: const RawAddress& address, std::vector<uint8_t>& presets_bin, +// uint8_t& active_preset Return: bool +struct btif_storage_get_leaudio_has_presets { + static bool return_value; + std::function<bool(const RawAddress& address, + std::vector<uint8_t>& presets_bin, uint8_t& active_preset)> + body{[](const RawAddress& /* address */, + std::vector<uint8_t>& /* presets_bin */, + uint8_t& /* active_preset */) { return return_value; }}; + bool operator()(const RawAddress& address, std::vector<uint8_t>& presets_bin, + uint8_t& active_preset) { + return body(address, presets_bin, active_preset); + }; +}; +extern struct btif_storage_get_leaudio_has_presets + btif_storage_get_leaudio_has_presets; + +// Name: btif_storage_get_wake_capable_classic_hid_devices +// Params: void +// Return: std::vector<RawAddress> +struct btif_storage_get_wake_capable_classic_hid_devices { + static std::vector<RawAddress> return_value; + std::function<std::vector<RawAddress>(void)> body{ + [](void) { return return_value; }}; + std::vector<RawAddress> operator()(void) { return body(); }; +}; +extern struct btif_storage_get_wake_capable_classic_hid_devices + btif_storage_get_wake_capable_classic_hid_devices; + +// Name: btif_storage_is_pce_version_102 +// Params: const RawAddress& remote_bd_addr +// Return: bool +struct btif_storage_is_pce_version_102 { + static bool return_value; + std::function<bool(const RawAddress& remote_bd_addr)> body{ + [](const RawAddress& /* remote_bd_addr */) { return return_value; }}; + bool operator()(const RawAddress& remote_bd_addr) { + return body(remote_bd_addr); + }; +}; +extern struct btif_storage_is_pce_version_102 btif_storage_is_pce_version_102; + +// Name: btif_storage_leaudio_clear_service_data +// Params: const RawAddress& address +// Return: void +struct btif_storage_leaudio_clear_service_data { + std::function<void(const RawAddress& address)> body{ + [](const RawAddress& /* address */) {}}; + void operator()(const RawAddress& address) { body(address); }; +}; +extern struct btif_storage_leaudio_clear_service_data + btif_storage_leaudio_clear_service_data; + +// Name: btif_storage_leaudio_update_ase_bin +// Params: const RawAddress& addr +// Return: void +struct btif_storage_leaudio_update_ase_bin { + std::function<void(const RawAddress& addr)> body{ + [](const RawAddress& /* addr */) {}}; + void operator()(const RawAddress& addr) { body(addr); }; +}; +extern struct btif_storage_leaudio_update_ase_bin + btif_storage_leaudio_update_ase_bin; + +// Name: btif_storage_leaudio_update_handles_bin +// Params: const RawAddress& addr +// Return: void +struct btif_storage_leaudio_update_handles_bin { + std::function<void(const RawAddress& addr)> body{ + [](const RawAddress& /* addr */) {}}; + void operator()(const RawAddress& addr) { body(addr); }; +}; +extern struct btif_storage_leaudio_update_handles_bin + btif_storage_leaudio_update_handles_bin; + +// Name: btif_storage_leaudio_update_pacs_bin +// Params: const RawAddress& addr +// Return: void +struct btif_storage_leaudio_update_pacs_bin { + std::function<void(const RawAddress& addr)> body{ + [](const RawAddress& /* addr */) {}}; + void operator()(const RawAddress& addr) { body(addr); }; +}; +extern struct btif_storage_leaudio_update_pacs_bin + btif_storage_leaudio_update_pacs_bin; + +// Name: btif_storage_load_bonded_csis_devices +// Params: void +// Return: void +struct btif_storage_load_bonded_csis_devices { + std::function<void(void)> body{[](void) {}}; + void operator()(void) { body(); }; +}; +extern struct btif_storage_load_bonded_csis_devices + btif_storage_load_bonded_csis_devices; + +// Name: btif_storage_load_bonded_groups +// Params: void +// Return: void +struct btif_storage_load_bonded_groups { + std::function<void(void)> body{[](void) {}}; + void operator()(void) { body(); }; +}; +extern struct btif_storage_load_bonded_groups btif_storage_load_bonded_groups; + +// Name: btif_storage_load_bonded_hearing_aids +// Params: +// Return: void +struct btif_storage_load_bonded_hearing_aids { + std::function<void()> body{[]() {}}; + void operator()() { body(); }; +}; +extern struct btif_storage_load_bonded_hearing_aids + btif_storage_load_bonded_hearing_aids; + +// Name: btif_storage_load_bonded_hid_info +// Params: void +// Return: bt_status_t +struct btif_storage_load_bonded_hid_info { + static bt_status_t return_value; + std::function<bt_status_t(void)> body{[](void) { return return_value; }}; + bt_status_t operator()(void) { return body(); }; +}; +extern struct btif_storage_load_bonded_hid_info + btif_storage_load_bonded_hid_info; + +// Name: btif_storage_load_bonded_leaudio +// Params: +// Return: void +struct btif_storage_load_bonded_leaudio { + std::function<void()> body{[]() {}}; + void operator()() { body(); }; +}; +extern struct btif_storage_load_bonded_leaudio btif_storage_load_bonded_leaudio; + +// Name: btif_storage_load_bonded_leaudio_has_devices +// Params: +// Return: void +struct btif_storage_load_bonded_leaudio_has_devices { + std::function<void()> body{[]() {}}; + void operator()() { body(); }; +}; +extern struct btif_storage_load_bonded_leaudio_has_devices + btif_storage_load_bonded_leaudio_has_devices; + +// Name: btif_storage_load_bonded_volume_control_devices +// Params: void +// Return: void +struct btif_storage_load_bonded_volume_control_devices { + std::function<void(void)> body{[](void) {}}; + void operator()(void) { body(); }; +}; +extern struct btif_storage_load_bonded_volume_control_devices + btif_storage_load_bonded_volume_control_devices; + +// Name: btif_storage_load_hidd +// Params: void +// Return: bt_status_t +struct btif_storage_load_hidd { + static bt_status_t return_value; + std::function<bt_status_t(void)> body{[](void) { return return_value; }}; + bt_status_t operator()(void) { return body(); }; +}; +extern struct btif_storage_load_hidd btif_storage_load_hidd; + +// Name: btif_storage_remove_csis_device +// Params: const RawAddress& address +// Return: void +struct btif_storage_remove_csis_device { + std::function<void(const RawAddress& address)> body{ + [](const RawAddress& /* address */) {}}; + void operator()(const RawAddress& address) { body(address); }; +}; +extern struct btif_storage_remove_csis_device btif_storage_remove_csis_device; + +// Name: btif_storage_remove_groups +// Params: const RawAddress& address +// Return: void +struct btif_storage_remove_groups { + std::function<void(const RawAddress& address)> body{ + [](const RawAddress& /* address */) {}}; + void operator()(const RawAddress& address) { body(address); }; +}; +extern struct btif_storage_remove_groups btif_storage_remove_groups; + +// Name: btif_storage_remove_hearing_aid +// Params: const RawAddress& address +// Return: void +struct btif_storage_remove_hearing_aid { + std::function<void(const RawAddress& address)> body{ + [](const RawAddress& /* address */) {}}; + void operator()(const RawAddress& address) { body(address); }; +}; +extern struct btif_storage_remove_hearing_aid btif_storage_remove_hearing_aid; + +// Name: btif_storage_remove_hid_info +// Params: const RawAddress& remote_bd_addr +// Return: bt_status_t +struct btif_storage_remove_hid_info { + static bt_status_t return_value; + std::function<bt_status_t(const RawAddress& remote_bd_addr)> body{ + [](const RawAddress& /* remote_bd_addr */) { return return_value; }}; + bt_status_t operator()(const RawAddress& remote_bd_addr) { + return body(remote_bd_addr); + }; +}; +extern struct btif_storage_remove_hid_info btif_storage_remove_hid_info; + +// Name: btif_storage_remove_hidd +// Params: RawAddress* remote_bd_addr +// Return: bt_status_t +struct btif_storage_remove_hidd { + static bt_status_t return_value; + std::function<bt_status_t(RawAddress* remote_bd_addr)> body{ + [](RawAddress* /* remote_bd_addr */) { return return_value; }}; + bt_status_t operator()(RawAddress* remote_bd_addr) { + return body(remote_bd_addr); + }; +}; +extern struct btif_storage_remove_hidd btif_storage_remove_hidd; + +// Name: btif_storage_remove_leaudio +// Params: const RawAddress& address +// Return: void +struct btif_storage_remove_leaudio { + std::function<void(const RawAddress& address)> body{ + [](const RawAddress& /* address */) {}}; + void operator()(const RawAddress& address) { body(address); }; +}; +extern struct btif_storage_remove_leaudio btif_storage_remove_leaudio; + +// Name: btif_storage_remove_leaudio_has +// Params: const RawAddress& address +// Return: void +struct btif_storage_remove_leaudio_has { + std::function<void(const RawAddress& address)> body{ + [](const RawAddress& /* address */) {}}; + void operator()(const RawAddress& address) { body(address); }; +}; +extern struct btif_storage_remove_leaudio_has btif_storage_remove_leaudio_has; + +// Name: btif_storage_set_hearing_aid_acceptlist +// Params: const RawAddress& address, bool add_to_acceptlist +// Return: void +struct btif_storage_set_hearing_aid_acceptlist { + std::function<void(const RawAddress& address, bool add_to_acceptlist)> body{ + [](const RawAddress& /* address */, bool /* add_to_acceptlist */) {}}; + void operator()(const RawAddress& address, bool add_to_acceptlist) { + body(address, add_to_acceptlist); + }; +}; +extern struct btif_storage_set_hearing_aid_acceptlist + btif_storage_set_hearing_aid_acceptlist; + +// Name: btif_storage_set_hidd +// Params: const RawAddress& remote_bd_addr +// Return: bt_status_t +struct btif_storage_set_hidd { + static bt_status_t return_value; + std::function<bt_status_t(const RawAddress& remote_bd_addr)> body{ + [](const RawAddress& /* remote_bd_addr */) { return return_value; }}; + bt_status_t operator()(const RawAddress& remote_bd_addr) { + return body(remote_bd_addr); + }; +}; +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_autoconnect +// Params: const RawAddress& addr, bool autoconnect +// Return: void +struct btif_storage_set_leaudio_autoconnect { + std::function<void(const RawAddress& addr, bool autoconnect)> body{ + [](const RawAddress& /* addr */, bool /* autoconnect */) {}}; + void operator()(const RawAddress& addr, bool autoconnect) { + body(addr, autoconnect); + }; +}; +extern struct btif_storage_set_leaudio_autoconnect + btif_storage_set_leaudio_autoconnect; + +// Name: btif_storage_set_leaudio_has_acceptlist +// Params: const RawAddress& address, bool add_to_acceptlist +// Return: void +struct btif_storage_set_leaudio_has_acceptlist { + std::function<void(const RawAddress& address, bool add_to_acceptlist)> body{ + [](const RawAddress& /* address */, bool /* add_to_acceptlist */) {}}; + void operator()(const RawAddress& address, bool add_to_acceptlist) { + body(address, add_to_acceptlist); + }; +}; +extern struct btif_storage_set_leaudio_has_acceptlist + btif_storage_set_leaudio_has_acceptlist; + +// Name: btif_storage_set_leaudio_has_active_preset +// Params: const RawAddress& address, uint8_t active_preset +// Return: void +struct btif_storage_set_leaudio_has_active_preset { + std::function<void(const RawAddress& address, uint8_t active_preset)> body{ + [](const RawAddress& /* address */, uint8_t /* active_preset */) {}}; + void operator()(const RawAddress& address, uint8_t active_preset) { + body(address, active_preset); + }; +}; +extern struct btif_storage_set_leaudio_has_active_preset + btif_storage_set_leaudio_has_active_preset; + +// Name: btif_storage_set_leaudio_has_features +// Params: const RawAddress& address, uint8_t features +// Return: void +struct btif_storage_set_leaudio_has_features { + std::function<void(const RawAddress& address, uint8_t features)> body{ + [](const RawAddress& /* address */, uint8_t /* features */) {}}; + void operator()(const RawAddress& address, uint8_t features) { + body(address, features); + }; +}; +extern struct btif_storage_set_leaudio_has_features + btif_storage_set_leaudio_has_features; + +// Name: btif_storage_set_leaudio_has_presets +// Params: const RawAddress& address, std::vector<uint8_t> presets_bin +// Return: void +struct btif_storage_set_leaudio_has_presets { + std::function<void(const RawAddress& address, + std::vector<uint8_t> presets_bin)> + body{[](const RawAddress& /* address */, + std::vector<uint8_t> /* presets_bin */) {}}; + void operator()(const RawAddress& address, std::vector<uint8_t> presets_bin) { + body(address, presets_bin); + }; +}; +extern struct btif_storage_set_leaudio_has_presets + btif_storage_set_leaudio_has_presets; + +// Name: btif_storage_set_leaudio_supported_context_types +// Params: const RawAddress& addr, uint16_t sink_supported_context_type, +// uint16_t source_supported_context_type Return: void +struct btif_storage_set_leaudio_supported_context_types { + std::function<void(const RawAddress& addr, + uint16_t sink_supported_context_type, + uint16_t source_supported_context_type)> + body{[](const RawAddress& /* addr */, + uint16_t /* sink_supported_context_type */, + uint16_t /* source_supported_context_type */) {}}; + void operator()(const RawAddress& addr, uint16_t sink_supported_context_type, + uint16_t source_supported_context_type) { + body(addr, sink_supported_context_type, source_supported_context_type); + }; +}; +extern struct btif_storage_set_leaudio_supported_context_types + btif_storage_set_leaudio_supported_context_types; + +// Name: btif_storage_set_pce_profile_version +// Params: const RawAddress& remote_bd_addr, uint16_t peer_pce_version +// Return: void +struct btif_storage_set_pce_profile_version { + std::function<void(const RawAddress& remote_bd_addr, + uint16_t peer_pce_version)> + body{[](const RawAddress& /* remote_bd_addr */, + uint16_t /* peer_pce_version */) {}}; + void operator()(const RawAddress& remote_bd_addr, uint16_t peer_pce_version) { + body(remote_bd_addr, peer_pce_version); + }; +}; +extern struct btif_storage_set_pce_profile_version + btif_storage_set_pce_profile_version; + +// Name: btif_storage_update_csis_info +// Params: const RawAddress& addr +// Return: void +struct btif_storage_update_csis_info { + std::function<void(const RawAddress& addr)> body{ + [](const RawAddress& /* addr */) {}}; + void operator()(const RawAddress& addr) { body(addr); }; +}; +extern struct btif_storage_update_csis_info btif_storage_update_csis_info; + +} // namespace btif_profile_storage +} // namespace mock +} // namespace test + +// END mockcify generation diff --git a/system/test/mock/mock_btif_sock_rfc.h b/system/test/mock/mock_btif_sock_rfc.h index be8be5dd1f..eadf438e51 100644 --- a/system/test/mock/mock_btif_sock_rfc.h +++ b/system/test/mock/mock_btif_sock_rfc.h @@ -50,7 +50,7 @@ namespace btif_sock_rfc { struct bta_co_rfc_data_incoming { static int return_value; std::function<int(uint32_t id, BT_HDR* p_buf)> body{ - [](uint32_t id, BT_HDR* p_buf) { return return_value; }}; + [](uint32_t /* id */, BT_HDR* /* p_buf */) { return return_value; }}; int operator()(uint32_t id, BT_HDR* p_buf) { return body(id, p_buf); }; }; extern struct bta_co_rfc_data_incoming bta_co_rfc_data_incoming; @@ -61,7 +61,9 @@ extern struct bta_co_rfc_data_incoming bta_co_rfc_data_incoming; struct bta_co_rfc_data_outgoing { static int return_value; std::function<int(uint32_t id, uint8_t* buf, uint16_t size)> body{ - [](uint32_t id, uint8_t* buf, uint16_t size) { return return_value; }}; + [](uint32_t /* id */, uint8_t* /* buf */, uint16_t /* size */) { + return return_value; + }}; int operator()(uint32_t id, uint8_t* buf, uint16_t size) { return body(id, buf, size); }; @@ -74,7 +76,7 @@ extern struct bta_co_rfc_data_outgoing bta_co_rfc_data_outgoing; struct bta_co_rfc_data_outgoing_size { static int return_value; std::function<int(uint32_t id, int* size)> body{ - [](uint32_t id, int* size) { return return_value; }}; + [](uint32_t /* id */, int* /* size */) { return return_value; }}; int operator()(uint32_t id, int* size) { return body(id, size); }; }; extern struct bta_co_rfc_data_outgoing_size bta_co_rfc_data_outgoing_size; @@ -95,8 +97,9 @@ 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; }}; + 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); @@ -114,9 +117,10 @@ struct btsock_rfc_control_req { uint8_t modem_signal, uint8_t break_signal, uint8_t discard_buffers, uint8_t break_signal_seq, bool fc)> - body{[](uint8_t dlci, const RawAddress& bd_addr, uint8_t modem_signal, - uint8_t break_signal, uint8_t discard_buffers, - uint8_t break_signal_seq, bool fc) { return return_value; }}; + body{[](uint8_t /* dlci */, const RawAddress& /* bd_addr */, + uint8_t /* modem_signal */, uint8_t /* break_signal */, + uint8_t /* discard_buffers */, uint8_t /* break_signal_seq */, + bool /* fc */) { return return_value; }}; bt_status_t operator()(uint8_t dlci, const RawAddress& bd_addr, uint8_t modem_signal, uint8_t break_signal, uint8_t discard_buffers, uint8_t break_signal_seq, @@ -133,7 +137,7 @@ extern struct btsock_rfc_control_req btsock_rfc_control_req; struct btsock_rfc_disconnect { static bt_status_t return_value; std::function<bt_status_t(const RawAddress* bd_addr)> body{ - [](const RawAddress* bd_addr) { return return_value; }}; + [](const RawAddress* /* bd_addr */) { return return_value; }}; bt_status_t operator()(const RawAddress* bd_addr) { return body(bd_addr); }; }; extern struct btsock_rfc_disconnect btsock_rfc_disconnect; @@ -144,7 +148,9 @@ extern struct btsock_rfc_disconnect btsock_rfc_disconnect; struct btsock_rfc_init { static bt_status_t return_value; std::function<bt_status_t(int poll_thread_handle, uid_set_t* set)> body{ - [](int poll_thread_handle, uid_set_t* set) { return return_value; }}; + [](int /* poll_thread_handle */, uid_set_t* /* set */) { + return return_value; + }}; bt_status_t operator()(int poll_thread_handle, uid_set_t* set) { return body(poll_thread_handle, set); }; @@ -158,8 +164,9 @@ 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)> - body{[](const char* service_name, const Uuid* service_uuid, int channel, - int* sock_fd, int flags, int app_uid) { return return_value; }}; + body{[](const char* /* service_name */, const Uuid* /* service_uuid */, + int /* channel */, int* /* sock_fd */, int /* flags */, + int /* app_uid */) { 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); @@ -172,7 +179,7 @@ extern struct btsock_rfc_listen btsock_rfc_listen; // Return: void struct btsock_rfc_signaled { std::function<void(int fd, int flags, uint32_t id)> body{ - [](int fd, int flags, uint32_t id) {}}; + [](int /* fd */, int /* flags */, uint32_t /* id */) {}}; void operator()(int fd, int flags, uint32_t id) { body(fd, flags, id); }; }; extern struct btsock_rfc_signaled btsock_rfc_signaled; @@ -181,4 +188,4 @@ extern struct btsock_rfc_signaled btsock_rfc_signaled; } // namespace mock } // namespace test -// END mockcify generation
\ No newline at end of file +// END mockcify generation diff --git a/system/test/mock/mock_btif_storage.cc b/system/test/mock/mock_btif_storage.cc index 2d528672f1..c52925824f 100644 --- a/system/test/mock/mock_btif_storage.cc +++ b/system/test/mock/mock_btif_storage.cc @@ -1,5 +1,5 @@ /* - * Copyright 2021 The Android Open Source Project + * 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. @@ -13,232 +13,343 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - /* * Generated mock file from original source file - * Functions generated:44 + * Functions generated:41 + * + * mockcify.pl ver 0.7.0 */ +// Mock include file to share data between tests and mock +#include "test/mock/mock_btif_storage.h" + #include <cstdint> -#include <string> -#include "bta/include/bta_hearing_aid_api.h" -#include "stack/include/bt_octets.h" -#include "stack/include/btm_sec_api_types.h" #include "test/common/mock_functions.h" -#include "types/ble_address_with_type.h" -#include "types/bluetooth/uuid.h" -#include "types/raw_address.h" -Octet16 btif_storage_get_gatt_cl_db_hash(const RawAddress& bd_addr) { +// Original usings +using bluetooth::Uuid; + +// Mocked internal structures, if any + +namespace test { +namespace mock { +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; +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; +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_local_io_caps btif_storage_get_local_io_caps; +struct btif_storage_get_num_bonded_devices btif_storage_get_num_bonded_devices; +struct btif_storage_get_remote_addr_type btif_storage_get_remote_addr_type; +struct btif_storage_get_remote_addr_type2 btif_storage_get_remote_addr_type2; +struct btif_storage_get_remote_device_property + btif_storage_get_remote_device_property; +struct btif_storage_get_remote_device_type btif_storage_get_remote_device_type; +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_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; +struct btif_storage_remove_ble_bonding_keys + btif_storage_remove_ble_bonding_keys; +struct btif_storage_remove_ble_local_keys btif_storage_remove_ble_local_keys; +struct btif_storage_remove_bonded_device btif_storage_remove_bonded_device; +struct btif_storage_remove_gatt_cl_db_hash btif_storage_remove_gatt_cl_db_hash; +struct btif_storage_remove_gatt_cl_supp_feat + btif_storage_remove_gatt_cl_supp_feat; +struct btif_storage_set_adapter_property btif_storage_set_adapter_property; +struct btif_storage_set_gatt_cl_db_hash btif_storage_set_gatt_cl_db_hash; +struct btif_storage_set_gatt_cl_supp_feat btif_storage_set_gatt_cl_supp_feat; +struct btif_storage_set_gatt_sr_supp_feat btif_storage_set_gatt_sr_supp_feat; +struct btif_storage_set_remote_addr_type btif_storage_set_remote_addr_type; +struct btif_storage_set_remote_addr_type2 btif_storage_set_remote_addr_type2; +struct btif_storage_set_remote_device_property + btif_storage_set_remote_device_property; +struct btif_storage_set_remote_device_type btif_storage_set_remote_device_type; + +} // namespace btif_storage +} // namespace mock +} // namespace test + +// Mocked function return values, if any +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; +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; +Octet16 btif_storage_get_gatt_cl_db_hash::return_value = {}; +uint8_t btif_storage_get_gatt_cl_supp_feat::return_value = 0; +tBTM_IO_CAP btif_storage_get_local_io_caps::return_value = 0; +int btif_storage_get_num_bonded_devices::return_value = 0; +bt_status_t btif_storage_get_remote_addr_type::return_value = BT_STATUS_SUCCESS; +bool btif_storage_get_remote_addr_type2::return_value = false; +bt_status_t btif_storage_get_remote_device_property::return_value = + BT_STATUS_SUCCESS; +bool btif_storage_get_remote_device_type::return_value = false; +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_is_restricted_device::return_value = false; +bt_status_t btif_storage_load_bonded_devices::return_value = BT_STATUS_SUCCESS; +bt_status_t btif_storage_remove_ble_bonding_keys::return_value = + BT_STATUS_SUCCESS; +bt_status_t btif_storage_remove_ble_local_keys::return_value = + BT_STATUS_SUCCESS; +bt_status_t btif_storage_remove_bonded_device::return_value = BT_STATUS_SUCCESS; +bt_status_t btif_storage_set_adapter_property::return_value = BT_STATUS_SUCCESS; +bt_status_t btif_storage_set_remote_device_property::return_value = + BT_STATUS_SUCCESS; + +} // namespace btif_storage +} // namespace mock +} // namespace test + +// Mocked functions, if any +void btif_debug_linkkey_type_dump(int fd) { inc_func_call_count(__func__); - Octet16 octet; - return octet; + 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 false; + return test::mock::btif_storage::btif_has_ble_keys(bdstr); } -bool btif_storage_get_hearing_aid_prop( - const RawAddress& address, uint8_t* capabilities, uint64_t* hi_sync_id, - uint16_t* render_delay, uint16_t* preparation_delay, uint16_t* codecs) { +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__); - return false; + return test::mock::btif_storage::btif_in_fetch_bonded_ble_device( + remote_bd_addr, add, p_bonded_devices); } -bool btif_storage_get_stored_remote_name(const RawAddress& bd_addr, - char* name) { +bt_status_t btif_in_fetch_bonded_device(const std::string& bdstr) { inc_func_call_count(__func__); - return false; + return test::mock::btif_storage::btif_in_fetch_bonded_device(bdstr); } -bool btif_storage_is_restricted_device(const RawAddress* remote_bd_addr) { +size_t btif_split_uuids_string(const char* str, bluetooth::Uuid* p_uuid, + size_t max_uuids) { inc_func_call_count(__func__); - return false; + return test::mock::btif_storage::btif_split_uuids_string(str, p_uuid, + max_uuids); } bt_status_t btif_storage_add_ble_bonding_key(RawAddress* remote_bd_addr, - const uint8_t* key, + const uint8_t* key_value, uint8_t key_type, uint8_t key_length) { inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; + return test::mock::btif_storage::btif_storage_add_ble_bonding_key( + remote_bd_addr, key_value, key_type, key_length); } -bt_status_t btif_storage_add_ble_local_key(const Octet16& key, +bt_status_t btif_storage_add_ble_local_key(const Octet16& key_value, uint8_t key_type) { inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; + return test::mock::btif_storage::btif_storage_add_ble_local_key(key_value, + key_type); } bt_status_t btif_storage_add_bonded_device(RawAddress* remote_bd_addr, LinkKey link_key, uint8_t key_type, uint8_t pin_length) { inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; -} -bt_status_t btif_storage_add_hid_device_info( - RawAddress* remote_bd_addr, uint16_t attr_mask, uint8_t sub_class, - uint8_t app_id, uint16_t vendor_id, uint16_t product_id, uint16_t version, - uint8_t ctry_code, uint16_t ssr_max_latency, uint16_t ssr_min_tout, - uint16_t dl_len, uint8_t* dsc_list) { - inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; + return test::mock::btif_storage::btif_storage_add_bonded_device( + remote_bd_addr, link_key, key_type, pin_length); } bt_status_t btif_storage_add_remote_device(const RawAddress* remote_bd_addr, uint32_t num_properties, bt_property_t* properties) { inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; + 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 BT_STATUS_SUCCESS; + return test::mock::btif_storage::btif_storage_get_adapter_property(property); } bt_status_t btif_storage_get_ble_bonding_key(const RawAddress& remote_bd_addr, uint8_t key_type, uint8_t* key_value, int key_length) { inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; + return test::mock::btif_storage::btif_storage_get_ble_bonding_key( + remote_bd_addr, key_type, key_value, key_length); } bt_status_t btif_storage_get_ble_local_key(uint8_t key_type, Octet16* key_value) { inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; -} -bt_status_t btif_storage_get_remote_addr_type(const RawAddress* remote_bd_addr, - tBLE_ADDR_TYPE* addr_type) { - inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; + return test::mock::btif_storage::btif_storage_get_ble_local_key(key_type, + key_value); } -bt_status_t btif_storage_get_remote_device_property( - const RawAddress* remote_bd_addr, bt_property_t* property) { +Octet16 btif_storage_get_gatt_cl_db_hash(const RawAddress& bd_addr) { inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; + return test::mock::btif_storage::btif_storage_get_gatt_cl_db_hash(bd_addr); } -bt_status_t btif_storage_load_bonded_devices(void) { +uint8_t btif_storage_get_gatt_cl_supp_feat(const RawAddress& bd_addr) { inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; + return test::mock::btif_storage::btif_storage_get_gatt_cl_supp_feat(bd_addr); } -bt_status_t btif_storage_load_bonded_hid_info(void) { +tBTM_IO_CAP btif_storage_get_local_io_caps() { inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; + return test::mock::btif_storage::btif_storage_get_local_io_caps(); } -bt_status_t btif_storage_load_hidd(void) { +int btif_storage_get_num_bonded_devices(void) { inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; + return test::mock::btif_storage::btif_storage_get_num_bonded_devices(); } -bt_status_t btif_storage_remove_ble_bonding_keys( - const RawAddress* remote_bd_addr) { +bt_status_t btif_storage_get_remote_addr_type(const RawAddress* remote_bd_addr, + tBLE_ADDR_TYPE* addr_type) { inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; + return test::mock::btif_storage::btif_storage_get_remote_addr_type( + remote_bd_addr, addr_type); } -bt_status_t btif_storage_remove_ble_local_keys(void) { +bool btif_storage_get_remote_addr_type(const RawAddress& remote_bd_addr, + tBLE_ADDR_TYPE& addr_type) { inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; + return test::mock::btif_storage::btif_storage_get_remote_addr_type2( + remote_bd_addr, addr_type); } -bt_status_t btif_storage_remove_bonded_device( - const RawAddress* remote_bd_addr) { +bt_status_t btif_storage_get_remote_device_property( + const RawAddress* remote_bd_addr, bt_property_t* property) { inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; + return test::mock::btif_storage::btif_storage_get_remote_device_property( + remote_bd_addr, property); } -bt_status_t btif_storage_remove_hid_info(const RawAddress& remote_bd_addr) { +bool btif_storage_get_remote_device_type(const RawAddress& remote_bd_addr, + tBT_DEVICE_TYPE& device_type) { inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; + return test::mock::btif_storage::btif_storage_get_remote_device_type( + remote_bd_addr, device_type); } -bt_status_t btif_storage_remove_hidd(RawAddress* remote_bd_addr) { +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 BT_STATUS_SUCCESS; + return test::mock::btif_storage::btif_storage_get_remote_prop( + remote_addr, type, buf, size, property); } -bt_status_t btif_storage_set_adapter_property(bt_property_t* property) { +uint8_t btif_storage_get_sr_supp_feat(const RawAddress& bd_addr) { inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; + return test::mock::btif_storage::btif_storage_get_sr_supp_feat(bd_addr); } -bt_status_t btif_storage_set_hidd(const RawAddress& remote_bd_addr) { +bool btif_storage_get_stored_remote_name(const RawAddress& bd_addr, + char* name) { inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; + return test::mock::btif_storage::btif_storage_get_stored_remote_name(bd_addr, + name); } -bt_status_t btif_storage_set_remote_addr_type(const RawAddress* remote_bd_addr, - tBLE_ADDR_TYPE addr_type) { +void btif_storage_invoke_addr_type_update(const RawAddress& remote_bd_addr, + const tBLE_ADDR_TYPE& addr_type) { inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; + test::mock::btif_storage::btif_storage_invoke_addr_type_update(remote_bd_addr, + addr_type); } -bt_status_t btif_storage_set_remote_device_property( - const RawAddress* remote_bd_addr, bt_property_t* property) { - inc_func_call_count(__func__); - return BT_STATUS_SUCCESS; -} -void btif_storage_add_hearing_aid(const HearingDevice& dev_info) { +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); } -int btif_storage_get_num_bonded_devices(void) { +bt_status_t btif_storage_load_bonded_devices(void) { inc_func_call_count(__func__); - return 0; + return test::mock::btif_storage::btif_storage_load_bonded_devices(); } -size_t btif_split_uuids_string(const char* str, bluetooth::Uuid* p_uuid, - size_t max_uuids) { +void btif_storage_load_le_devices(void) { inc_func_call_count(__func__); - return 0; + test::mock::btif_storage::btif_storage_load_le_devices(); } -uint8_t btif_storage_get_gatt_cl_supp_feat(const RawAddress& bd_addr) { +bt_status_t btif_storage_remove_ble_bonding_keys( + const RawAddress* remote_bd_addr) { inc_func_call_count(__func__); - return 0; + return test::mock::btif_storage::btif_storage_remove_ble_bonding_keys( + remote_bd_addr); } -tBTM_IO_CAP btif_storage_get_local_io_caps() { +bt_status_t btif_storage_remove_ble_local_keys(void) { inc_func_call_count(__func__); - return BTM_IO_CAP_UNKNOWN; + return test::mock::btif_storage::btif_storage_remove_ble_local_keys(); } -tBTM_IO_CAP btif_storage_get_local_io_caps_ble() { +bt_status_t btif_storage_remove_bonded_device( + const RawAddress* remote_bd_addr) { inc_func_call_count(__func__); - return BTM_IO_CAP_UNKNOWN; + return test::mock::btif_storage::btif_storage_remove_bonded_device( + remote_bd_addr); } -void btif_storage_load_bonded_hearing_aids() { inc_func_call_count(__func__); } void btif_storage_remove_gatt_cl_db_hash(const RawAddress& bd_addr) { inc_func_call_count(__func__); + test::mock::btif_storage::btif_storage_remove_gatt_cl_db_hash(bd_addr); } void btif_storage_remove_gatt_cl_supp_feat(const RawAddress& bd_addr) { inc_func_call_count(__func__); + test::mock::btif_storage::btif_storage_remove_gatt_cl_supp_feat(bd_addr); } -void btif_storage_remove_hearing_aid(const RawAddress& address) { +bt_status_t btif_storage_set_adapter_property(bt_property_t* property) { inc_func_call_count(__func__); + return test::mock::btif_storage::btif_storage_set_adapter_property(property); } void btif_storage_set_gatt_cl_db_hash(const RawAddress& bd_addr, Octet16 hash) { inc_func_call_count(__func__); + test::mock::btif_storage::btif_storage_set_gatt_cl_db_hash(bd_addr, hash); } void btif_storage_set_gatt_cl_supp_feat(const RawAddress& bd_addr, uint8_t feat) { inc_func_call_count(__func__); -} -void btif_storage_set_hearing_aid_acceptlist(const RawAddress& address, - bool add_to_acceptlist) { - inc_func_call_count(__func__); + test::mock::btif_storage::btif_storage_set_gatt_cl_supp_feat(bd_addr, feat); } void btif_storage_set_gatt_sr_supp_feat(const RawAddress& addr, uint8_t feat) { inc_func_call_count(__func__); + test::mock::btif_storage::btif_storage_set_gatt_sr_supp_feat(addr, feat); } -uint8_t btif_storage_get_sr_supp_feat(const RawAddress& bd_addr) { - inc_func_call_count(__func__); - return 0; -} -void btif_storage_add_groups(RawAddress const&) { - inc_func_call_count(__func__); -} -void btif_storage_remove_groups(RawAddress const&) { - inc_func_call_count(__func__); -} -void btif_storage_load_bonded_groups() { inc_func_call_count(__func__); } -void btif_storage_set_csis_autoconnect(const RawAddress& addr, - bool autoconnect) { - inc_func_call_count(__func__); -} -void btif_storage_update_csis_info(const RawAddress& addr) { +bt_status_t btif_storage_set_remote_addr_type(const RawAddress* remote_bd_addr, + const tBLE_ADDR_TYPE addr_type) { inc_func_call_count(__func__); + return test::mock::btif_storage::btif_storage_set_remote_addr_type( + remote_bd_addr, addr_type); } -void btif_storage_load_bonded_csis_devices() { inc_func_call_count(__func__); } -void btif_storage_remove_csis_device(const RawAddress& address) { +void btif_storage_set_remote_addr_type(const RawAddress& remote_bd_addr, + const tBLE_ADDR_TYPE& addr_type) { inc_func_call_count(__func__); + test::mock::btif_storage::btif_storage_set_remote_addr_type2(remote_bd_addr, + addr_type); } -void btif_storage_set_pce_profile_version(const RawAddress& remote_bd_addr, - uint16_t peer_pce_version) { +bt_status_t btif_storage_set_remote_device_property( + const RawAddress* remote_bd_addr, bt_property_t* property) { inc_func_call_count(__func__); + return test::mock::btif_storage::btif_storage_set_remote_device_property( + remote_bd_addr, property); } -bool btif_storage_is_pce_version_102(const RawAddress& remote_bd_addr) { +void btif_storage_set_remote_device_type(const RawAddress& remote_bd_addr, + const tBT_DEVICE_TYPE& device_type) { inc_func_call_count(__func__); - return false; + test::mock::btif_storage::btif_storage_set_remote_device_type(remote_bd_addr, + device_type); } +// Mocked functions complete +// END mockcify generation diff --git a/system/test/mock/mock_btif_storage.h b/system/test/mock/mock_btif_storage.h new file mode 100644 index 0000000000..e38a1bb544 --- /dev/null +++ b/system/test/mock/mock_btif_storage.h @@ -0,0 +1,627 @@ +/* + * 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. + */ +#pragma once + +/* + * Generated mock file from original source file + * Functions generated:41 + * + * mockcify.pl ver 0.7.0 + */ + +#include <cstdint> +#include <functional> + +// Original included files, if any +// NOTE: Since this is a mock file with mock definitions some number of +// include files may not be required. The include-what-you-use +// still applies, but crafting proper inclusion is out of scope +// for this effort. This compilation unit may compile as-is, or +// may need attention to prune from (or add to ) the inclusion set. + +#include "btif/include/btif_storage.h" +#include "stack/include/bt_octets.h" +#include "types/bluetooth/uuid.h" +#include "types/raw_address.h" + +// Original usings + +// Mocked compile conditionals, if any + +namespace test { +namespace mock { +namespace btif_storage { + +// Shared state between mocked functions and tests +// Name: btif_debug_linkkey_type_dump +// Params: int fd +// Return: void +struct btif_debug_linkkey_type_dump { + std::function<void(int fd)> body{[](int /* fd */) {}}; + void operator()(int fd) { body(fd); }; +}; +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 +struct btif_in_fetch_bonded_ble_device { + static bt_status_t return_value; + std::function<bt_status_t(const std::string& remote_bd_addr, int add, + btif_bonded_devices_t* p_bonded_devices)> + body{[](const std::string& /* remote_bd_addr */, int /* add */, + btif_bonded_devices_t* /* p_bonded_devices */) { + return return_value; + }}; + bt_status_t operator()(const std::string& remote_bd_addr, int add, + btif_bonded_devices_t* p_bonded_devices) { + return body(remote_bd_addr, add, p_bonded_devices); + }; +}; +extern struct btif_in_fetch_bonded_ble_device btif_in_fetch_bonded_ble_device; + +// Name: btif_in_fetch_bonded_device +// Params: const std::string& bdstr +// Return: bt_status_t +struct btif_in_fetch_bonded_device { + static bt_status_t return_value; + std::function<bt_status_t(const std::string& bdstr)> body{ + [](const std::string& /* bdstr */) { return return_value; }}; + bt_status_t operator()(const std::string& bdstr) { return body(bdstr); }; +}; +extern struct btif_in_fetch_bonded_device btif_in_fetch_bonded_device; + +// Name: btif_split_uuids_string +// Params: const char* str, bluetooth::Uuid* p_uuid, size_t max_uuids +// Return: size_t +struct btif_split_uuids_string { + static size_t return_value; + std::function<size_t(const char* str, bluetooth::Uuid* p_uuid, + size_t max_uuids)> + body{[](const char* /* str */, bluetooth::Uuid* /* p_uuid */, + size_t /* max_uuids */) { return return_value; }}; + size_t operator()(const char* str, bluetooth::Uuid* p_uuid, + size_t max_uuids) { + return body(str, p_uuid, max_uuids); + }; +}; +extern struct btif_split_uuids_string btif_split_uuids_string; + +// Name: btif_storage_add_ble_bonding_key +// Params: RawAddress* remote_bd_addr, const uint8_t* key_value, uint8_t +// key_type, uint8_t key_length Return: bt_status_t +struct btif_storage_add_ble_bonding_key { + static bt_status_t return_value; + std::function<bt_status_t(RawAddress* remote_bd_addr, + const uint8_t* key_value, uint8_t key_type, + uint8_t key_length)> + body{[](RawAddress* /* remote_bd_addr */, const uint8_t* /* key_value */, + uint8_t /* key_type */, + uint8_t /* key_length */) { return return_value; }}; + bt_status_t operator()(RawAddress* remote_bd_addr, const uint8_t* key_value, + uint8_t key_type, uint8_t key_length) { + return body(remote_bd_addr, key_value, key_type, key_length); + }; +}; +extern struct btif_storage_add_ble_bonding_key btif_storage_add_ble_bonding_key; + +// Name: btif_storage_add_ble_local_key +// Params: const Octet16& key_value, uint8_t key_type +// Return: bt_status_t +struct btif_storage_add_ble_local_key { + static bt_status_t return_value; + std::function<bt_status_t(const Octet16& key_value, uint8_t key_type)> body{ + [](const Octet16& /* key_value */, uint8_t /* key_type */) { + return return_value; + }}; + bt_status_t operator()(const Octet16& key_value, uint8_t key_type) { + return body(key_value, key_type); + }; +}; +extern struct btif_storage_add_ble_local_key btif_storage_add_ble_local_key; + +// Name: btif_storage_add_bonded_device +// Params: RawAddress* remote_bd_addr, LinkKey link_key, uint8_t key_type, +// uint8_t pin_length Return: bt_status_t +struct btif_storage_add_bonded_device { + static bt_status_t return_value; + std::function<bt_status_t(RawAddress* remote_bd_addr, LinkKey link_key, + uint8_t key_type, uint8_t pin_length)> + body{[](RawAddress* /* remote_bd_addr */, LinkKey /* link_key */, + uint8_t /* key_type */, + uint8_t /* pin_length */) { return return_value; }}; + bt_status_t operator()(RawAddress* remote_bd_addr, LinkKey link_key, + uint8_t key_type, uint8_t pin_length) { + return body(remote_bd_addr, link_key, key_type, pin_length); + }; +}; +extern struct btif_storage_add_bonded_device btif_storage_add_bonded_device; + +// Name: btif_storage_add_remote_device +// Params: const RawAddress* remote_bd_addr, uint32_t num_properties, +// bt_property_t* properties Return: bt_status_t +struct btif_storage_add_remote_device { + static bt_status_t return_value; + std::function<bt_status_t(const RawAddress* remote_bd_addr, + uint32_t num_properties, bt_property_t* properties)> + body{[](const RawAddress* /* remote_bd_addr */, + uint32_t /* num_properties */, + bt_property_t* /* properties */) { return return_value; }}; + bt_status_t operator()(const RawAddress* remote_bd_addr, + uint32_t num_properties, bt_property_t* properties) { + return body(remote_bd_addr, num_properties, properties); + }; +}; +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 +struct btif_storage_get_adapter_property { + static bt_status_t return_value; + std::function<bt_status_t(bt_property_t* property)> body{ + [](bt_property_t* /* property */) { return return_value; }}; + bt_status_t operator()(bt_property_t* property) { return body(property); }; +}; +extern struct btif_storage_get_adapter_property + btif_storage_get_adapter_property; + +// Name: btif_storage_get_ble_bonding_key +// Params: const RawAddress& remote_bd_addr, uint8_t key_type, uint8_t* +// key_value, int key_length Return: bt_status_t +struct btif_storage_get_ble_bonding_key { + static bt_status_t return_value; + std::function<bt_status_t(const RawAddress& remote_bd_addr, uint8_t key_type, + uint8_t* key_value, int key_length)> + body{[](const RawAddress& /* remote_bd_addr */, uint8_t /* key_type */, + uint8_t* /* key_value */, + int /* key_length */) { return return_value; }}; + bt_status_t operator()(const RawAddress& remote_bd_addr, uint8_t key_type, + uint8_t* key_value, int key_length) { + return body(remote_bd_addr, key_type, key_value, key_length); + }; +}; +extern struct btif_storage_get_ble_bonding_key btif_storage_get_ble_bonding_key; + +// Name: btif_storage_get_ble_local_key +// Params: uint8_t key_type, Octet16* key_value +// Return: bt_status_t +struct btif_storage_get_ble_local_key { + static bt_status_t return_value; + std::function<bt_status_t(uint8_t key_type, Octet16* key_value)> body{ + [](uint8_t /* key_type */, Octet16* /* key_value */) { + return return_value; + }}; + bt_status_t operator()(uint8_t key_type, Octet16* key_value) { + return body(key_type, key_value); + }; +}; +extern struct btif_storage_get_ble_local_key btif_storage_get_ble_local_key; + +// Name: btif_storage_get_gatt_cl_db_hash +// Params: const RawAddress& bd_addr +// Return: Octet16 +struct btif_storage_get_gatt_cl_db_hash { + static Octet16 return_value; + std::function<Octet16(const RawAddress& bd_addr)> body{ + [](const RawAddress& /* bd_addr */) { return return_value; }}; + Octet16 operator()(const RawAddress& bd_addr) { return body(bd_addr); }; +}; +extern struct btif_storage_get_gatt_cl_db_hash btif_storage_get_gatt_cl_db_hash; + +// Name: btif_storage_get_gatt_cl_supp_feat +// Params: const RawAddress& bd_addr +// Return: uint8_t +struct btif_storage_get_gatt_cl_supp_feat { + static uint8_t return_value; + std::function<uint8_t(const RawAddress& bd_addr)> body{ + [](const RawAddress& /* bd_addr */) { return return_value; }}; + uint8_t operator()(const RawAddress& bd_addr) { return body(bd_addr); }; +}; +extern struct btif_storage_get_gatt_cl_supp_feat + btif_storage_get_gatt_cl_supp_feat; + +// Name: btif_storage_get_local_io_caps +// Params: +// Return: tBTM_IO_CAP +struct btif_storage_get_local_io_caps { + static tBTM_IO_CAP return_value; + std::function<tBTM_IO_CAP()> body{[]() { return return_value; }}; + tBTM_IO_CAP operator()() { return body(); }; +}; +extern struct btif_storage_get_local_io_caps btif_storage_get_local_io_caps; + +// Name: btif_storage_get_num_bonded_devices +// Params: void +// Return: int +struct btif_storage_get_num_bonded_devices { + static int return_value; + std::function<int(void)> body{[](void) { return return_value; }}; + int operator()(void) { return body(); }; +}; +extern struct btif_storage_get_num_bonded_devices + btif_storage_get_num_bonded_devices; + +// Name: btif_storage_get_remote_addr_type +// Params: const RawAddress* remote_bd_addr, tBLE_ADDR_TYPE addr_type +// Return: bt_status_t +struct btif_storage_get_remote_addr_type { + static bt_status_t return_value; + std::function<bt_status_t(const RawAddress* remote_bd_addr, + tBLE_ADDR_TYPE* addr_type)> + body{[](const RawAddress* /* remote_bd_addr */, + tBLE_ADDR_TYPE* /* addr_type */) -> bt_status_t { + return return_value; + }}; + bt_status_t operator()(const RawAddress* remote_bd_addr, + tBLE_ADDR_TYPE* addr_type) { + return body(remote_bd_addr, addr_type); + }; +}; +extern struct btif_storage_get_remote_addr_type + btif_storage_get_remote_addr_type; + +// Name: btif_storage_get_remote_addr_type2 +// Params: const RawAddress& remote_bd_addr, tBLE_ADDR_TYPE& addr_type +// Return: bool +struct btif_storage_get_remote_addr_type2 { + static bool return_value; + std::function<bool(const RawAddress& remote_bd_addr, + tBLE_ADDR_TYPE& addr_type)> + body{[](const RawAddress& /* remote_bd_addr */, + tBLE_ADDR_TYPE& /* addr_type */) { return return_value; }}; + bool operator()(const RawAddress& remote_bd_addr, tBLE_ADDR_TYPE& addr_type) { + return body(remote_bd_addr, addr_type); + }; +}; +extern struct btif_storage_get_remote_addr_type2 + btif_storage_get_remote_addr_type2; + +// Name: btif_storage_get_remote_device_property +// Params: const RawAddress* remote_bd_addr, bt_property_t* property +// Return: bt_status_t +struct btif_storage_get_remote_device_property { + static bt_status_t return_value; + std::function<bt_status_t(const RawAddress* remote_bd_addr, + bt_property_t* property)> + body{[](const RawAddress* /* remote_bd_addr */, + bt_property_t* /* property */) { return return_value; }}; + bt_status_t operator()(const RawAddress* remote_bd_addr, + bt_property_t* property) { + return body(remote_bd_addr, property); + }; +}; +extern struct btif_storage_get_remote_device_property + btif_storage_get_remote_device_property; + +// Name: btif_storage_get_remote_device_type +// Params: const RawAddress& remote_bd_addr, tBT_DEVICE_TYPE& device_type +// Return: bool +struct btif_storage_get_remote_device_type { + static bool return_value; + std::function<bool(const RawAddress& remote_bd_addr, + tBT_DEVICE_TYPE& device_type)> + body{[](const RawAddress& /* remote_bd_addr */, + tBT_DEVICE_TYPE& /* device_type */) { return return_value; }}; + bool operator()(const RawAddress& remote_bd_addr, + tBT_DEVICE_TYPE& device_type) { + return body(remote_bd_addr, device_type); + }; +}; +extern struct btif_storage_get_remote_device_type + btif_storage_get_remote_device_type; + +// 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 +struct btif_storage_get_sr_supp_feat { + static uint8_t return_value; + std::function<uint8_t(const RawAddress& bd_addr)> body{ + [](const RawAddress& /* bd_addr */) { return return_value; }}; + uint8_t operator()(const RawAddress& bd_addr) { return body(bd_addr); }; +}; +extern struct btif_storage_get_sr_supp_feat btif_storage_get_sr_supp_feat; + +// Name: btif_storage_get_stored_remote_name +// Params: const RawAddress& bd_addr, char* name +// Return: bool +struct btif_storage_get_stored_remote_name { + static bool return_value; + std::function<bool(const RawAddress& bd_addr, char* name)> body{ + [](const RawAddress& /* bd_addr */, char* /* name */) { + return return_value; + }}; + bool operator()(const RawAddress& bd_addr, char* name) { + return body(bd_addr, name); + }; +}; +extern struct btif_storage_get_stored_remote_name + btif_storage_get_stored_remote_name; + +// 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 +struct btif_storage_is_restricted_device { + static bool return_value; + std::function<bool(const RawAddress* remote_bd_addr)> body{ + [](const RawAddress* /* remote_bd_addr */) { return return_value; }}; + bool operator()(const RawAddress* remote_bd_addr) { + return body(remote_bd_addr); + }; +}; +extern struct btif_storage_is_restricted_device + btif_storage_is_restricted_device; + +// Name: btif_storage_load_bonded_devices +// Params: void +// Return: bt_status_t +struct btif_storage_load_bonded_devices { + static bt_status_t return_value; + std::function<bt_status_t(void)> body{[](void) { return return_value; }}; + bt_status_t operator()(void) { return body(); }; +}; +extern struct btif_storage_load_bonded_devices btif_storage_load_bonded_devices; + +// Name: btif_storage_load_le_devices +// Params: void +// Return: void +struct btif_storage_load_le_devices { + std::function<void(void)> body{[](void) {}}; + void operator()(void) { body(); }; +}; +extern struct btif_storage_load_le_devices btif_storage_load_le_devices; + +// Name: btif_storage_remove_ble_bonding_keys +// Params: const RawAddress* remote_bd_addr +// Return: bt_status_t +struct btif_storage_remove_ble_bonding_keys { + static bt_status_t return_value; + std::function<bt_status_t(const RawAddress* remote_bd_addr)> body{ + [](const RawAddress* /* remote_bd_addr */) { return return_value; }}; + bt_status_t operator()(const RawAddress* remote_bd_addr) { + return body(remote_bd_addr); + }; +}; +extern struct btif_storage_remove_ble_bonding_keys + btif_storage_remove_ble_bonding_keys; + +// Name: btif_storage_remove_ble_local_keys +// Params: void +// Return: bt_status_t +struct btif_storage_remove_ble_local_keys { + static bt_status_t return_value; + std::function<bt_status_t(void)> body{[](void) { return return_value; }}; + bt_status_t operator()(void) { return body(); }; +}; +extern struct btif_storage_remove_ble_local_keys + btif_storage_remove_ble_local_keys; + +// Name: btif_storage_remove_bonded_device +// Params: const RawAddress* remote_bd_addr +// Return: bt_status_t +struct btif_storage_remove_bonded_device { + static bt_status_t return_value; + std::function<bt_status_t(const RawAddress* remote_bd_addr)> body{ + [](const RawAddress* /* remote_bd_addr */) { return return_value; }}; + bt_status_t operator()(const RawAddress* remote_bd_addr) { + return body(remote_bd_addr); + }; +}; +extern struct btif_storage_remove_bonded_device + btif_storage_remove_bonded_device; + +// Name: btif_storage_remove_gatt_cl_db_hash +// Params: const RawAddress& bd_addr +// Return: void +struct btif_storage_remove_gatt_cl_db_hash { + std::function<void(const RawAddress& bd_addr)> body{ + [](const RawAddress& /* bd_addr */) {}}; + void operator()(const RawAddress& bd_addr) { body(bd_addr); }; +}; +extern struct btif_storage_remove_gatt_cl_db_hash + btif_storage_remove_gatt_cl_db_hash; + +// Name: btif_storage_remove_gatt_cl_supp_feat +// Params: const RawAddress& bd_addr +// Return: void +struct btif_storage_remove_gatt_cl_supp_feat { + std::function<void(const RawAddress& bd_addr)> body{ + [](const RawAddress& /* bd_addr */) {}}; + void operator()(const RawAddress& bd_addr) { body(bd_addr); }; +}; +extern struct btif_storage_remove_gatt_cl_supp_feat + btif_storage_remove_gatt_cl_supp_feat; + +// Name: btif_storage_set_adapter_property +// Params: bt_property_t* property +// Return: bt_status_t +struct btif_storage_set_adapter_property { + static bt_status_t return_value; + std::function<bt_status_t(bt_property_t* property)> body{ + [](bt_property_t* /* property */) { return return_value; }}; + bt_status_t operator()(bt_property_t* property) { return body(property); }; +}; +extern struct btif_storage_set_adapter_property + btif_storage_set_adapter_property; + +// Name: btif_storage_set_gatt_cl_db_hash +// Params: const RawAddress& bd_addr, Octet16 hash +// Return: void +struct btif_storage_set_gatt_cl_db_hash { + std::function<void(const RawAddress& bd_addr, Octet16 hash)> body{ + [](const RawAddress& /* bd_addr */, Octet16 /* hash */) {}}; + void operator()(const RawAddress& bd_addr, Octet16 hash) { + body(bd_addr, hash); + }; +}; +extern struct btif_storage_set_gatt_cl_db_hash btif_storage_set_gatt_cl_db_hash; + +// Name: btif_storage_set_gatt_cl_supp_feat +// Params: const RawAddress& bd_addr, uint8_t feat +// Return: void +struct btif_storage_set_gatt_cl_supp_feat { + std::function<void(const RawAddress& bd_addr, uint8_t feat)> body{ + [](const RawAddress& /* bd_addr */, uint8_t /* feat */) {}}; + void operator()(const RawAddress& bd_addr, uint8_t feat) { + body(bd_addr, feat); + }; +}; +extern struct btif_storage_set_gatt_cl_supp_feat + btif_storage_set_gatt_cl_supp_feat; + +// Name: btif_storage_set_gatt_sr_supp_feat +// Params: const RawAddress& addr, uint8_t feat +// Return: void +struct btif_storage_set_gatt_sr_supp_feat { + std::function<void(const RawAddress& addr, uint8_t feat)> body{ + [](const RawAddress& /* addr */, uint8_t /* feat */) {}}; + void operator()(const RawAddress& addr, uint8_t feat) { body(addr, feat); }; +}; +extern struct btif_storage_set_gatt_sr_supp_feat + btif_storage_set_gatt_sr_supp_feat; + +// Name: btif_storage_set_remote_addr_type +// Params: const RawAddress& remote_bd_addr, const tBLE_ADDR_TYPE& addr_type +// Return: void +struct btif_storage_set_remote_addr_type { + std::function<bt_status_t(const RawAddress* remote_bd_addr, + const tBLE_ADDR_TYPE addr_type)> + body{[](const RawAddress* /* remote_bd_addr */, + const tBLE_ADDR_TYPE /* addr_type */) { + return BT_STATUS_SUCCESS; + }}; + bt_status_t operator()(const RawAddress* remote_bd_addr, + const tBLE_ADDR_TYPE addr_type) { + return body(remote_bd_addr, addr_type); + }; +}; +extern struct btif_storage_set_remote_addr_type + btif_storage_set_remote_addr_type; + +// Name: btif_storage_set_remote_addr_type +// Params: const RawAddress& remote_bd_addr, const tBLE_ADDR_TYPE& addr_type +// Return: void +struct btif_storage_set_remote_addr_type2 { + 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_set_remote_addr_type2 + btif_storage_set_remote_addr_type2; + +// Name: btif_storage_set_remote_device_property +// Params: const RawAddress* remote_bd_addr, bt_property_t* property +// Return: bt_status_t +struct btif_storage_set_remote_device_property { + static bt_status_t return_value; + std::function<bt_status_t(const RawAddress* remote_bd_addr, + bt_property_t* property)> + body{[](const RawAddress* /* remote_bd_addr */, + bt_property_t* /* property */) { return return_value; }}; + bt_status_t operator()(const RawAddress* remote_bd_addr, + bt_property_t* property) { + return body(remote_bd_addr, property); + }; +}; +extern struct btif_storage_set_remote_device_property + btif_storage_set_remote_device_property; + +// Name: btif_storage_set_remote_device_type +// Params: const RawAddress& remote_bd_addr, const tBT_DEVICE_TYPE& device_type +// Return: void +struct btif_storage_set_remote_device_type { + std::function<void(const RawAddress& remote_bd_addr, + const tBT_DEVICE_TYPE& device_type)> + body{[](const RawAddress& /* remote_bd_addr */, + const tBT_DEVICE_TYPE& /* device_type */) {}}; + void operator()(const RawAddress& remote_bd_addr, + const tBT_DEVICE_TYPE& device_type) { + body(remote_bd_addr, device_type); + }; +}; +extern struct btif_storage_set_remote_device_type + btif_storage_set_remote_device_type; + +} // namespace btif_storage +} // namespace mock +} // namespace test + +// END mockcify generation diff --git a/system/test/mock/mock_btif_util.h b/system/test/mock/mock_btif_util.h index 2753712420..dd7dec3a39 100644 --- a/system/test/mock/mock_btif_util.h +++ b/system/test/mock/mock_btif_util.h @@ -46,7 +46,7 @@ namespace btif_util { struct ascii_2_hex { static int return_value; std::function<int(const char* p_ascii, int len, uint8_t* p_hex)> body{ - [](const char* p_ascii, int len, uint8_t* p_hex) { + [](const char* /* p_ascii */, int /* len */, uint8_t* /* p_hex */) { return return_value; }}; int operator()(const char* p_ascii, int len, uint8_t* p_hex) { @@ -61,7 +61,7 @@ extern struct ascii_2_hex ascii_2_hex; struct devclass2uint { static uint32_t return_value; std::function<uint32_t(DEV_CLASS dev_class)> body{ - [](DEV_CLASS dev_class) { return return_value; }}; + [](DEV_CLASS /* dev_class */) { return return_value; }}; uint32_t operator()(DEV_CLASS dev_class) { return body(dev_class); }; }; extern struct devclass2uint devclass2uint; @@ -72,7 +72,7 @@ extern struct devclass2uint devclass2uint; struct dump_adapter_scan_mode { static const char* return_value; std::function<const char*(bt_scan_mode_t mode)> body{ - [](bt_scan_mode_t mode) { return return_value; }}; + [](bt_scan_mode_t /* mode */) { return return_value; }}; const char* operator()(bt_scan_mode_t mode) { return body(mode); }; }; extern struct dump_adapter_scan_mode dump_adapter_scan_mode; @@ -83,7 +83,7 @@ extern struct dump_adapter_scan_mode dump_adapter_scan_mode; struct dump_av_audio_state { static const char* return_value; std::function<const char*(uint16_t event)> body{ - [](uint16_t event) { return return_value; }}; + [](uint16_t /* event */) { return return_value; }}; const char* operator()(uint16_t event) { return body(event); }; }; extern struct dump_av_audio_state dump_av_audio_state; @@ -94,7 +94,7 @@ extern struct dump_av_audio_state dump_av_audio_state; struct dump_av_conn_state { static const char* return_value; std::function<const char*(uint16_t event)> body{ - [](uint16_t event) { return return_value; }}; + [](uint16_t /* event */) { return return_value; }}; const char* operator()(uint16_t event) { return body(event); }; }; extern struct dump_av_conn_state dump_av_conn_state; @@ -105,7 +105,7 @@ extern struct dump_av_conn_state dump_av_conn_state; struct dump_bt_status { static const char* return_value; std::function<const char*(bt_status_t status)> body{ - [](bt_status_t status) { return return_value; }}; + [](bt_status_t /* status */) { return return_value; }}; const char* operator()(bt_status_t status) { return body(status); }; }; extern struct dump_bt_status dump_bt_status; @@ -116,7 +116,7 @@ extern struct dump_bt_status dump_bt_status; struct dump_dm_event { static const char* return_value; std::function<const char*(uint16_t event)> body{ - [](uint16_t event) { return return_value; }}; + [](uint16_t /* event */) { return return_value; }}; const char* operator()(uint16_t event) { return body(event); }; }; extern struct dump_dm_event dump_dm_event; @@ -127,7 +127,7 @@ extern struct dump_dm_event dump_dm_event; struct dump_dm_search_event { static const char* return_value; std::function<const char*(uint16_t event)> body{ - [](uint16_t event) { return return_value; }}; + [](uint16_t /* event */) { return return_value; }}; const char* operator()(uint16_t event) { return body(event); }; }; extern struct dump_dm_search_event dump_dm_search_event; @@ -138,7 +138,7 @@ extern struct dump_dm_search_event dump_dm_search_event; struct dump_hd_event { static const char* return_value; std::function<const char*(uint16_t event)> body{ - [](uint16_t event) { return return_value; }}; + [](uint16_t /* event */) { return return_value; }}; const char* operator()(uint16_t event) { return body(event); }; }; extern struct dump_hd_event dump_hd_event; @@ -149,7 +149,7 @@ extern struct dump_hd_event dump_hd_event; struct dump_hf_client_event { static const char* return_value; std::function<const char*(uint16_t event)> body{ - [](uint16_t event) { return return_value; }}; + [](uint16_t /* event */) { return return_value; }}; const char* operator()(uint16_t event) { return body(event); }; }; extern struct dump_hf_client_event dump_hf_client_event; @@ -160,7 +160,7 @@ extern struct dump_hf_client_event dump_hf_client_event; struct dump_hf_event { static const char* return_value; std::function<const char*(uint16_t event)> body{ - [](uint16_t event) { return return_value; }}; + [](uint16_t /* event */) { return return_value; }}; const char* operator()(uint16_t event) { return body(event); }; }; extern struct dump_hf_event dump_hf_event; @@ -171,7 +171,7 @@ extern struct dump_hf_event dump_hf_event; struct dump_hh_event { static const char* return_value; std::function<const char*(uint16_t event)> body{ - [](uint16_t event) { return return_value; }}; + [](uint16_t /* event */) { return return_value; }}; const char* operator()(uint16_t event) { return body(event); }; }; extern struct dump_hh_event dump_hh_event; @@ -182,7 +182,7 @@ extern struct dump_hh_event dump_hh_event; struct dump_property_type { static const char* return_value; std::function<const char*(bt_property_type_t type)> body{ - [](bt_property_type_t type) { return return_value; }}; + [](bt_property_type_t /* type */) { return return_value; }}; const char* operator()(bt_property_type_t type) { return body(type); }; }; extern struct dump_property_type dump_property_type; @@ -193,7 +193,7 @@ extern struct dump_property_type dump_property_type; struct dump_rc_event { static const char* return_value; std::function<const char*(uint8_t event)> body{ - [](uint8_t event) { return return_value; }}; + [](uint8_t /* event */) { return return_value; }}; const char* operator()(uint8_t event) { return body(event); }; }; extern struct dump_rc_event dump_rc_event; @@ -204,7 +204,7 @@ extern struct dump_rc_event dump_rc_event; struct dump_rc_notification_event_id { static const char* return_value; std::function<const char*(uint8_t event_id)> body{ - [](uint8_t event_id) { return return_value; }}; + [](uint8_t /* event_id */) { return return_value; }}; const char* operator()(uint8_t event_id) { return body(event_id); }; }; extern struct dump_rc_notification_event_id dump_rc_notification_event_id; @@ -215,7 +215,7 @@ extern struct dump_rc_notification_event_id dump_rc_notification_event_id; struct dump_rc_pdu { static const char* return_value; std::function<const char*(uint8_t pdu)> body{ - [](uint8_t pdu) { return return_value; }}; + [](uint8_t /* pdu */) { return return_value; }}; const char* operator()(uint8_t pdu) { return body(pdu); }; }; extern struct dump_rc_pdu dump_rc_pdu; @@ -226,7 +226,7 @@ extern struct dump_rc_pdu dump_rc_pdu; struct dump_thread_evt { static const char* return_value; std::function<const char*(bt_cb_thread_evt evt)> body{ - [](bt_cb_thread_evt evt) { return return_value; }}; + [](bt_cb_thread_evt /* evt */) { return return_value; }}; const char* operator()(bt_cb_thread_evt evt) { return body(evt); }; }; extern struct dump_thread_evt dump_thread_evt; @@ -237,7 +237,7 @@ extern struct dump_thread_evt dump_thread_evt; struct uint2devclass { static constexpr DEV_CLASS return_value{}; std::function<DEV_CLASS(uint32_t cod)> body{ - [](uint32_t cod) { return return_value; }}; + [](uint32_t /* cod */) { return return_value; }}; DEV_CLASS operator()(uint32_t cod) { return body(cod); }; }; extern struct uint2devclass uint2devclass; diff --git a/system/test/mock/mock_jni_thread.cc b/system/test/mock/mock_jni_thread.cc new file mode 100644 index 0000000000..bcc0471384 --- /dev/null +++ b/system/test/mock/mock_jni_thread.cc @@ -0,0 +1,52 @@ +/* + * 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. + */ + +/* + * Generated mock file from original source file + * Functions generated:27 + */ + +#include <base/functional/bind.h> + +#include <cstdint> + +#include "btif/include/btif_common.h" +#include "include/hardware/bluetooth.h" +#include "test/common/jni_thread.h" +#include "test/common/mock_functions.h" + +bool is_on_jni_thread() { + inc_func_call_count(__func__); + return false; +} +bt_status_t btif_transfer_context(tBTIF_CBACK* /* p_cback */, + uint16_t /* event */, char* /* p_params */, + int /* param_len */, + tBTIF_COPY_CBACK* /* p_copy_cback */) { + inc_func_call_count(__func__); + return BT_STATUS_SUCCESS; +} +bt_status_t do_in_jni_thread(base::OnceClosure task) { + inc_func_call_count(__func__); + 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_stack_btm_sec.cc b/system/test/mock/mock_stack_btm_sec.cc index 850c89216e..1f656f3a6d 100644 --- a/system/test/mock/mock_stack_btm_sec.cc +++ b/system/test/mock/mock_stack_btm_sec.cc @@ -89,6 +89,7 @@ struct btm_sec_dev_reset btm_sec_dev_reset; struct btm_sec_disconnect btm_sec_disconnect; struct btm_sec_disconnected btm_sec_disconnected; struct btm_sec_encrypt_change btm_sec_encrypt_change; +struct btm_sec_encryption_change_evt btm_sec_encryption_change_evt; struct btm_sec_is_a_bonded_dev btm_sec_is_a_bonded_dev; struct btm_sec_l2cap_access_req btm_sec_l2cap_access_req; struct btm_sec_l2cap_access_req_by_requirement @@ -377,6 +378,12 @@ void btm_sec_encrypt_change(uint16_t handle, tHCI_STATUS status, test::mock::stack_btm_sec::btm_sec_encrypt_change(handle, status, encr_enable); } +void btm_sec_encryption_change_evt(uint16_t handle, tHCI_STATUS status, + uint8_t encr_enable) { + inc_func_call_count(__func__); + test::mock::stack_btm_sec::btm_sec_encryption_change_evt(handle, status, + encr_enable); +} bool btm_sec_is_a_bonded_dev(const RawAddress& bda) { inc_func_call_count(__func__); return test::mock::stack_btm_sec::btm_sec_is_a_bonded_dev(bda); diff --git a/system/test/mock/mock_stack_btm_sec.h b/system/test/mock/mock_stack_btm_sec.h index ecad42612e..d757592280 100644 --- a/system/test/mock/mock_stack_btm_sec.h +++ b/system/test/mock/mock_stack_btm_sec.h @@ -669,6 +669,19 @@ struct btm_sec_encrypt_change { }; extern struct btm_sec_encrypt_change btm_sec_encrypt_change; +// Name: btm_sec_encryption_change_evt +// Params: uint16_t handle, tHCI_STATUS status, uint8_t encr_enable +// Return: void +struct btm_sec_encryption_change_evt { + std::function<void(uint16_t handle, tHCI_STATUS status, uint8_t encr_enable)> + body{[](uint16_t /* handle */, tHCI_STATUS /* status */, + uint8_t /* encr_enable */) {}}; + void operator()(uint16_t handle, tHCI_STATUS status, uint8_t encr_enable) { + body(handle, status, encr_enable); + }; +}; +extern struct btm_sec_encryption_change_evt btm_sec_encryption_change_evt; + // Name: btm_sec_is_a_bonded_dev // Params: const RawAddress& bda // Return: bool diff --git a/system/test/mock/mock_stack_btu_hcif.cc b/system/test/mock/mock_stack_btu_hcif.cc index ba9967917c..e525c9225d 100644 --- a/system/test/mock/mock_stack_btu_hcif.cc +++ b/system/test/mock/mock_stack_btu_hcif.cc @@ -38,20 +38,20 @@ struct cmd_with_cb_data { base::Location posted_from; }; -void btu_hcif_process_event(uint8_t controller_id, BT_HDR* p_msg) { +void btu_hcif_process_event(uint8_t /* controller_id */, BT_HDR* /* p_msg */) { inc_func_call_count(__func__); } -void btu_hcif_send_cmd(uint8_t controller_id, const BT_HDR* p_buf) { +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(const base::Location& /* posted_from */, + uint16_t /* opcode */, uint8_t* /* params */, + uint8_t /* params_len */, hci_cmd_cb /* cb */) { inc_func_call_count(__func__); } -void cmd_with_cb_data_cleanup(cmd_with_cb_data* cb_wrapper) { +void cmd_with_cb_data_cleanup(cmd_with_cb_data* /* cb_wrapper */) { inc_func_call_count(__func__); } -void cmd_with_cb_data_init(cmd_with_cb_data* cb_wrapper) { +void cmd_with_cb_data_init(cmd_with_cb_data* /* cb_wrapper */) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_stack_hcic_hciblecmds.h b/system/test/mock/mock_stack_hcic_hciblecmds.h index 5d9b5766b4..ef68736388 100644 --- a/system/test/mock/mock_stack_hcic_hciblecmds.h +++ b/system/test/mock/mock_stack_hcic_hciblecmds.h @@ -45,9 +45,9 @@ namespace stack_hcic_hciblecmds { struct btsnd_hci_ble_add_device_to_periodic_advertiser_list { std::function<void(uint8_t, const RawAddress&, uint8_t, base::OnceCallback<void(uint8_t*, uint16_t)>)> - body{[](uint8_t adv_addr_type, const RawAddress& adv_addr, - uint8_t adv_sid, - base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}}; + body{[](uint8_t /* adv_addr_type */, const RawAddress& /* adv_addr */, + uint8_t /* adv_sid */, + base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}}; void operator()(uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_sid, base::OnceCallback<void(uint8_t*, uint16_t)> cb) { @@ -76,9 +76,9 @@ extern struct btsnd_hci_ble_clear_periodic_advertiser_list struct btsnd_hci_ble_remove_device_from_periodic_advertiser_list { std::function<void(uint8_t, const RawAddress&, uint8_t, base::OnceCallback<void(uint8_t*, uint16_t)>)> - body{[](uint8_t adv_addr_type, const RawAddress& adv_addr, - uint8_t adv_sid, - base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}}; + body{[](uint8_t /* adv_addr_type */, const RawAddress& /* adv_addr */, + uint8_t /* adv_sid */, + base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}}; void operator()(uint8_t adv_addr_type, const RawAddress& adv_addr, uint8_t adv_sid, base::OnceCallback<void(uint8_t*, uint16_t)> cb) { @@ -92,7 +92,8 @@ extern struct btsnd_hci_ble_remove_device_from_periodic_advertiser_list // Params: uint16_t conn_handle // Return: void struct btsnd_hcic_accept_cis_req { - std::function<void(uint16_t conn_handle)> body{[](uint16_t conn_handle) {}}; + std::function<void(uint16_t conn_handle)> body{ + [](uint16_t /* conn_handle */) {}}; void operator()(uint16_t conn_handle) { body(conn_handle); }; }; extern struct btsnd_hcic_accept_cis_req btsnd_hcic_accept_cis_req; @@ -103,8 +104,9 @@ extern struct btsnd_hcic_accept_cis_req btsnd_hcic_accept_cis_req; struct btsnd_hcic_ble_add_device_resolving_list { std::function<void(uint8_t addr_type_peer, const RawAddress& bda_peer, const Octet16& irk_peer, const Octet16& irk_local)> - body{[](uint8_t addr_type_peer, const RawAddress& bda_peer, - const Octet16& irk_peer, const Octet16& irk_local) {}}; + body{[](uint8_t /* addr_type_peer */, const RawAddress& /* bda_peer */, + const Octet16& /* irk_peer */, + const Octet16& /* irk_local */) {}}; void operator()(uint8_t addr_type_peer, const RawAddress& bda_peer, const Octet16& irk_peer, const Octet16& irk_local) { body(addr_type_peer, bda_peer, irk_peer, irk_local); @@ -128,7 +130,7 @@ extern struct btsnd_hcic_ble_clear_resolving_list // Return: void struct btsnd_hcic_ble_enh_rx_test { std::function<void(uint8_t rx_chan, uint8_t phy, uint8_t mod_index)> body{ - [](uint8_t rx_chan, uint8_t phy, uint8_t mod_index) {}}; + [](uint8_t /* rx_chan */, uint8_t /* phy */, uint8_t /* mod_index */) {}}; void operator()(uint8_t rx_chan, uint8_t phy, uint8_t mod_index) { body(rx_chan, phy, mod_index); }; @@ -141,8 +143,8 @@ extern struct btsnd_hcic_ble_enh_rx_test btsnd_hcic_ble_enh_rx_test; struct btsnd_hcic_ble_enh_tx_test { std::function<void(uint8_t tx_chan, uint8_t data_len, uint8_t payload, uint8_t phy)> - body{[](uint8_t tx_chan, uint8_t data_len, uint8_t payload, uint8_t phy) { - }}; + body{[](uint8_t /* tx_chan */, uint8_t /* data_len */, + uint8_t /* payload */, uint8_t /* phy */) {}}; void operator()(uint8_t tx_chan, uint8_t data_len, uint8_t payload, uint8_t phy) { body(tx_chan, data_len, payload, phy); @@ -154,7 +156,7 @@ extern struct btsnd_hcic_ble_enh_tx_test btsnd_hcic_ble_enh_tx_test; // Params: uint16_t handle // Return: void struct btsnd_hcic_ble_ltk_req_neg_reply { - std::function<void(uint16_t handle)> body{[](uint16_t handle) {}}; + std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) {}}; void operator()(uint16_t handle) { body(handle); }; }; extern struct btsnd_hcic_ble_ltk_req_neg_reply btsnd_hcic_ble_ltk_req_neg_reply; @@ -164,7 +166,7 @@ extern struct btsnd_hcic_ble_ltk_req_neg_reply btsnd_hcic_ble_ltk_req_neg_reply; // Return: void struct btsnd_hcic_ble_ltk_req_reply { std::function<void(uint16_t handle, const Octet16& ltk)> body{ - [](uint16_t handle, const Octet16& ltk) {}}; + [](uint16_t /* handle */, const Octet16& /* ltk */) {}}; void operator()(uint16_t handle, const Octet16& ltk) { body(handle, ltk); }; }; extern struct btsnd_hcic_ble_ltk_req_reply btsnd_hcic_ble_ltk_req_reply; @@ -177,9 +179,10 @@ struct btsnd_hcic_ble_periodic_advertising_create_sync { std::function<void(uint8_t options, uint8_t adv_sid, uint8_t adv_addr_type, const RawAddress& adv_addr, uint16_t skip_num, uint16_t sync_timeout, uint8_t sync_cte_type)> - body{[](uint8_t options, uint8_t adv_sid, uint8_t adv_addr_type, - const RawAddress& adv_addr, uint16_t skip_num, - uint16_t sync_timeout, uint8_t sync_cte_type) {}}; + body{[](uint8_t /* options */, uint8_t /* adv_sid */, + uint8_t /* adv_addr_type */, const RawAddress& /* adv_addr */, + uint16_t /* skip_num */, uint16_t /* sync_timeout */, + uint8_t /* sync_cte_type */) {}}; void operator()(uint8_t options, uint8_t adv_sid, uint8_t adv_addr_type, const RawAddress& adv_addr, uint16_t skip_num, uint16_t sync_timeout, uint8_t sync_cte_type) { @@ -195,7 +198,7 @@ extern struct btsnd_hcic_ble_periodic_advertising_create_sync // Return: void struct btsnd_hcic_ble_periodic_advertising_create_sync_cancel { std::function<void(base::OnceCallback<void(uint8_t*, uint16_t)>)> body{ - [](base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}}; + [](base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}}; void operator()(base::OnceCallback<void(uint8_t*, uint16_t)> cb) { body(std::move(cb)); }; @@ -209,8 +212,9 @@ extern struct btsnd_hcic_ble_periodic_advertising_create_sync_cancel struct btsnd_hcic_ble_periodic_advertising_set_info_transfer { std::function<void(uint16_t, uint16_t, uint8_t, base::OnceCallback<void(uint8_t*, uint16_t)>)> - body{[](uint16_t conn_handle, uint16_t service_data, uint8_t adv_handle, - base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}}; + body{[](uint16_t /* conn_handle */, uint16_t /* service_data */, + uint8_t /* adv_handle */, + base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}}; void operator()(uint16_t conn_handle, uint16_t service_data, uint8_t adv_handle, base::OnceCallback<void(uint8_t*, uint16_t)> cb) { @@ -226,8 +230,9 @@ extern struct btsnd_hcic_ble_periodic_advertising_set_info_transfer struct btsnd_hcic_ble_periodic_advertising_sync_transfer { std::function<void(uint16_t, uint16_t, uint16_t, base::OnceCallback<void(uint8_t*, uint16_t)>)> - body{[](uint16_t conn_handle, uint16_t service_data, uint16_t sync_handle, - base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}}; + body{[](uint16_t /* conn_handle */, uint16_t /* service_data */, + uint16_t /* sync_handle */, + base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}}; void operator()(uint16_t conn_handle, uint16_t service_data, uint16_t sync_handle, base::OnceCallback<void(uint8_t*, uint16_t)> cb) { @@ -242,8 +247,8 @@ extern struct btsnd_hcic_ble_periodic_advertising_sync_transfer // Return: void struct btsnd_hcic_ble_periodic_advertising_terminate_sync { std::function<void(uint16_t, base::OnceCallback<void(uint8_t*, uint16_t)>)> - body{[](uint16_t sync_handle, - base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}}; + body{[](uint16_t /* sync_handle */, + base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}}; void operator()(uint16_t sync_handle, base::OnceCallback<void(uint8_t*, uint16_t)> cb) { body(sync_handle, std::move(cb)); @@ -257,7 +262,7 @@ extern struct btsnd_hcic_ble_periodic_advertising_terminate_sync // Return: void struct btsnd_hcic_ble_rand { std::function<void(base::Callback<void(BT_OCTET8)>)> body{ - [](base::Callback<void(BT_OCTET8)> cb) {}}; + [](base::Callback<void(BT_OCTET8)> /* cb */) {}}; void operator()(base::Callback<void(BT_OCTET8)> cb) { body(std::move(cb)); }; }; extern struct btsnd_hcic_ble_rand btsnd_hcic_ble_rand; @@ -267,7 +272,7 @@ extern struct btsnd_hcic_ble_rand btsnd_hcic_ble_rand; // Return: void struct btsnd_hcic_ble_rc_param_req_neg_reply { std::function<void(uint16_t handle, uint8_t reason)> body{ - [](uint16_t handle, uint8_t reason) {}}; + [](uint16_t /* handle */, uint8_t /* reason */) {}}; void operator()(uint16_t handle, uint8_t reason) { body(handle, reason); }; }; extern struct btsnd_hcic_ble_rc_param_req_neg_reply @@ -282,9 +287,10 @@ struct btsnd_hcic_ble_rc_param_req_reply { uint16_t conn_int_max, uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len, uint16_t max_ce_len)> - body{[](uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max, - uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len, - uint16_t max_ce_len) {}}; + body{[](uint16_t /* handle */, uint16_t /* conn_int_min */, + uint16_t /* conn_int_max */, uint16_t /* conn_latency */, + uint16_t /* conn_timeout */, uint16_t /* min_ce_len */, + uint16_t /* max_ce_len */) {}}; void operator()(uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max, uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len, uint16_t max_ce_len) { @@ -309,7 +315,7 @@ extern struct btsnd_hcic_ble_read_adv_chnl_tx_power // Params: uint16_t handle // Return: void struct btsnd_hcic_ble_read_remote_feat { - std::function<void(uint16_t handle)> body{[](uint16_t handle) {}}; + std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) {}}; void operator()(uint16_t handle) { body(handle); }; }; extern struct btsnd_hcic_ble_read_remote_feat btsnd_hcic_ble_read_remote_feat; @@ -319,7 +325,7 @@ extern struct btsnd_hcic_ble_read_remote_feat btsnd_hcic_ble_read_remote_feat; // Return: void struct btsnd_hcic_ble_read_resolvable_addr_peer { std::function<void(uint8_t addr_type_peer, const RawAddress& bda_peer)> body{ - [](uint8_t addr_type_peer, const RawAddress& bda_peer) {}}; + [](uint8_t /* addr_type_peer */, const RawAddress& /* bda_peer */) {}}; void operator()(uint8_t addr_type_peer, const RawAddress& bda_peer) { body(addr_type_peer, bda_peer); }; @@ -331,7 +337,7 @@ extern struct btsnd_hcic_ble_read_resolvable_addr_peer // Params: uint8_t rx_freq // Return: void struct btsnd_hcic_ble_receiver_test { - std::function<void(uint8_t rx_freq)> body{[](uint8_t rx_freq) {}}; + std::function<void(uint8_t rx_freq)> body{[](uint8_t /* rx_freq */) {}}; void operator()(uint8_t rx_freq) { body(rx_freq); }; }; extern struct btsnd_hcic_ble_receiver_test btsnd_hcic_ble_receiver_test; @@ -341,7 +347,7 @@ extern struct btsnd_hcic_ble_receiver_test btsnd_hcic_ble_receiver_test; // Return: void struct btsnd_hcic_ble_rm_device_resolving_list { std::function<void(uint8_t addr_type_peer, const RawAddress& bda_peer)> body{ - [](uint8_t addr_type_peer, const RawAddress& bda_peer) {}}; + [](uint8_t /* addr_type_peer */, const RawAddress& /* bda_peer */) {}}; void operator()(uint8_t addr_type_peer, const RawAddress& bda_peer) { body(addr_type_peer, bda_peer); }; @@ -354,7 +360,7 @@ extern struct btsnd_hcic_ble_rm_device_resolving_list // Return: void struct btsnd_hcic_ble_set_adv_data { std::function<void(uint8_t data_len, uint8_t* p_data)> body{ - [](uint8_t data_len, uint8_t* p_data) {}}; + [](uint8_t /* data_len */, uint8_t* /* p_data */) {}}; void operator()(uint8_t data_len, uint8_t* p_data) { body(data_len, p_data); }; @@ -365,7 +371,7 @@ extern struct btsnd_hcic_ble_set_adv_data btsnd_hcic_ble_set_adv_data; // Params: uint8_t adv_enable // Return: void struct btsnd_hcic_ble_set_adv_enable { - std::function<void(uint8_t adv_enable)> body{[](uint8_t adv_enable) {}}; + std::function<void(uint8_t adv_enable)> body{[](uint8_t /* adv_enable */) {}}; void operator()(uint8_t adv_enable) { body(adv_enable); }; }; extern struct btsnd_hcic_ble_set_adv_enable btsnd_hcic_ble_set_adv_enable; @@ -376,7 +382,8 @@ extern struct btsnd_hcic_ble_set_adv_enable btsnd_hcic_ble_set_adv_enable; struct btsnd_hcic_ble_set_data_length { std::function<void(uint16_t conn_handle, uint16_t tx_octets, uint16_t tx_time)> - body{[](uint16_t conn_handle, uint16_t tx_octets, uint16_t tx_time) {}}; + body{[](uint16_t /* conn_handle */, uint16_t /* tx_octets */, + uint16_t /* tx_time */) {}}; void operator()(uint16_t conn_handle, uint16_t tx_octets, uint16_t tx_time) { body(conn_handle, tx_octets, tx_time); }; @@ -390,9 +397,10 @@ extern struct btsnd_hcic_ble_set_data_length btsnd_hcic_ble_set_data_length; struct btsnd_hcic_ble_set_default_periodic_advertising_sync_transfer_params { std::function<void(uint16_t, uint8_t, uint16_t, uint16_t, uint8_t, base::OnceCallback<void(uint8_t*, uint16_t)>)> - body{[](uint16_t conn_handle, uint8_t mode, uint16_t skip, - uint16_t sync_timeout, uint8_t cte_type, - base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}}; + body{[](uint16_t /* conn_handle */, uint8_t /* mode */, + uint16_t /* skip */, uint16_t /* sync_timeout */, + uint8_t /* cte_type */, + base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}}; void operator()(uint16_t conn_handle, uint8_t mode, uint16_t skip, uint16_t sync_timeout, uint8_t cte_type, base::OnceCallback<void(uint8_t*, uint16_t)> cb) { @@ -409,8 +417,8 @@ extern struct struct btsnd_hcic_ble_set_extended_scan_enable { std::function<void(uint8_t enable, uint8_t filter_duplicates, uint16_t duration, uint16_t period)> - body{[](uint8_t enable, uint8_t filter_duplicates, uint16_t duration, - uint16_t period) {}}; + body{[](uint8_t /* enable */, uint8_t /* filter_duplicates */, + uint16_t /* duration */, uint16_t /* period */) {}}; void operator()(uint8_t enable, uint8_t filter_duplicates, uint16_t duration, uint16_t period) { body(enable, filter_duplicates, duration, period); @@ -425,8 +433,9 @@ extern struct btsnd_hcic_ble_set_extended_scan_enable struct btsnd_hcic_ble_set_extended_scan_params { std::function<void(uint8_t own_address_type, uint8_t scanning_filter_policy, uint8_t scanning_phys, scanning_phy_cfg* phy_cfg)> - body{[](uint8_t own_address_type, uint8_t scanning_filter_policy, - uint8_t scanning_phys, scanning_phy_cfg* phy_cfg) {}}; + body{[](uint8_t /* own_address_type */, + uint8_t /* scanning_filter_policy */, uint8_t /* scanning_phys */, + scanning_phy_cfg* /* phy_cfg */) {}}; void operator()(uint8_t own_address_type, uint8_t scanning_filter_policy, uint8_t scanning_phys, scanning_phy_cfg* phy_cfg) { body(own_address_type, scanning_filter_policy, scanning_phys, phy_cfg); @@ -441,8 +450,8 @@ extern struct btsnd_hcic_ble_set_extended_scan_params struct btsnd_hcic_ble_set_periodic_advertising_receive_enable { std::function<void(uint16_t, bool, base::OnceCallback<void(uint8_t*, uint16_t)>)> - body{[](uint16_t sync_handle, bool enable, - base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}}; + body{[](uint16_t /* sync_handle */, bool /* enable */, + base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}}; void operator()(uint16_t sync_handle, bool enable, base::OnceCallback<void(uint8_t*, uint16_t)> cb) { body(sync_handle, enable, std::move(cb)); @@ -458,9 +467,10 @@ extern struct btsnd_hcic_ble_set_periodic_advertising_receive_enable struct btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params { std::function<void(uint16_t, uint8_t, uint16_t, uint16_t, uint8_t, base::OnceCallback<void(uint8_t*, uint16_t)>)> - body{[](uint16_t conn_handle, uint8_t mode, uint16_t skip, - uint16_t sync_timeout, uint8_t cte_type, - base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}}; + body{[](uint16_t /* conn_handle */, uint8_t /* mode */, + uint16_t /* skip */, uint16_t /* sync_timeout */, + uint8_t /* cte_type */, + base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}}; void operator()(uint16_t conn_handle, uint8_t mode, uint16_t skip, uint16_t sync_timeout, uint8_t cte_type, base::OnceCallback<void(uint8_t*, uint16_t)> cb) { @@ -476,8 +486,8 @@ extern struct btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params 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) {}}; + 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); @@ -489,7 +499,8 @@ extern struct btsnd_hcic_ble_set_privacy_mode btsnd_hcic_ble_set_privacy_mode; // Params: uint16_t rpa_timout // Return: void struct btsnd_hcic_ble_set_rand_priv_addr_timeout { - std::function<void(uint16_t rpa_timout)> body{[](uint16_t rpa_timout) {}}; + std::function<void(uint16_t rpa_timout)> body{ + [](uint16_t /* rpa_timout */) {}}; void operator()(uint16_t rpa_timout) { body(rpa_timout); }; }; extern struct btsnd_hcic_ble_set_rand_priv_addr_timeout @@ -500,7 +511,7 @@ extern struct btsnd_hcic_ble_set_rand_priv_addr_timeout // Return: void struct btsnd_hcic_ble_set_scan_enable { std::function<void(uint8_t scan_enable, uint8_t duplicate)> body{ - [](uint8_t scan_enable, uint8_t duplicate) {}}; + [](uint8_t /* scan_enable */, uint8_t /* duplicate */) {}}; void operator()(uint8_t scan_enable, uint8_t duplicate) { body(scan_enable, duplicate); }; @@ -513,8 +524,9 @@ extern struct btsnd_hcic_ble_set_scan_enable btsnd_hcic_ble_set_scan_enable; struct btsnd_hcic_ble_set_scan_params { std::function<void(uint8_t scan_type, uint16_t scan_int, uint16_t scan_win, uint8_t addr_type_own, uint8_t scan_filter_policy)> - body{[](uint8_t scan_type, uint16_t scan_int, uint16_t scan_win, - uint8_t addr_type_own, uint8_t scan_filter_policy) {}}; + body{[](uint8_t /* scan_type */, uint16_t /* scan_int */, + uint16_t /* scan_win */, uint8_t /* addr_type_own */, + uint8_t /* scan_filter_policy */) {}}; void operator()(uint8_t scan_type, uint16_t scan_int, uint16_t scan_win, uint8_t addr_type_own, uint8_t scan_filter_policy) { body(scan_type, scan_int, scan_win, addr_type_own, scan_filter_policy); @@ -528,8 +540,8 @@ extern struct btsnd_hcic_ble_set_scan_params btsnd_hcic_ble_set_scan_params; struct btsnd_hcic_ble_start_enc { std::function<void(uint16_t handle, uint8_t rand[HCIC_BLE_RAND_DI_SIZE], uint16_t ediv, const Octet16& ltk)> - body{[](uint16_t handle, uint8_t rand[HCIC_BLE_RAND_DI_SIZE], - uint16_t ediv, const Octet16& ltk) {}}; + body{[](uint16_t /* handle */, uint8_t[HCIC_BLE_RAND_DI_SIZE] /* rand */, + uint16_t /* ediv */, const Octet16& /* ltk */) {}}; void operator()(uint16_t handle, uint8_t rand[HCIC_BLE_RAND_DI_SIZE], uint16_t ediv, const Octet16& ltk) { body(handle, rand, ediv, ltk); @@ -551,7 +563,8 @@ extern struct btsnd_hcic_ble_test_end btsnd_hcic_ble_test_end; // Return: void struct btsnd_hcic_ble_transmitter_test { std::function<void(uint8_t tx_freq, uint8_t test_data_len, uint8_t payload)> - body{[](uint8_t tx_freq, uint8_t test_data_len, uint8_t payload) {}}; + body{[](uint8_t /* tx_freq */, uint8_t /* test_data_len */, + uint8_t /* payload */) {}}; void operator()(uint8_t tx_freq, uint8_t test_data_len, uint8_t payload) { body(tx_freq, test_data_len, payload); }; @@ -567,9 +580,10 @@ struct btsnd_hcic_ble_upd_ll_conn_params { uint16_t conn_int_max, uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len, uint16_t max_ce_len)> - body{[](uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max, - uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len, - uint16_t max_ce_len) {}}; + body{[](uint16_t /* handle */, uint16_t /* conn_int_min */, + uint16_t /* conn_int_max */, uint16_t /* conn_latency */, + uint16_t /* conn_timeout */, uint16_t /* min_ce_len */, + uint16_t /* max_ce_len */) {}}; void operator()(uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max, uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len, uint16_t max_ce_len) { @@ -589,10 +603,11 @@ struct btsnd_hcic_ble_write_adv_params { uint8_t adv_type, tBLE_ADDR_TYPE addr_type_own, tBLE_ADDR_TYPE addr_type_dir, const RawAddress& direct_bda, uint8_t channel_map, uint8_t adv_filter_policy)> - body{[](uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type, - tBLE_ADDR_TYPE addr_type_own, tBLE_ADDR_TYPE addr_type_dir, - const RawAddress& direct_bda, uint8_t channel_map, - uint8_t adv_filter_policy) {}}; + body{[](uint16_t /* adv_int_min */, uint16_t /* adv_int_max */, + uint8_t /* adv_type */, tBLE_ADDR_TYPE /* addr_type_own */, + tBLE_ADDR_TYPE /* addr_type_dir */, + const RawAddress& /* direct_bda */, uint8_t /* channel_map */, + uint8_t /* adv_filter_policy */) {}}; void operator()(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type, tBLE_ADDR_TYPE addr_type_own, tBLE_ADDR_TYPE addr_type_dir, const RawAddress& direct_bda, uint8_t channel_map, @@ -614,11 +629,12 @@ struct btsnd_hcic_create_big { uint16_t transport_latency, uint8_t rtn, uint8_t phy, uint8_t packing, uint8_t framing, uint8_t enc, std::array<uint8_t, 16> bcst_code)> - body{[](uint8_t big_handle, uint8_t adv_handle, uint8_t num_bis, - uint32_t sdu_itv, uint16_t max_sdu_size, - uint16_t transport_latency, uint8_t rtn, uint8_t phy, - uint8_t packing, uint8_t framing, uint8_t enc, - std::array<uint8_t, 16> bcst_code) {}}; + body{[](uint8_t /* big_handle */, uint8_t /* adv_handle */, + uint8_t /* num_bis */, uint32_t /* sdu_itv */, + uint16_t /* max_sdu_size */, uint16_t /* transport_latency */, + uint8_t /* rtn */, uint8_t /* phy */, uint8_t /* packing */, + uint8_t /* framing */, uint8_t /* enc */, + std::array<uint8_t, 16> /* bcst_code */) {}}; void operator()(uint8_t big_handle, uint8_t adv_handle, uint8_t num_bis, uint32_t sdu_itv, uint16_t max_sdu_size, uint16_t transport_latency, uint8_t rtn, uint8_t phy, @@ -636,8 +652,8 @@ extern struct btsnd_hcic_create_big btsnd_hcic_create_big; struct btsnd_hcic_create_cis { std::function<void(uint8_t, const EXT_CIS_CREATE_CFG*, base::OnceCallback<void(uint8_t*, uint16_t)>)> - body{[](uint8_t num_cis, const EXT_CIS_CREATE_CFG* cis_cfg, - base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}}; + body{[](uint8_t /* num_cis */, const EXT_CIS_CREATE_CFG* /* cis_cfg */, + base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}}; void operator()(uint8_t num_cis, const EXT_CIS_CREATE_CFG* cis_cfg, base::OnceCallback<void(uint8_t*, uint16_t)> cb) { body(num_cis, cis_cfg, std::move(cb)); @@ -650,7 +666,7 @@ extern struct btsnd_hcic_create_cis btsnd_hcic_create_cis; // Return: void struct btsnd_hcic_read_iso_link_quality { std::function<void(uint16_t, base::OnceCallback<void(uint8_t*, uint16_t)>)> - body{[](uint16_t iso_handle, + body{[](uint16_t /* iso_handle */, base::OnceCallback<void(uint8_t*, uint16_t)>) {}}; void operator()(uint16_t iso_handle, base::OnceCallback<void(uint8_t*, uint16_t)> cb) { @@ -665,8 +681,8 @@ extern struct btsnd_hcic_read_iso_link_quality btsnd_hcic_read_iso_link_quality; struct btsnd_hcic_rej_cis_req { std::function<void(uint16_t, uint8_t, base::OnceCallback<void(uint8_t*, uint16_t)>)> - body{[](uint16_t conn_handle, uint8_t reason, - base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}}; + body{[](uint16_t /* conn_handle */, uint8_t /* reason */, + base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}}; void operator()(uint16_t conn_handle, uint8_t reason, base::OnceCallback<void(uint8_t*, uint16_t)> cb) { body(conn_handle, reason, std::move(cb)); @@ -679,8 +695,8 @@ extern struct btsnd_hcic_rej_cis_req btsnd_hcic_rej_cis_req; // Return: void struct btsnd_hcic_remove_cig { std::function<void(uint8_t, base::OnceCallback<void(uint8_t*, uint16_t)>)> - body{[](uint8_t cig_id, base::OnceCallback<void(uint8_t*, uint16_t)> cb) { - }}; + body{[](uint8_t /* cig_id */, + base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}}; void operator()(uint8_t cig_id, base::OnceCallback<void(uint8_t*, uint16_t)> cb) { body(cig_id, std::move(cb)); @@ -694,8 +710,8 @@ extern struct btsnd_hcic_remove_cig btsnd_hcic_remove_cig; struct btsnd_hcic_remove_iso_data_path { std::function<void(uint16_t, uint8_t, base::OnceCallback<void(uint8_t*, uint16_t)>)> - body{[](uint16_t iso_handle, uint8_t data_path_dir, - base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}}; + body{[](uint16_t /* iso_handle */, uint8_t /* data_path_dir */, + base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}}; void operator()(uint16_t iso_handle, uint8_t data_path_dir, base::OnceCallback<void(uint8_t*, uint16_t)> cb) { body(iso_handle, data_path_dir, std::move(cb)); @@ -707,7 +723,7 @@ extern struct btsnd_hcic_remove_iso_data_path btsnd_hcic_remove_iso_data_path; // Params: uint16_t conn_handle // Return: void struct btsnd_hcic_req_peer_sca { - std::function<void(uint16_t)> body{[](uint16_t conn_handle) {}}; + std::function<void(uint16_t)> body{[](uint16_t /* conn_handle */) {}}; void operator()(uint16_t conn_handle) { body(conn_handle); }; }; extern struct btsnd_hcic_req_peer_sca btsnd_hcic_req_peer_sca; @@ -721,11 +737,13 @@ struct btsnd_hcic_set_cig_params { std::function<void(uint8_t, uint32_t, uint32_t, uint8_t, uint8_t, uint8_t, uint16_t, uint16_t, uint8_t, const EXT_CIS_CFG*, base::OnceCallback<void(uint8_t*, uint16_t)>)> - body{[](uint8_t cig_id, uint32_t sdu_itv_mtos, uint32_t sdu_itv_stom, - uint8_t sca, uint8_t packing, uint8_t framing, - uint16_t max_trans_lat_stom, uint16_t max_trans_lat_mtos, - uint8_t cis_cnt, const EXT_CIS_CFG* cis_cfg, - base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}}; + body{[](uint8_t /* cig_id */, uint32_t /* sdu_itv_mtos */, + uint32_t /* sdu_itv_stom */, uint8_t /* sca */, + uint8_t /* packing */, uint8_t /* framing */, + uint16_t /* max_trans_lat_stom */, + uint16_t /* max_trans_lat_mtos */, uint8_t /* cis_cnt */, + const EXT_CIS_CFG* /* cis_cfg */, + base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}}; void operator()(uint8_t cig_id, uint32_t sdu_itv_mtos, uint32_t sdu_itv_stom, uint8_t sca, uint8_t packing, uint8_t framing, uint16_t max_trans_lat_stom, uint16_t max_trans_lat_mtos, @@ -747,11 +765,12 @@ struct btsnd_hcic_setup_iso_data_path { std::function<void(uint16_t, uint8_t, uint8_t, uint8_t, uint16_t, uint16_t, uint32_t, std::vector<uint8_t>, base::OnceCallback<void(uint8_t*, uint16_t)>)> - body{[](uint16_t iso_handle, uint8_t data_path_dir, uint8_t data_path_id, - uint8_t codec_id_format, uint16_t codec_id_company, - uint16_t codec_id_vendor, uint32_t controller_delay, - std::vector<uint8_t> codec_conf, - base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}}; + body{[](uint16_t /* iso_handle */, uint8_t /* data_path_dir */, + uint8_t /* data_path_id */, uint8_t /* codec_id_format */, + uint16_t /* codec_id_company */, uint16_t /* codec_id_vendor */, + uint32_t /* controller_delay */, + std::vector<uint8_t> /* codec_conf */, + base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}}; void operator()(uint16_t iso_handle, uint8_t data_path_dir, uint8_t data_path_id, uint8_t codec_id_format, uint16_t codec_id_company, uint16_t codec_id_vendor, @@ -769,7 +788,7 @@ extern struct btsnd_hcic_setup_iso_data_path btsnd_hcic_setup_iso_data_path; // Return: void struct btsnd_hcic_term_big { std::function<void(uint8_t, uint8_t)> body{ - [](uint8_t big_handle, uint8_t reason) {}}; + [](uint8_t /* big_handle */, uint8_t /* reason */) {}}; void operator()(uint8_t big_handle, uint8_t reason) { body(big_handle, reason); }; diff --git a/system/test/mock/mock_stack_hcic_hcicmds.h b/system/test/mock/mock_stack_hcic_hcicmds.h index b0d5d3ef78..232a60f671 100644 --- a/system/test/mock/mock_stack_hcic_hcicmds.h +++ b/system/test/mock/mock_stack_hcic_hcicmds.h @@ -44,7 +44,7 @@ namespace stack_hcic_hcicmds { // Return: void struct btsnd_hcic_accept_conn { std::function<void(const RawAddress& dest, uint8_t role)> body{ - [](const RawAddress& dest, uint8_t role) {}}; + [](const RawAddress& /* dest */, uint8_t /* role */) {}}; void operator()(const RawAddress& dest, uint8_t role) { body(dest, role); }; }; extern struct btsnd_hcic_accept_conn btsnd_hcic_accept_conn; @@ -58,10 +58,11 @@ struct btsnd_hcic_accept_esco_conn { uint32_t receive_bandwidth, uint16_t max_latency, uint16_t content_fmt, uint8_t retrans_effort, uint16_t packet_types)> - body{[](const RawAddress& bd_addr, uint32_t transmit_bandwidth, - uint32_t receive_bandwidth, uint16_t max_latency, - uint16_t content_fmt, uint8_t retrans_effort, - uint16_t packet_types) {}}; + body{[](const RawAddress& /* bd_addr */, + uint32_t /* transmit_bandwidth */, + uint32_t /* receive_bandwidth */, uint16_t /* max_latency */, + uint16_t /* content_fmt */, uint8_t /* retrans_effort */, + uint16_t /* packet_types */) {}}; void operator()(const RawAddress& bd_addr, uint32_t transmit_bandwidth, uint32_t receive_bandwidth, uint16_t max_latency, uint16_t content_fmt, uint8_t retrans_effort, @@ -77,7 +78,7 @@ extern struct btsnd_hcic_accept_esco_conn btsnd_hcic_accept_esco_conn; // Return: void struct btsnd_hcic_add_SCO_conn { std::function<void(uint16_t handle, uint16_t packet_types)> body{ - [](uint16_t handle, uint16_t packet_types) {}}; + [](uint16_t /* handle */, uint16_t /* packet_types */) {}}; void operator()(uint16_t handle, uint16_t packet_types) { body(handle, packet_types); }; @@ -88,7 +89,7 @@ extern struct btsnd_hcic_add_SCO_conn btsnd_hcic_add_SCO_conn; // Params: uint16_t handle // Return: void struct btsnd_hcic_auth_request { - std::function<void(uint16_t handle)> body{[](uint16_t handle) {}}; + std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) {}}; void operator()(uint16_t handle) { body(handle); }; }; extern struct btsnd_hcic_auth_request btsnd_hcic_auth_request; @@ -97,7 +98,7 @@ extern struct btsnd_hcic_auth_request btsnd_hcic_auth_request; // Params: BD_NAME name // Return: void struct btsnd_hcic_change_name { - std::function<void(BD_NAME name)> body{[](BD_NAME name) {}}; + std::function<void(BD_NAME name)> body{[](BD_NAME /* name */) {}}; void operator()(BD_NAME name) { body(name); }; }; extern struct btsnd_hcic_change_name btsnd_hcic_change_name; @@ -107,7 +108,7 @@ extern struct btsnd_hcic_change_name btsnd_hcic_change_name; // Return: void struct btsnd_hcic_create_conn_cancel { std::function<void(const RawAddress& dest)> body{ - [](const RawAddress& dest) {}}; + [](const RawAddress& /* dest */) {}}; void operator()(const RawAddress& dest) { body(dest); }; }; extern struct btsnd_hcic_create_conn_cancel btsnd_hcic_create_conn_cancel; @@ -117,7 +118,7 @@ extern struct btsnd_hcic_create_conn_cancel btsnd_hcic_create_conn_cancel; // Return: void struct btsnd_hcic_delete_stored_key { std::function<void(const RawAddress& bd_addr, bool delete_all_flag)> body{ - [](const RawAddress& bd_addr, bool delete_all_flag) {}}; + [](const RawAddress& /* bd_addr */, bool /* delete_all_flag */) {}}; void operator()(const RawAddress& bd_addr, bool delete_all_flag) { body(bd_addr, delete_all_flag); }; @@ -138,7 +139,8 @@ extern struct btsnd_hcic_enable_test_mode btsnd_hcic_enable_test_mode; // Return: void struct btsnd_hcic_enhanced_accept_synchronous_connection { std::function<void(const RawAddress& bd_addr, enh_esco_params_t* p_params)> - body{[](const RawAddress& bd_addr, enh_esco_params_t* p_params) {}}; + body{[](const RawAddress& /* bd_addr */, + enh_esco_params_t* /* p_params */) {}}; void operator()(const RawAddress& bd_addr, enh_esco_params_t* p_params) { body(bd_addr, p_params); }; @@ -151,7 +153,7 @@ extern struct btsnd_hcic_enhanced_accept_synchronous_connection // Return: void struct btsnd_hcic_enhanced_flush { std::function<void(uint16_t handle, uint8_t packet_type)> body{ - [](uint16_t handle, uint8_t packet_type) {}}; + [](uint16_t /* handle */, uint8_t /* packet_type */) {}}; void operator()(uint16_t handle, uint8_t packet_type) { body(handle, packet_type); }; @@ -163,7 +165,7 @@ extern struct btsnd_hcic_enhanced_flush btsnd_hcic_enhanced_flush; // Return: void struct btsnd_hcic_enhanced_set_up_synchronous_connection { std::function<void(uint16_t conn_handle, enh_esco_params_t* p_params)> body{ - [](uint16_t conn_handle, enh_esco_params_t* p_params) {}}; + [](uint16_t /* conn_handle */, enh_esco_params_t* /* p_params */) {}}; void operator()(uint16_t conn_handle, enh_esco_params_t* p_params) { body(conn_handle, p_params); }; @@ -175,7 +177,7 @@ extern struct btsnd_hcic_enhanced_set_up_synchronous_connection // Params: uint16_t handle // Return: void struct btsnd_hcic_exit_park_mode { - std::function<void(uint16_t handle)> body{[](uint16_t handle) {}}; + std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) {}}; void operator()(uint16_t handle) { body(handle); }; }; extern struct btsnd_hcic_exit_park_mode btsnd_hcic_exit_park_mode; @@ -184,7 +186,7 @@ extern struct btsnd_hcic_exit_park_mode btsnd_hcic_exit_park_mode; // Params: uint16_t handle // Return: void struct btsnd_hcic_exit_sniff_mode { - std::function<void(uint16_t handle)> body{[](uint16_t handle) {}}; + std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) {}}; void operator()(uint16_t handle) { body(handle); }; }; extern struct btsnd_hcic_exit_sniff_mode btsnd_hcic_exit_sniff_mode; @@ -195,8 +197,8 @@ extern struct btsnd_hcic_exit_sniff_mode btsnd_hcic_exit_sniff_mode; struct btsnd_hcic_hold_mode { std::function<void(uint16_t handle, uint16_t max_hold_period, uint16_t min_hold_period)> - body{[](uint16_t handle, uint16_t max_hold_period, - uint16_t min_hold_period) {}}; + body{[](uint16_t /* handle */, uint16_t /* max_hold_period */, + uint16_t /* min_hold_period */) {}}; void operator()(uint16_t handle, uint16_t max_hold_period, uint16_t min_hold_period) { body(handle, max_hold_period, min_hold_period); @@ -209,7 +211,7 @@ extern struct btsnd_hcic_hold_mode btsnd_hcic_hold_mode; // Return: void struct btsnd_hcic_io_cap_req_neg_reply { std::function<void(const RawAddress& bd_addr, uint8_t err_code)> body{ - [](const RawAddress& bd_addr, uint8_t err_code) {}}; + [](const RawAddress& /* bd_addr */, uint8_t /* err_code */) {}}; void operator()(const RawAddress& bd_addr, uint8_t err_code) { body(bd_addr, err_code); }; @@ -222,8 +224,8 @@ extern struct btsnd_hcic_io_cap_req_neg_reply btsnd_hcic_io_cap_req_neg_reply; struct btsnd_hcic_io_cap_req_reply { std::function<void(const RawAddress& bd_addr, uint8_t capability, uint8_t oob_present, uint8_t auth_req)> - body{[](const RawAddress& bd_addr, uint8_t capability, - uint8_t oob_present, uint8_t auth_req) {}}; + body{[](const RawAddress& /* bd_addr */, uint8_t /* capability */, + uint8_t /* oob_present */, uint8_t /* auth_req */) {}}; void operator()(const RawAddress& bd_addr, uint8_t capability, uint8_t oob_present, uint8_t auth_req) { body(bd_addr, capability, oob_present, auth_req); @@ -236,7 +238,7 @@ extern struct btsnd_hcic_io_cap_req_reply btsnd_hcic_io_cap_req_reply; // Return: void struct btsnd_hcic_link_key_neg_reply { std::function<void(const RawAddress& bd_addr)> body{ - [](const RawAddress& bd_addr) {}}; + [](const RawAddress& /* bd_addr */) {}}; void operator()(const RawAddress& bd_addr) { body(bd_addr); }; }; extern struct btsnd_hcic_link_key_neg_reply btsnd_hcic_link_key_neg_reply; @@ -246,7 +248,7 @@ extern struct btsnd_hcic_link_key_neg_reply btsnd_hcic_link_key_neg_reply; // Return: void struct btsnd_hcic_link_key_req_reply { std::function<void(const RawAddress& bd_addr, const LinkKey& link_key)> body{ - [](const RawAddress& bd_addr, const LinkKey& link_key) {}}; + [](const RawAddress& /* bd_addr */, const LinkKey& /* link_key */) {}}; void operator()(const RawAddress& bd_addr, const LinkKey& link_key) { body(bd_addr, link_key); }; @@ -259,8 +261,8 @@ extern struct btsnd_hcic_link_key_req_reply btsnd_hcic_link_key_req_reply; struct btsnd_hcic_park_mode { std::function<void(uint16_t handle, uint16_t beacon_max_interval, uint16_t beacon_min_interval)> - body{[](uint16_t handle, uint16_t beacon_max_interval, - uint16_t beacon_min_interval) {}}; + body{[](uint16_t /* handle */, uint16_t /* beacon_max_interval */, + uint16_t /* beacon_min_interval */) {}}; void operator()(uint16_t handle, uint16_t beacon_max_interval, uint16_t beacon_min_interval) { body(handle, beacon_max_interval, beacon_min_interval); @@ -273,7 +275,7 @@ extern struct btsnd_hcic_park_mode btsnd_hcic_park_mode; // Return: void struct btsnd_hcic_pin_code_neg_reply { std::function<void(const RawAddress& bd_addr)> body{ - [](const RawAddress& bd_addr) {}}; + [](const RawAddress& /* bd_addr */) {}}; void operator()(const RawAddress& bd_addr) { body(bd_addr); }; }; extern struct btsnd_hcic_pin_code_neg_reply btsnd_hcic_pin_code_neg_reply; @@ -284,8 +286,8 @@ extern struct btsnd_hcic_pin_code_neg_reply btsnd_hcic_pin_code_neg_reply; struct btsnd_hcic_pin_code_req_reply { std::function<void(const RawAddress& bd_addr, uint8_t pin_code_len, PIN_CODE pin_code)> - body{[](const RawAddress& bd_addr, uint8_t pin_code_len, - PIN_CODE pin_code) {}}; + body{[](const RawAddress& /* bd_addr */, uint8_t /* pin_code_len */, + PIN_CODE /* pin_code */) {}}; void operator()(const RawAddress& bd_addr, uint8_t pin_code_len, PIN_CODE pin_code) { body(bd_addr, pin_code_len, pin_code); @@ -298,7 +300,7 @@ extern struct btsnd_hcic_pin_code_req_reply btsnd_hcic_pin_code_req_reply; // Return: void struct btsnd_hcic_read_encryption_key_size { std::function<void(uint16_t handle, ReadEncKeySizeCb cb)> body{ - [](uint16_t handle, ReadEncKeySizeCb cb) {}}; + [](uint16_t /* handle */, ReadEncKeySizeCb /* cb */) {}}; void operator()(uint16_t handle, ReadEncKeySizeCb cb) { body(handle, std::move(cb)); }; @@ -310,7 +312,7 @@ extern struct btsnd_hcic_read_encryption_key_size // Params: uint16_t handle // Return: void struct btsnd_hcic_read_failed_contact_counter { - std::function<void(uint16_t handle)> body{[](uint16_t handle) {}}; + std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) {}}; void operator()(uint16_t handle) { body(handle); }; }; extern struct btsnd_hcic_read_failed_contact_counter @@ -338,7 +340,7 @@ extern struct btsnd_hcic_read_name btsnd_hcic_read_name; // Params: uint16_t handle // Return: void struct btsnd_hcic_read_rmt_clk_offset { - std::function<void(uint16_t handle)> body{[](uint16_t handle) {}}; + std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) {}}; void operator()(uint16_t handle) { body(handle); }; }; extern struct btsnd_hcic_read_rmt_clk_offset btsnd_hcic_read_rmt_clk_offset; @@ -347,7 +349,7 @@ extern struct btsnd_hcic_read_rmt_clk_offset btsnd_hcic_read_rmt_clk_offset; // Params: uint16_t handle // Return: void struct btsnd_hcic_read_rssi { - std::function<void(uint16_t handle)> body{[](uint16_t handle) {}}; + std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) {}}; void operator()(uint16_t handle) { body(handle); }; }; extern struct btsnd_hcic_read_rssi btsnd_hcic_read_rssi; @@ -357,7 +359,7 @@ extern struct btsnd_hcic_read_rssi btsnd_hcic_read_rssi; // Return: void struct btsnd_hcic_read_tx_power { std::function<void(uint16_t handle, uint8_t type)> body{ - [](uint16_t handle, uint8_t type) {}}; + [](uint16_t /* handle */, uint8_t /* type */) {}}; void operator()(uint16_t handle, uint8_t type) { body(handle, type); }; }; extern struct btsnd_hcic_read_tx_power btsnd_hcic_read_tx_power; @@ -367,7 +369,7 @@ extern struct btsnd_hcic_read_tx_power btsnd_hcic_read_tx_power; // Return: void struct btsnd_hcic_reject_conn { std::function<void(const RawAddress& dest, uint8_t reason)> body{ - [](const RawAddress& dest, uint8_t reason) {}}; + [](const RawAddress& /* dest */, uint8_t /* reason */) {}}; void operator()(const RawAddress& dest, uint8_t reason) { body(dest, reason); }; @@ -379,7 +381,7 @@ extern struct btsnd_hcic_reject_conn btsnd_hcic_reject_conn; // Return: void struct btsnd_hcic_reject_esco_conn { std::function<void(const RawAddress& bd_addr, uint8_t reason)> body{ - [](const RawAddress& bd_addr, uint8_t reason) {}}; + [](const RawAddress& /* bd_addr */, uint8_t /* reason */) {}}; void operator()(const RawAddress& bd_addr, uint8_t reason) { body(bd_addr, reason); }; @@ -391,7 +393,7 @@ extern struct btsnd_hcic_reject_esco_conn btsnd_hcic_reject_esco_conn; // Return: void struct btsnd_hcic_rem_oob_neg_reply { std::function<void(const RawAddress& bd_addr)> body{ - [](const RawAddress& bd_addr) {}}; + [](const RawAddress& /* bd_addr */) {}}; void operator()(const RawAddress& bd_addr) { body(bd_addr); }; }; extern struct btsnd_hcic_rem_oob_neg_reply btsnd_hcic_rem_oob_neg_reply; @@ -402,8 +404,8 @@ extern struct btsnd_hcic_rem_oob_neg_reply btsnd_hcic_rem_oob_neg_reply; struct btsnd_hcic_rem_oob_reply { std::function<void(const RawAddress& bd_addr, const Octet16& c, const Octet16& r)> - body{ - [](const RawAddress& bd_addr, const Octet16& c, const Octet16& r) {}}; + body{[](const RawAddress& /* bd_addr */, const Octet16& /* c */, + const Octet16& /* r */) {}}; void operator()(const RawAddress& bd_addr, const Octet16& c, const Octet16& r) { body(bd_addr, c, r); @@ -416,7 +418,7 @@ extern struct btsnd_hcic_rem_oob_reply btsnd_hcic_rem_oob_reply; // Return: void struct btsnd_hcic_rmt_ext_features { std::function<void(uint16_t handle, uint8_t page_num)> body{ - [](uint16_t handle, uint8_t page_num) {}}; + [](uint16_t /* handle */, uint8_t /* page_num */) {}}; void operator()(uint16_t handle, uint8_t page_num) { body(handle, page_num); }; @@ -429,8 +431,8 @@ extern struct btsnd_hcic_rmt_ext_features btsnd_hcic_rmt_ext_features; struct btsnd_hcic_rmt_name_req { std::function<void(const RawAddress& bd_addr, uint8_t page_scan_rep_mode, uint8_t page_scan_mode, uint16_t clock_offset)> - body{[](const RawAddress& bd_addr, uint8_t page_scan_rep_mode, - uint8_t page_scan_mode, uint16_t clock_offset) {}}; + body{[](const RawAddress& /* bd_addr */, uint8_t /* page_scan_rep_mode */, + uint8_t /* page_scan_mode */, uint16_t /* clock_offset */) {}}; void operator()(const RawAddress& bd_addr, uint8_t page_scan_rep_mode, uint8_t page_scan_mode, uint16_t clock_offset) { body(bd_addr, page_scan_rep_mode, page_scan_mode, clock_offset); @@ -443,7 +445,7 @@ extern struct btsnd_hcic_rmt_name_req btsnd_hcic_rmt_name_req; // Return: void struct btsnd_hcic_rmt_name_req_cancel { std::function<void(const RawAddress& bd_addr)> body{ - [](const RawAddress& bd_addr) {}}; + [](const RawAddress& /* bd_addr */) {}}; void operator()(const RawAddress& bd_addr) { body(bd_addr); }; }; extern struct btsnd_hcic_rmt_name_req_cancel btsnd_hcic_rmt_name_req_cancel; @@ -452,7 +454,7 @@ extern struct btsnd_hcic_rmt_name_req_cancel btsnd_hcic_rmt_name_req_cancel; // Params: uint16_t handle // Return: void struct btsnd_hcic_rmt_ver_req { - std::function<void(uint16_t handle)> body{[](uint16_t handle) {}}; + std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) {}}; void operator()(uint16_t handle) { body(handle); }; }; extern struct btsnd_hcic_rmt_ver_req btsnd_hcic_rmt_ver_req; @@ -462,7 +464,7 @@ extern struct btsnd_hcic_rmt_ver_req btsnd_hcic_rmt_ver_req; // Return: void struct btsnd_hcic_set_conn_encrypt { std::function<void(uint16_t handle, bool enable)> body{ - [](uint16_t handle, bool enable) {}}; + [](uint16_t /* handle */, bool /* enable */) {}}; void operator()(uint16_t handle, bool enable) { body(handle, enable); }; }; extern struct btsnd_hcic_set_conn_encrypt btsnd_hcic_set_conn_encrypt; @@ -473,8 +475,8 @@ extern struct btsnd_hcic_set_conn_encrypt btsnd_hcic_set_conn_encrypt; struct btsnd_hcic_set_event_filter { std::function<void(uint8_t filt_type, uint8_t filt_cond_type, uint8_t* filt_cond, uint8_t filt_cond_len)> - body{[](uint8_t filt_type, uint8_t filt_cond_type, uint8_t* filt_cond, - uint8_t filt_cond_len) {}}; + body{[](uint8_t /* filt_type */, uint8_t /* filt_cond_type */, + uint8_t* /* filt_cond */, uint8_t /* filt_cond_len */) {}}; void operator()(uint8_t filt_type, uint8_t filt_cond_type, uint8_t* filt_cond, uint8_t filt_cond_len) { body(filt_type, filt_cond_type, filt_cond, filt_cond_len); @@ -491,9 +493,10 @@ struct btsnd_hcic_setup_esco_conn { uint32_t receive_bandwidth, uint16_t max_latency, uint16_t voice, uint8_t retrans_effort, uint16_t packet_types)> - body{[](uint16_t handle, uint32_t transmit_bandwidth, - uint32_t receive_bandwidth, uint16_t max_latency, uint16_t voice, - uint8_t retrans_effort, uint16_t packet_types) {}}; + body{[](uint16_t /* handle */, uint32_t /* transmit_bandwidth */, + uint32_t /* receive_bandwidth */, uint16_t /* max_latency */, + uint16_t /* voice */, uint8_t /* retrans_effort */, + uint16_t /* packet_types */) {}}; void operator()(uint16_t handle, uint32_t transmit_bandwidth, uint32_t receive_bandwidth, uint16_t max_latency, uint16_t voice, uint8_t retrans_effort, @@ -511,9 +514,9 @@ struct btsnd_hcic_sniff_mode { std::function<void(uint16_t handle, uint16_t max_sniff_period, uint16_t min_sniff_period, uint16_t sniff_attempt, uint16_t sniff_timeout)> - body{[](uint16_t handle, uint16_t max_sniff_period, - uint16_t min_sniff_period, uint16_t sniff_attempt, - uint16_t sniff_timeout) {}}; + body{[](uint16_t /* handle */, uint16_t /* max_sniff_period */, + uint16_t /* min_sniff_period */, uint16_t /* sniff_attempt */, + uint16_t /* sniff_timeout */) {}}; void operator()(uint16_t handle, uint16_t max_sniff_period, uint16_t min_sniff_period, uint16_t sniff_attempt, uint16_t sniff_timeout) { @@ -529,8 +532,8 @@ extern struct btsnd_hcic_sniff_mode btsnd_hcic_sniff_mode; struct btsnd_hcic_sniff_sub_rate { std::function<void(uint16_t handle, uint16_t max_lat, uint16_t min_remote_lat, uint16_t min_local_lat)> - body{[](uint16_t handle, uint16_t max_lat, uint16_t min_remote_lat, - uint16_t min_local_lat) {}}; + body{[](uint16_t /* handle */, uint16_t /* max_lat */, + uint16_t /* min_remote_lat */, uint16_t /* min_local_lat */) {}}; void operator()(uint16_t handle, uint16_t max_lat, uint16_t min_remote_lat, uint16_t min_local_lat) { body(handle, max_lat, min_remote_lat, min_local_lat); @@ -543,7 +546,7 @@ extern struct btsnd_hcic_sniff_sub_rate btsnd_hcic_sniff_sub_rate; // Return: void struct btsnd_hcic_user_conf_reply { std::function<void(const RawAddress& bd_addr, bool is_yes)> body{ - [](const RawAddress& bd_addr, bool is_yes) {}}; + [](const RawAddress& /* bd_addr */, bool /* is_yes */) {}}; void operator()(const RawAddress& bd_addr, bool is_yes) { body(bd_addr, is_yes); }; @@ -555,7 +558,7 @@ extern struct btsnd_hcic_user_conf_reply btsnd_hcic_user_conf_reply; // Return: void struct btsnd_hcic_user_passkey_neg_reply { std::function<void(const RawAddress& bd_addr)> body{ - [](const RawAddress& bd_addr) {}}; + [](const RawAddress& /* bd_addr */) {}}; void operator()(const RawAddress& bd_addr) { body(bd_addr); }; }; extern struct btsnd_hcic_user_passkey_neg_reply @@ -566,7 +569,7 @@ extern struct btsnd_hcic_user_passkey_neg_reply // Return: void struct btsnd_hcic_user_passkey_reply { std::function<void(const RawAddress& bd_addr, uint32_t value)> body{ - [](const RawAddress& bd_addr, uint32_t value) {}}; + [](const RawAddress& /* bd_addr */, uint32_t /* value */) {}}; void operator()(const RawAddress& bd_addr, uint32_t value) { body(bd_addr, value); }; @@ -579,8 +582,8 @@ extern struct btsnd_hcic_user_passkey_reply btsnd_hcic_user_passkey_reply; struct btsnd_hcic_vendor_spec_cmd { std::function<void(uint16_t opcode, uint8_t len, uint8_t* p_data, tBTM_VSC_CMPL_CB* p_cmd_cplt_cback)> - body{[](uint16_t opcode, uint8_t len, uint8_t* p_data, - tBTM_VSC_CMPL_CB* p_cmd_cplt_cback) {}}; + body{[](uint16_t /* opcode */, uint8_t /* len */, uint8_t* /* p_data */, + tBTM_VSC_CMPL_CB* /* p_cmd_cplt_cback */) {}}; void operator()(uint16_t opcode, uint8_t len, uint8_t* p_data, tBTM_VSC_CMPL_CB* p_cmd_cplt_cback) { body(opcode, len, p_data, p_cmd_cplt_cback); @@ -592,7 +595,7 @@ extern struct btsnd_hcic_vendor_spec_cmd btsnd_hcic_vendor_spec_cmd; // Params: uint8_t flag // Return: void struct btsnd_hcic_write_auth_enable { - std::function<void(uint8_t flag)> body{[](uint8_t flag) {}}; + std::function<void(uint8_t flag)> body{[](uint8_t /* flag */) {}}; void operator()(uint8_t flag) { body(flag); }; }; extern struct btsnd_hcic_write_auth_enable btsnd_hcic_write_auth_enable; @@ -602,7 +605,7 @@ extern struct btsnd_hcic_write_auth_enable btsnd_hcic_write_auth_enable; // Return: void struct btsnd_hcic_write_auto_flush_tout { std::function<void(uint16_t handle, uint16_t tout)> body{ - [](uint16_t handle, uint16_t tout) {}}; + [](uint16_t /* handle */, uint16_t /* tout */) {}}; void operator()(uint16_t handle, uint16_t tout) { body(handle, tout); }; }; extern struct btsnd_hcic_write_auto_flush_tout btsnd_hcic_write_auto_flush_tout; @@ -612,7 +615,7 @@ extern struct btsnd_hcic_write_auto_flush_tout btsnd_hcic_write_auto_flush_tout; // Return: void struct btsnd_hcic_write_cur_iac_lap { std::function<void(uint8_t num_cur_iac, LAP* const iac_lap)> body{ - [](uint8_t num_cur_iac, LAP* const iac_lap) {}}; + [](uint8_t /* num_cur_iac */, LAP* const /* iac_lap */) {}}; void operator()(uint8_t num_cur_iac, LAP* const iac_lap) { body(num_cur_iac, iac_lap); }; @@ -623,7 +626,7 @@ extern struct btsnd_hcic_write_cur_iac_lap btsnd_hcic_write_cur_iac_lap; // Params: uint16_t settings // Return: void struct btsnd_hcic_write_def_policy_set { - std::function<void(uint16_t settings)> body{[](uint16_t settings) {}}; + std::function<void(uint16_t settings)> body{[](uint16_t /* settings */) {}}; void operator()(uint16_t settings) { body(settings); }; }; extern struct btsnd_hcic_write_def_policy_set btsnd_hcic_write_def_policy_set; @@ -632,7 +635,8 @@ extern struct btsnd_hcic_write_def_policy_set btsnd_hcic_write_def_policy_set; // Params: DEV_CLASS dev_class // Return: void struct btsnd_hcic_write_dev_class { - std::function<void(DEV_CLASS dev_class)> body{[](DEV_CLASS dev_class) {}}; + std::function<void(DEV_CLASS dev_class)> body{ + [](DEV_CLASS /* dev_class */) {}}; void operator()(DEV_CLASS dev_class) { body(dev_class); }; }; extern struct btsnd_hcic_write_dev_class btsnd_hcic_write_dev_class; @@ -642,7 +646,7 @@ extern struct btsnd_hcic_write_dev_class btsnd_hcic_write_dev_class; // Return: void struct btsnd_hcic_write_ext_inquiry_response { std::function<void(void* buffer, uint8_t fec_req)> body{ - [](void* buffer, uint8_t fec_req) {}}; + [](void* /* buffer */, uint8_t /* fec_req */) {}}; void operator()(void* buffer, uint8_t fec_req) { body(buffer, fec_req); }; }; extern struct btsnd_hcic_write_ext_inquiry_response @@ -653,7 +657,7 @@ extern struct btsnd_hcic_write_ext_inquiry_response // Return: void struct btsnd_hcic_write_inqscan_cfg { std::function<void(uint16_t interval, uint16_t window)> body{ - [](uint16_t interval, uint16_t window) {}}; + [](uint16_t /* interval */, uint16_t /* window */) {}}; void operator()(uint16_t interval, uint16_t window) { body(interval, window); }; @@ -664,7 +668,7 @@ extern struct btsnd_hcic_write_inqscan_cfg btsnd_hcic_write_inqscan_cfg; // Params: uint8_t type // Return: void struct btsnd_hcic_write_inqscan_type { - std::function<void(uint8_t type)> body{[](uint8_t type) {}}; + std::function<void(uint8_t type)> body{[](uint8_t /* type */) {}}; void operator()(uint8_t type) { body(type); }; }; extern struct btsnd_hcic_write_inqscan_type btsnd_hcic_write_inqscan_type; @@ -673,7 +677,7 @@ extern struct btsnd_hcic_write_inqscan_type btsnd_hcic_write_inqscan_type; // Params: uint8_t mode // Return: void struct btsnd_hcic_write_inquiry_mode { - std::function<void(uint8_t mode)> body{[](uint8_t mode) {}}; + std::function<void(uint8_t mode)> body{[](uint8_t /* mode */) {}}; void operator()(uint8_t mode) { body(mode); }; }; extern struct btsnd_hcic_write_inquiry_mode btsnd_hcic_write_inquiry_mode; @@ -683,7 +687,7 @@ extern struct btsnd_hcic_write_inquiry_mode btsnd_hcic_write_inquiry_mode; // Return: void struct btsnd_hcic_write_link_super_tout { std::function<void(uint16_t handle, uint16_t timeout)> body{ - [](uint16_t handle, uint16_t timeout) {}}; + [](uint16_t /* handle */, uint16_t /* timeout */) {}}; void operator()(uint16_t handle, uint16_t timeout) { body(handle, timeout); }; }; extern struct btsnd_hcic_write_link_super_tout btsnd_hcic_write_link_super_tout; @@ -692,7 +696,7 @@ extern struct btsnd_hcic_write_link_super_tout btsnd_hcic_write_link_super_tout; // Params: uint16_t timeout // Return: void struct btsnd_hcic_write_page_tout { - std::function<void(uint16_t timeout)> body{[](uint16_t timeout) {}}; + std::function<void(uint16_t timeout)> body{[](uint16_t /* timeout */) {}}; void operator()(uint16_t timeout) { body(timeout); }; }; extern struct btsnd_hcic_write_page_tout btsnd_hcic_write_page_tout; @@ -702,7 +706,7 @@ extern struct btsnd_hcic_write_page_tout btsnd_hcic_write_page_tout; // Return: void struct btsnd_hcic_write_pagescan_cfg { std::function<void(uint16_t interval, uint16_t window)> body{ - [](uint16_t interval, uint16_t window) {}}; + [](uint16_t /* interval */, uint16_t /* window */) {}}; void operator()(uint16_t interval, uint16_t window) { body(interval, window); }; @@ -713,7 +717,7 @@ extern struct btsnd_hcic_write_pagescan_cfg btsnd_hcic_write_pagescan_cfg; // Params: uint8_t type // Return: void struct btsnd_hcic_write_pagescan_type { - std::function<void(uint8_t type)> body{[](uint8_t type) {}}; + std::function<void(uint8_t type)> body{[](uint8_t /* type */) {}}; void operator()(uint8_t type) { body(type); }; }; extern struct btsnd_hcic_write_pagescan_type btsnd_hcic_write_pagescan_type; @@ -722,7 +726,7 @@ extern struct btsnd_hcic_write_pagescan_type btsnd_hcic_write_pagescan_type; // Params: uint8_t type // Return: void struct btsnd_hcic_write_pin_type { - std::function<void(uint8_t type)> body{[](uint8_t type) {}}; + std::function<void(uint8_t type)> body{[](uint8_t /* type */) {}}; void operator()(uint8_t type) { body(type); }; }; extern struct btsnd_hcic_write_pin_type btsnd_hcic_write_pin_type; @@ -732,7 +736,7 @@ extern struct btsnd_hcic_write_pin_type btsnd_hcic_write_pin_type; // Return: void struct btsnd_hcic_write_policy_set { std::function<void(uint16_t handle, uint16_t settings)> body{ - [](uint16_t handle, uint16_t settings) {}}; + [](uint16_t /* handle */, uint16_t /* settings */) {}}; void operator()(uint16_t handle, uint16_t settings) { body(handle, settings); }; @@ -743,7 +747,7 @@ extern struct btsnd_hcic_write_policy_set btsnd_hcic_write_policy_set; // Params: uint8_t flag // Return: void struct btsnd_hcic_write_scan_enable { - std::function<void(uint8_t flag)> body{[](uint8_t flag) {}}; + std::function<void(uint8_t flag)> body{[](uint8_t /* flag */) {}}; void operator()(uint8_t flag) { body(flag); }; }; extern struct btsnd_hcic_write_scan_enable btsnd_hcic_write_scan_enable; @@ -752,7 +756,7 @@ extern struct btsnd_hcic_write_scan_enable btsnd_hcic_write_scan_enable; // Params: uint16_t flags // Return: void struct btsnd_hcic_write_voice_settings { - std::function<void(uint16_t flags)> body{[](uint16_t flags) {}}; + std::function<void(uint16_t flags)> body{[](uint16_t /* flags */) {}}; void operator()(uint16_t flags) { body(flags); }; }; extern struct btsnd_hcic_write_voice_settings btsnd_hcic_write_voice_settings; diff --git a/system/test/mock/mock_stack_metrics_logging.h b/system/test/mock/mock_stack_metrics_logging.h index fd34980a10..ca938a698e 100644 --- a/system/test/mock/mock_stack_metrics_logging.h +++ b/system/test/mock/mock_stack_metrics_logging.h @@ -44,9 +44,10 @@ struct log_classic_pairing_event { std::function<void(const RawAddress& address, uint16_t handle, uint32_t hci_cmd, uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, int64_t event_value)> - body{[](const RawAddress& address, uint16_t handle, uint32_t hci_cmd, - uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, - int64_t event_value) {}}; + body{[](const RawAddress& /* address */, uint16_t /* handle */, + uint32_t /* hci_cmd */, uint16_t /* hci_event */, + uint16_t /* cmd_status */, uint16_t /* reason_code */, + int64_t /* event_value */) {}}; void operator()(const RawAddress& address, uint16_t handle, uint32_t hci_cmd, uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code, int64_t event_value) { @@ -66,10 +67,11 @@ struct log_link_layer_connection_event { uint16_t link_type, uint32_t hci_cmd, uint16_t hci_event, uint16_t hci_ble_event, uint16_t cmd_status, uint16_t reason_code)> - body{[](const RawAddress* address, uint32_t connection_handle, - android::bluetooth::DirectionEnum direction, uint16_t link_type, - uint32_t hci_cmd, uint16_t hci_event, uint16_t hci_ble_event, - uint16_t cmd_status, uint16_t reason_code) {}}; + body{[](const RawAddress* /* address */, uint32_t /* connection_handle */, + android::bluetooth::DirectionEnum /* direction */, + uint16_t /* link_type */, uint32_t /* hci_cmd */, + uint16_t /* hci_event */, uint16_t /* hci_ble_event */, + uint16_t /* cmd_status */, uint16_t /* reason_code */) {}}; void operator()(const RawAddress* address, uint32_t connection_handle, android::bluetooth::DirectionEnum direction, uint16_t link_type, uint32_t hci_cmd, uint16_t hci_event, @@ -88,9 +90,9 @@ struct log_smp_pairing_event { std::function<void(const RawAddress& address, uint16_t smp_cmd, android::bluetooth::DirectionEnum direction, uint16_t smp_fail_reason)> - body{[](const RawAddress& address, uint16_t smp_cmd, - android::bluetooth::DirectionEnum direction, - uint16_t smp_fail_reason) {}}; + body{[](const RawAddress& /* address */, uint16_t /* smp_cmd */, + android::bluetooth::DirectionEnum /* direction */, + uint16_t /* smp_fail_reason */) {}}; void operator()(const RawAddress& address, uint16_t smp_cmd, android::bluetooth::DirectionEnum direction, uint16_t smp_fail_reason) { @@ -106,9 +108,9 @@ struct log_sdp_attribute { std::function<void(const RawAddress& address, uint16_t protocol_uuid, uint16_t attribute_id, size_t attribute_size, const char* attribute_value)> - body{[](const RawAddress& address, uint16_t protocol_uuid, - uint16_t attribute_id, size_t attribute_size, - const char* attribute_value) {}}; + body{[](const RawAddress& /* address */, uint16_t /* protocol_uuid */, + uint16_t /* attribute_id */, size_t /* attribute_size */, + const char* /* attribute_value */) {}}; void operator()(const RawAddress& address, uint16_t protocol_uuid, uint16_t attribute_id, size_t attribute_size, const char* attribute_value) { @@ -129,12 +131,14 @@ struct log_manufacturer_info { const std::string& manufacturer, const std::string& model, const std::string& hardware_version, const std::string& software_version)> - body2{[](const RawAddress& address, - android::bluetooth::AddressTypeEnum address_type, - android::bluetooth::DeviceInfoSrcEnum source_type, - const std::string& source_name, const std::string& manufacturer, - const std::string& model, const std::string& hardware_version, - const std::string& software_version) {}}; + body2{[](const RawAddress& /* address */, + android::bluetooth::AddressTypeEnum /* address_type */, + android::bluetooth::DeviceInfoSrcEnum /* source_type */, + const std::string& /* source_name */, + const std::string& /* manufacturer */, + const std::string& /* model */, + const std::string& /* hardware_version */, + const std::string& /* software_version */) {}}; void operator()(const RawAddress& address, android::bluetooth::AddressTypeEnum address_type, android::bluetooth::DeviceInfoSrcEnum source_type, @@ -151,11 +155,13 @@ struct log_manufacturer_info { const std::string& manufacturer, const std::string& model, const std::string& hardware_version, const std::string& software_version)> - body{[](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) {}}; + body{[](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 */) {}}; void operator()(const RawAddress& address, android::bluetooth::DeviceInfoSrcEnum source_type, const std::string& source_name, @@ -172,8 +178,8 @@ extern struct log_manufacturer_info log_manufacturer_info; struct log_counter_metrics { std::function<void(android::bluetooth::CodePathCounterKeyEnum key, int64_t value)> - body{ - [](android::bluetooth::CodePathCounterKeyEnum key, int64_t value) {}}; + body{[](android::bluetooth::CodePathCounterKeyEnum /* key */, + int64_t /* value */) {}}; void operator()(android::bluetooth::CodePathCounterKeyEnum key, int64_t value) { body(key, value); @@ -185,8 +191,8 @@ extern struct log_counter_metrics log_counter_metrics; struct log_hfp_audio_packet_loss_stats { std::function<void(const RawAddress& address, int num_decoded_frames, double packet_loss_ratio, uint16_t codec_type)> - body{[](const RawAddress& address, int num_decoded_frames, - double packet_loss_ratio, uint16_t codec_type) {}}; + body{[](const RawAddress& /* address */, int /* num_decoded_frames */, + double /* packet_loss_ratio */, uint16_t /* codec_type */) {}}; void operator()(const RawAddress& address, int num_decoded_frames, double packet_loss_ratio, uint16_t codec_type) { body(address, num_decoded_frames, packet_loss_ratio, codec_type); @@ -198,8 +204,8 @@ extern struct log_hfp_audio_packet_loss_stats log_hfp_audio_packet_loss_stats; struct log_mmc_transcode_rtt_stats { std::function<void(int maximum_rtt, double mean_rtt, int num_requests, int codec_type)> - body{[](int maximum_rtt, double mean_rtt, int num_requests, - int codec_type) {}}; + body{[](int /* maximum_rtt */, double /* mean_rtt */, + int /* num_requests */, int /* codec_type */) {}}; void operator()(int maximum_rtt, double mean_rtt, int num_requests, int codec_type) { body(maximum_rtt, mean_rtt, num_requests, codec_type); diff --git a/system/test/suite/Android.bp b/system/test/suite/Android.bp index 3a43433fbc..439e9a38ff 100644 --- a/system/test/suite/Android.bp +++ b/system/test/suite/Android.bp @@ -69,6 +69,7 @@ cc_defaults { "libbluetooth-types", "libbluetooth_core_rs", "libbluetooth_core_rs_bridge", + "libbluetooth_log", "libbt-audio-asrc", "libbt-audio-hal-interface", "libbt-bta", @@ -119,6 +120,7 @@ cc_test { "libbluetooth_crypto_toolbox", "libbluetooth_gd", "libbluetooth_hci_pdl", + "libbluetooth_log", "libbt-btu-main-thread", "libbt-jni-thread", "libbt-platform-protos-lite", @@ -128,6 +130,7 @@ cc_test { "libprotobuf-cpp-lite", ], shared_libs: [ + "libbase", "server_configurable_flags", ], generated_headers: [ diff --git a/system/types/Android.bp b/system/types/Android.bp index 8ff1cd0ea2..742d6d3efb 100644 --- a/system/types/Android.bp +++ b/system/types/Android.bp @@ -67,6 +67,7 @@ cc_test { ], include_dirs: [ "packages/modules/Bluetooth/system", + "packages/modules/Bluetooth/system/include", ], host_supported: true, srcs: [ diff --git a/system/types/ble_address_with_type.h b/system/types/ble_address_with_type.h index 90aefdd289..9dece14050 100644 --- a/system/types/ble_address_with_type.h +++ b/system/types/ble_address_with_type.h @@ -18,6 +18,8 @@ #include <cstdint> #include <string> + +#include "types/bt_transport.h" #include "types/raw_address.h" #define BLE_ADDR_PUBLIC 0x00 @@ -149,4 +151,42 @@ struct std::hash<tBLE_BD_ADDR> { } }; +struct tTypedAddressTransport { + tBLE_BD_ADDR addrt; + tBT_TRANSPORT transport; + + bool operator==(const tTypedAddressTransport rhs) const { + if (rhs.addrt != addrt) return false; + + if (rhs.transport == BT_TRANSPORT_AUTO || transport == BT_TRANSPORT_AUTO) { + return true; + } + + return rhs.transport == transport; + } + + bool operator!=(const tTypedAddressTransport rhs) const { + return !(*this == rhs); + } + + bool StrictlyEquals(const tTypedAddressTransport rhs) const { + return rhs.addrt == addrt && rhs.transport == transport; + } + + std::string ToString() const { + return std::string(addrt.ToString() + "[" + bt_transport_text(transport) + + "]"); + } + + std::string ToStringForLogging() const { + return addrt.ToStringForLogging() + "[" + bt_transport_text(transport) + + "]"; + } + + std::string ToRedactedStringForLogging() const { + return addrt.ToRedactedStringForLogging() + "[" + + bt_transport_text(transport) + "]"; + } +}; + #endif diff --git a/system/types/test/ble_address_with_type_unittest.cc b/system/types/test/ble_address_with_type_unittest.cc index 5332d99e28..dd057b4b9e 100644 --- a/system/types/test/ble_address_with_type_unittest.cc +++ b/system/types/test/ble_address_with_type_unittest.cc @@ -17,6 +17,8 @@ #include "types/ble_address_with_type.h" #include <gtest/gtest.h> +static constexpr uint8_t RAW_ADDRESS_TEST1[6] = {0x01, 0x02, 0x03, + 0x04, 0x05, 0x06}; TEST(BleAddressWithTypeTest, to_ble_addr_type) { for (unsigned i = 0; i < 0xff + 1; i++) { @@ -97,6 +99,23 @@ TEST(BleAddressWithTypeTest, STREAM_TO_BLE_ADDR_TYPE) { } } +TEST(BleAddressWithTypeTest, TYPED_ADDRESS_TRANSPORT) { + tTypedAddressTransport typedAddressTransportA = { + {BLE_ADDR_PUBLIC, RAW_ADDRESS_TEST1}, BT_TRANSPORT_AUTO}; + tTypedAddressTransport typedAddressTransportB = { + {BLE_ADDR_PUBLIC, RAW_ADDRESS_TEST1}, BT_TRANSPORT_BR_EDR}; + tTypedAddressTransport typedAddressTransportC = { + {BLE_ADDR_PUBLIC, RAW_ADDRESS_TEST1}, BT_TRANSPORT_LE}; + + ASSERT_EQ(typedAddressTransportA, typedAddressTransportB); + ASSERT_EQ(typedAddressTransportA, typedAddressTransportC); + ASSERT_NE(typedAddressTransportB, typedAddressTransportC); + + ASSERT_FALSE(typedAddressTransportA.StrictlyEquals(typedAddressTransportB)); + ASSERT_FALSE(typedAddressTransportA.StrictlyEquals(typedAddressTransportC)); + ASSERT_FALSE(typedAddressTransportB.StrictlyEquals(typedAddressTransportC)); +} + TEST(BleAddressWithTypeTest, BLE_ADDR_TYPE_TO_STREAM) { uint8_t buf[256] = {0}; uint8_t* p = buf; diff --git a/system/udrv/Android.bp b/system/udrv/Android.bp index dee3f082f8..0e8be074e0 100644 --- a/system/udrv/Android.bp +++ b/system/udrv/Android.bp @@ -28,5 +28,8 @@ cc_library_static { ], min_sdk_version: "Tiramisu", header_libs: ["libbluetooth_headers"], - static_libs: ["libbt_shim_bridge"], + static_libs: [ + "libbluetooth_log", + "libbt_shim_bridge", + ], } |