diff options
468 files changed, 6969 insertions, 2517 deletions
diff --git a/CPPLINT.cfg b/CPPLINT.cfg index cc062661c7..3dff24b5c4 100644 --- a/CPPLINT.cfg +++ b/CPPLINT.cfg @@ -5,14 +5,6 @@ linelength=100 filter=-whitespace/indent # TODO: b/364967694 re-enable the warning -filter=-whitespace/newline -# TODO: b/364967694 re-enable the warning -filter=-whitespace/blank_line -# TODO: b/364967694 re-enable the warning -filter=-whitespace/ending_newline -# TODO: b/364967694 re-enable the warning -filter=-readability/check -# TODO: b/364967694 re-enable the warning filter=-runtime/int # TODO: b/364967694 re-enable the warning filter=-runtime/string @@ -5,11 +5,12 @@ girardier@google.com #{LAST_RESORT_SUGGESTION} muhammadfalam@google.com #{LAST_RESORT_SUGGESTION} siyuanh@google.com #{LAST_RESORT_SUGGESTION} okamil@google.com #{LAST_RESORT_SUGGESTION} +wescande@google.com #{LAST_RESORT_SUGGESTION} # Per-file ownership # Build files / test_config / presubmit / preupload / linter file -per-file PREUPLOAD.cfg,TEST_MAPPING,*.bp,*.xml,.clang-tidy,pyrightconfig.json=file:/OWNERS_build +per-file *.cfg,.cfg,TEST_MAPPING,*.bp,*.xml,.clang-tidy,pyrightconfig.json=file:/OWNERS_build # ChromeOS team owns Linux build files # - build.py is used for Linux build diff --git a/android/app/Android.bp b/android/app/Android.bp index bb873554df..e8ca967da4 100644 --- a/android/app/Android.bp +++ b/android/app/Android.bp @@ -79,7 +79,6 @@ cc_library_shared { include_dirs: [ "packages/modules/Bluetooth/system", "packages/modules/Bluetooth/system/gd", - "packages/modules/Bluetooth/system/types", ], // libbluetooth_jni is the jni lib included in the btservices apex. // As this library is inside an APEX the shared_libs that does not @@ -182,9 +181,6 @@ cc_library { "jni_headers", "libbluetooth_headers", ], - include_dirs: [ - "packages/modules/Bluetooth/system/types", - ], static_libs: [ "lib-bt-packets", "lib-bt-packets-base", @@ -243,6 +239,7 @@ android_app { jni_uses_platform_apis: true, libs: [ "app-compat-annotations", + "bluetooth_constants_java", "bluetooth_flags_java_lib", "error_prone_annotations", "framework-annotations-lib", @@ -271,7 +268,6 @@ android_app { "bluetooth-protos-lite", "bluetooth.change-ids", "bluetooth.mapsapi", - "bluetooth_constants_java", "com.android.obex", "com.android.vcard", "guava", diff --git a/android/app/aidl/Android.bp b/android/app/aidl/Android.bp index 03f2d109ce..0829e0296c 100644 --- a/android/app/aidl/Android.bp +++ b/android/app/aidl/Android.bp @@ -12,6 +12,7 @@ filegroup { name: "Bluetooth-binder-aidl", srcs: [ ":framework-bluetooth-updatable-exported-aidl-sources", + "android/bluetooth/IAudioInputCallback.aidl", "android/bluetooth/IBluetooth.aidl", "android/bluetooth/IBluetoothA2dp.aidl", "android/bluetooth/IBluetoothA2dpSink.aidl", diff --git a/android/app/aidl/android/bluetooth/IAudioInputCallback.aidl b/android/app/aidl/android/bluetooth/IAudioInputCallback.aidl new file mode 100644 index 0000000000..133dfbebbb --- /dev/null +++ b/android/app/aidl/android/bluetooth/IAudioInputCallback.aidl @@ -0,0 +1,31 @@ +/* + * Copyright 2024 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.bluetooth; + +/** + * Callback definitions for interacting with @see AudioInputControl + * + * @hide + */ +oneway interface IAudioInputCallback { + void onDescriptionChanged(in String description); + void onStatusChanged(int status); + void onStateChanged(int gainSetting, int mute, int gainMode); + void onSetGainSettingFailed(); + void onSetGainModeFailed(); + void onSetMuteFailed(); +} diff --git a/android/app/aidl/android/bluetooth/IBluetooth.aidl b/android/app/aidl/android/bluetooth/IBluetooth.aidl index 83cbe469ae..e619073fd9 100644 --- a/android/app/aidl/android/bluetooth/IBluetooth.aidl +++ b/android/app/aidl/android/bluetooth/IBluetooth.aidl @@ -325,6 +325,12 @@ interface IBluetooth @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") int getActiveAudioDevicePolicy(in BluetoothDevice device, in AttributionSource source); + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + int setMicrophonePreferredForCalls(in BluetoothDevice device, in boolean enabled, in AttributionSource source); + + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + boolean isMicrophonePreferredForCalls(in BluetoothDevice device, in AttributionSource source); + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED)") oneway void killBluetoothProcess(); } diff --git a/android/app/aidl/android/bluetooth/IBluetoothLeAudioCallback.aidl b/android/app/aidl/android/bluetooth/IBluetoothLeAudioCallback.aidl index 92ecfe814d..f333405f5e 100644 --- a/android/app/aidl/android/bluetooth/IBluetoothLeAudioCallback.aidl +++ b/android/app/aidl/android/bluetooth/IBluetoothLeAudioCallback.aidl @@ -32,4 +32,5 @@ oneway interface IBluetoothLeAudioCallback { void onGroupNodeRemoved(in BluetoothDevice device, int groupId); void onGroupStatusChanged(int groupId, int groupStatus); void onGroupStreamStatusChanged(int groupId, int groupStreamStatus); + void onBroadcastToUnicastFallbackGroupChanged(in int groupId); } diff --git a/android/app/aidl/android/bluetooth/IBluetoothVolumeControl.aidl b/android/app/aidl/android/bluetooth/IBluetoothVolumeControl.aidl index e4509661c8..2605a263fd 100644 --- a/android/app/aidl/android/bluetooth/IBluetoothVolumeControl.aidl +++ b/android/app/aidl/android/bluetooth/IBluetoothVolumeControl.aidl @@ -18,6 +18,7 @@ package android.bluetooth; import android.bluetooth.BluetoothDevice; +import android.bluetooth.IAudioInputCallback; import android.bluetooth.IBluetoothVolumeControlCallback; import android.content.AttributionSource; @@ -72,4 +73,50 @@ interface IBluetoothVolumeControl { void unregisterCallback(in IBluetoothVolumeControlCallback callback, in AttributionSource attributionSource); @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") void notifyNewRegisteredCallback(in IBluetoothVolumeControlCallback callback, in AttributionSource attributionSource); + + // --------------------- + // AICS related methods: + + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + int getNumberOfAudioInputControlServices(in AttributionSource attributionSource, in BluetoothDevice device); + + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + void registerAudioInputControlCallback(in AttributionSource attributionSource, in BluetoothDevice device, int instanceId, in IAudioInputCallback callback); + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + void unregisterAudioInputControlCallback(in AttributionSource attributionSource, in BluetoothDevice device, int instanceId, in IAudioInputCallback callback); + + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + int getAudioInputGainSettingUnit(in AttributionSource attributionSource, in BluetoothDevice device, int instanceId); + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + int getAudioInputGainSettingMin(in AttributionSource attributionSource, in BluetoothDevice device, int instanceId); + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + int getAudioInputGainSettingMax(in AttributionSource attributionSource, in BluetoothDevice device, int instanceId); + + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + String getAudioInputDescription(in AttributionSource attributionSource, in BluetoothDevice device, int instanceId); + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + boolean isAudioInputDescriptionWritable(in AttributionSource attributionSource, in BluetoothDevice device, int instanceId); + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + boolean setAudioInputDescription(in AttributionSource attributionSource, in BluetoothDevice device, int instanceId, in String description); + + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + int getAudioInputStatus(in AttributionSource attributionSource, in BluetoothDevice device, int instanceId); + + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + int getAudioInputType(in AttributionSource attributionSource, in BluetoothDevice device, int instanceId); + + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + int getAudioInputGainSetting(in AttributionSource attributionSource, in BluetoothDevice device, int instanceId); + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + boolean setAudioInputGainSetting(in AttributionSource attributionSource, in BluetoothDevice device, int instanceId, int gainSetting); + + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + int getAudioInputGainMode(in AttributionSource attributionSource, in BluetoothDevice device, int instanceId); + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + boolean setAudioInputGainMode(in AttributionSource attributionSource, in BluetoothDevice device, int instanceId, int gainMode); + + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + int getAudioInputMute(in AttributionSource attributionSource, in BluetoothDevice device, int instanceId); + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") + boolean setAudioInputMute(in AttributionSource attributionSource, in BluetoothDevice device, int instanceId, int mute); } diff --git a/android/app/jni/com_android_bluetooth_vc.cpp b/android/app/jni/com_android_bluetooth_vc.cpp index e7cf0ab080..6d5d8984cd 100644 --- a/android/app/jni/com_android_bluetooth_vc.cpp +++ b/android/app/jni/com_android_bluetooth_vc.cpp @@ -35,6 +35,7 @@ #include "hardware/bt_vc.h" #include "types/raw_address.h" +using bluetooth::aics::GainMode; using bluetooth::aics::Mute; using bluetooth::vc::ConnectionState; using bluetooth::vc::VolumeControlCallbacks; @@ -51,9 +52,12 @@ static jmethodID method_onExtAudioOutVolumeOffsetChanged; static jmethodID method_onExtAudioOutLocationChanged; static jmethodID method_onExtAudioOutDescriptionChanged; static jmethodID method_onExtAudioInStateChanged; +static jmethodID method_onExtAudioInSetGainSettingFailed; +static jmethodID method_onExtAudioInSetMuteFailed; +static jmethodID method_onExtAudioInSetGainModeFailed; static jmethodID method_onExtAudioInStatusChanged; static jmethodID method_onExtAudioInTypeChanged; -static jmethodID method_onExtAudioInGainPropsChanged; +static jmethodID method_onExtAudioInGainSettingPropertiesChanged; static jmethodID method_onExtAudioInDescriptionChanged; static VolumeControlInterface* sVolumeControlInterface = nullptr; @@ -224,7 +228,7 @@ public: } void OnExtAudioInStateChanged(const RawAddress& bd_addr, uint8_t ext_input_id, - int8_t gain_setting, Mute mute, uint8_t gain_mode) override { + int8_t gain_setting, Mute mute, GainMode gain_mode) override { log::info(""); std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex); @@ -246,6 +250,71 @@ public: (jint)gain_setting, (jint)mute, (jint)gain_mode, addr.get()); } + void OnExtAudioInSetGainSettingFailed(const RawAddress& bd_addr, uint8_t ext_input_id) override { + log::info(""); + + std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex); + CallbackEnv sCallbackEnv(__func__); + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } + + ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); + if (!addr.get()) { + log::error("Failed to get addr for {}", bd_addr); + return; + } + + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), + reinterpret_cast<const jbyte*>(&bd_addr)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onExtAudioInSetGainSettingFailed, + (jint)ext_input_id, addr.get()); + } + + void OnExtAudioInSetMuteFailed(const RawAddress& bd_addr, uint8_t ext_input_id) override { + log::info(""); + + std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex); + CallbackEnv sCallbackEnv(__func__); + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } + + ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); + if (!addr.get()) { + log::error("Failed to get addr for {}", bd_addr); + return; + } + + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), + reinterpret_cast<const jbyte*>(&bd_addr)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onExtAudioInSetMuteFailed, + (jint)ext_input_id, addr.get()); + } + void OnExtAudioInSetGainModeFailed(const RawAddress& bd_addr, uint8_t ext_input_id) override { + log::info(""); + + std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex); + CallbackEnv sCallbackEnv(__func__); + if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { + return; + } + + ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), + sCallbackEnv->NewByteArray(sizeof(RawAddress))); + if (!addr.get()) { + log::error("Failed to get addr for {}", bd_addr); + return; + } + + sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), + reinterpret_cast<const jbyte*>(&bd_addr)); + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onExtAudioInSetGainModeFailed, + (jint)ext_input_id, addr.get()); + } + void OnExtAudioInStatusChanged(const RawAddress& bd_addr, uint8_t ext_input_id, VolumeInputStatus status) override { log::info(""); @@ -292,8 +361,8 @@ public: (jint)type, addr.get()); } - void OnExtAudioInGainPropsChanged(const RawAddress& bd_addr, uint8_t ext_input_id, uint8_t unit, - int8_t min, int8_t max) override { + void OnExtAudioInGainSettingPropertiesChanged(const RawAddress& bd_addr, uint8_t ext_input_id, + uint8_t unit, int8_t min, int8_t max) override { log::info(""); std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex); @@ -311,12 +380,12 @@ public: sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), reinterpret_cast<const jbyte*>(&bd_addr)); - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onExtAudioInGainPropsChanged, + sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onExtAudioInGainSettingPropertiesChanged, (jint)ext_input_id, (jint)unit, (jint)min, (jint)max, addr.get()); } void OnExtAudioInDescriptionChanged(const RawAddress& bd_addr, uint8_t ext_input_id, - std::string descr) override { + std::string description, bool is_writable) override { log::info(""); std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex); @@ -334,9 +403,10 @@ public: sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), reinterpret_cast<const jbyte*>(&bd_addr)); - jstring description = sCallbackEnv->NewStringUTF(descr.c_str()); + jstring jdescription = sCallbackEnv->NewStringUTF(description.c_str()); sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onExtAudioInDescriptionChanged, - (jint)ext_input_id, description, addr.get()); + (jint)ext_input_id, jdescription, (jboolean)is_writable, + addr.get()); } }; @@ -777,9 +847,9 @@ static jboolean setExtAudioInDescriptionNative(JNIEnv* env, jobject /* object */ } RawAddress* tmpraw = reinterpret_cast<RawAddress*>(addr); - sVolumeControlInterface->SetExtAudioInDescription(*tmpraw, ext_input_id, description); + bool ret = sVolumeControlInterface->SetExtAudioInDescription(*tmpraw, ext_input_id, description); env->ReleaseByteArrayElements(address, addr, 0); - return JNI_TRUE; + return ret ? JNI_TRUE : JNI_FALSE; } static jboolean setExtAudioInGainSettingNative(JNIEnv* env, jobject /* object */, @@ -798,13 +868,13 @@ static jboolean setExtAudioInGainSettingNative(JNIEnv* env, jobject /* object */ } RawAddress* tmpraw = reinterpret_cast<RawAddress*>(addr); - sVolumeControlInterface->SetExtAudioInGainSetting(*tmpraw, ext_input_id, gain_setting); + bool ret = sVolumeControlInterface->SetExtAudioInGainSetting(*tmpraw, ext_input_id, gain_setting); env->ReleaseByteArrayElements(address, addr, 0); - return JNI_TRUE; + return ret ? JNI_TRUE : JNI_FALSE; } static jboolean setExtAudioInGainModeNative(JNIEnv* env, jobject /* object */, jbyteArray address, - jint ext_input_id, jboolean mode_auto) { + jint ext_input_id, jint gain_mode) { log::info(""); std::shared_lock<std::shared_timed_mutex> lock(interface_mutex); if (!sVolumeControlInterface) { @@ -818,13 +888,14 @@ static jboolean setExtAudioInGainModeNative(JNIEnv* env, jobject /* object */, j } RawAddress* tmpraw = reinterpret_cast<RawAddress*>(addr); - sVolumeControlInterface->SetExtAudioInGainMode(*tmpraw, ext_input_id, mode_auto); + bool ret = sVolumeControlInterface->SetExtAudioInGainMode( + *tmpraw, ext_input_id, bluetooth::aics::parseGainModeField(gain_mode)); env->ReleaseByteArrayElements(address, addr, 0); - return JNI_TRUE; + return ret ? JNI_TRUE : JNI_FALSE; } -static jboolean setExtAudioInGainMuteNative(JNIEnv* env, jobject /* object */, jbyteArray address, - jint ext_input_id, jboolean mute) { +static jboolean setExtAudioInMuteNative(JNIEnv* env, jobject /* object */, jbyteArray address, + jint ext_input_id, jint mute) { log::info(""); std::shared_lock<std::shared_timed_mutex> lock(interface_mutex); if (!sVolumeControlInterface) { @@ -838,9 +909,10 @@ static jboolean setExtAudioInGainMuteNative(JNIEnv* env, jobject /* object */, j } RawAddress* tmpraw = reinterpret_cast<RawAddress*>(addr); - sVolumeControlInterface->SetExtAudioInGainMute(*tmpraw, ext_input_id, mute); + bool ret = sVolumeControlInterface->SetExtAudioInMute(*tmpraw, ext_input_id, + bluetooth::aics::parseMuteField(mute)); env->ReleaseByteArrayElements(address, addr, 0); - return JNI_TRUE; + return ret ? JNI_TRUE : JNI_FALSE; } int register_com_android_bluetooth_vc(JNIEnv* env) { @@ -881,10 +953,9 @@ int register_com_android_bluetooth_vc(JNIEnv* env) { reinterpret_cast<void*>(setExtAudioInDescriptionNative)}, {"setExtAudioInGainSettingNative", "([BII)Z", reinterpret_cast<void*>(setExtAudioInGainSettingNative)}, - {"setExtAudioInGainModeNative", "([BIZ)Z", + {"setExtAudioInGainModeNative", "([BII)Z", reinterpret_cast<void*>(setExtAudioInGainModeNative)}, - {"setExtAudioInGainMuteNative", "([BIZ)Z", - reinterpret_cast<void*>(setExtAudioInGainMuteNative)}, + {"setExtAudioInMuteNative", "([BII)Z", reinterpret_cast<void*>(setExtAudioInMuteNative)}, }; const int result = REGISTER_NATIVE_METHODS( env, "com/android/bluetooth/vc/VolumeControlNativeInterface", methods); @@ -908,10 +979,14 @@ int register_com_android_bluetooth_vc(JNIEnv* env) { {"onExtAudioOutDescriptionChanged", "(ILjava/lang/String;[B)V", &method_onExtAudioOutDescriptionChanged}, {"onExtAudioInStateChanged", "(IIII[B)V", &method_onExtAudioInStateChanged}, + {"onExtAudioInSetGainSettingFailed", "(I[B)V", &method_onExtAudioInSetGainSettingFailed}, + {"onExtAudioInSetMuteFailed", "(I[B)V", &method_onExtAudioInSetMuteFailed}, + {"onExtAudioInSetGainModeFailed", "(I[B)V", &method_onExtAudioInSetGainModeFailed}, {"onExtAudioInStatusChanged", "(II[B)V", &method_onExtAudioInStatusChanged}, {"onExtAudioInTypeChanged", "(II[B)V", &method_onExtAudioInTypeChanged}, - {"onExtAudioInGainPropsChanged", "(IIII[B)V", &method_onExtAudioInGainPropsChanged}, - {"onExtAudioInDescriptionChanged", "(ILjava/lang/String;[B)V", + {"onExtAudioInGainSettingPropertiesChanged", "(IIII[B)V", + &method_onExtAudioInGainSettingPropertiesChanged}, + {"onExtAudioInDescriptionChanged", "(ILjava/lang/String;Z[B)V", &method_onExtAudioInDescriptionChanged}, }; GET_JAVA_METHODS(env, "com/android/bluetooth/vc/VolumeControlNativeCallback", javaMethods); 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 957b02c322..72648cbcfd 100644 --- a/android/app/src/com/android/bluetooth/bass_client/BassClientService.java +++ b/android/app/src/com/android/bluetooth/bass_client/BassClientService.java @@ -1297,9 +1297,9 @@ public class BassClientService extends ProfileService { return devices; } - private boolean isValidBroadcastSourceAddition( + private int checkDuplicateSourceAdditionAndGetSourceId( BluetoothDevice device, BluetoothLeBroadcastMetadata metaData) { - boolean retval = true; + int sourceId = BassConstants.INVALID_SOURCE_ID; List<BluetoothLeBroadcastReceiveState> currentAllSources = getAllSources(device); for (int i = 0; i < currentAllSources.size(); i++) { BluetoothLeBroadcastReceiveState state = currentAllSources.get(i); @@ -1307,17 +1307,12 @@ public class BassClientService extends ProfileService { && metaData.getSourceAddressType() == state.getSourceAddressType() && metaData.getSourceAdvertisingSid() == state.getSourceAdvertisingSid() && metaData.getBroadcastId() == state.getBroadcastId()) { - retval = false; - Log.e( - TAG, - "isValidBroadcastSourceAddition: fail for " - + device - + " metaData: " - + metaData); + sourceId = state.getSourceId(); + log("DuplicatedSourceAddition: for " + device + " metaData: " + metaData); break; } } - return retval; + return sourceId; } private boolean hasRoomForBroadcastSourceAddition(BluetoothDevice device) { @@ -1512,45 +1507,77 @@ public class BassClientService extends ProfileService { } } - private int areValidParametersToModifySource( - BluetoothLeBroadcastMetadata updatedMetadata, - BassClientStateMachine stateMachine, - Integer deviceSourceId, - BluetoothDevice device) { - if (updatedMetadata == null || stateMachine == null) { - log( - "areValidParametersToModifySource: Error bad parameters: sourceId = " - + deviceSourceId - + " updatedMetadata = " - + updatedMetadata); + private int validateParametersForSourceOperation( + BassClientStateMachine stateMachine, BluetoothDevice device) { + if (stateMachine == null) { + log("validateParameters: stateMachine is null for device: " + device); return BluetoothStatusCodes.ERROR_BAD_PARAMETERS; } - if (deviceSourceId == BassConstants.INVALID_SOURCE_ID) { - log("areValidParametersToModifySource: no such sourceId for device: " + device); - return BluetoothStatusCodes.ERROR_LE_BROADCAST_ASSISTANT_INVALID_SOURCE_ID; - } + if (getConnectionState(device) != BluetoothProfile.STATE_CONNECTED) { - log("areValidParametersToModifySource: device is not connected"); + log("validateParameters: device is not connected, device: " + device); return BluetoothStatusCodes.ERROR_REMOTE_LINK_ERROR; } - byte[] code = updatedMetadata.getBroadcastCode(); + + return BluetoothStatusCodes.SUCCESS; + } + + private int validateParametersForSourceOperation( + BassClientStateMachine stateMachine, + BluetoothDevice device, + BluetoothLeBroadcastMetadata metadata) { + int status = validateParametersForSourceOperation(stateMachine, device); + if (status != BluetoothStatusCodes.SUCCESS) { + return status; + } + + if (metadata == null) { + log("validateParameters: metadata is null for device: " + device); + return BluetoothStatusCodes.ERROR_BAD_PARAMETERS; + } + + byte[] code = metadata.getBroadcastCode(); if ((code != null) && (code.length != 0)) { if ((code.length > 16) || (code.length < 4)) { log( - "areValidParametersToModifySource: Invalid broadcast code length: " + "validateParameters: Invalid broadcast code length: " + code.length + ", should be between 4 and 16 octets"); return BluetoothStatusCodes.ERROR_BAD_PARAMETERS; } } - if (stateMachine.hasPendingSourceOperation()) { - Log.w( - TAG, - "modifySource: source operation already pending, device: " - + device - + ", broadcastId: " - + updatedMetadata.getBroadcastId()); - return BluetoothStatusCodes.ERROR_ALREADY_IN_TARGET_STATE; + + return BluetoothStatusCodes.SUCCESS; + } + + private int validateParametersForSourceOperation( + BassClientStateMachine stateMachine, BluetoothDevice device, Integer sourceId) { + int status = validateParametersForSourceOperation(stateMachine, device); + if (status != BluetoothStatusCodes.SUCCESS) { + return status; + } + + if (sourceId == BassConstants.INVALID_SOURCE_ID) { + log("validateParameters: no such sourceId for device: " + device); + return BluetoothStatusCodes.ERROR_LE_BROADCAST_ASSISTANT_INVALID_SOURCE_ID; + } + + return BluetoothStatusCodes.SUCCESS; + } + + private int validateParametersForSourceOperation( + BassClientStateMachine stateMachine, + BluetoothDevice device, + BluetoothLeBroadcastMetadata metadata, + Integer sourceId) { + int status = validateParametersForSourceOperation(stateMachine, device, metadata); + if (status != BluetoothStatusCodes.SUCCESS) { + return status; + } + + if (sourceId == BassConstants.INVALID_SOURCE_ID) { + log("validateParameters: no such sourceId for device: " + device); + return BluetoothStatusCodes.ERROR_LE_BROADCAST_ASSISTANT_INVALID_SOURCE_ID; } return BluetoothStatusCodes.SUCCESS; @@ -2942,16 +2969,10 @@ public class BassClientService extends ProfileService { byte[] code = sourceMetadata.getBroadcastCode(); for (BluetoothDevice device : devices) { BassClientStateMachine stateMachine = getOrCreateStateMachine(device); - if (stateMachine == null) { - log("addSource: Error bad parameter: no state machine for " + device); - mCallbacks.notifySourceAddFailed( - device, sourceMetadata, BluetoothStatusCodes.ERROR_BAD_PARAMETERS); - continue; - } - if (getConnectionState(device) != BluetoothProfile.STATE_CONNECTED) { - log("addSource: device is not connected"); - mCallbacks.notifySourceAddFailed( - device, sourceMetadata, BluetoothStatusCodes.ERROR_REMOTE_LINK_ERROR); + int statusCode = + validateParametersForSourceOperation(stateMachine, device, sourceMetadata); + if (statusCode != BluetoothStatusCodes.SUCCESS) { + mCallbacks.notifySourceAddFailed(device, sourceMetadata, statusCode); continue; } if (stateMachine.hasPendingSourceOperation()) { @@ -2965,12 +2986,19 @@ public class BassClientService extends ProfileService { device, sourceMetadata, BluetoothStatusCodes.ERROR_ALREADY_IN_TARGET_STATE); continue; } + if (leaudioBroadcastResyncHelper()) { + int sourceId = checkDuplicateSourceAdditionAndGetSourceId(device, sourceMetadata); + if (sourceId != BassConstants.INVALID_SOURCE_ID) { + updateSourceToResumeBroadcast(device, sourceId, sourceMetadata); + continue; + } + } if (!hasRoomForBroadcastSourceAddition(device)) { log("addSource: device has no room"); - Integer sourceId = getSourceIdToRemove(device); - if (sourceId != BassConstants.INVALID_SOURCE_ID) { + Integer sourceIdToRemove = getSourceIdToRemove(device); + if (sourceIdToRemove != BassConstants.INVALID_SOURCE_ID) { BluetoothLeBroadcastMetadata metaData = - stateMachine.getCurrentBroadcastMetadata(sourceId); + stateMachine.getCurrentBroadcastMetadata(sourceIdToRemove); if (metaData != null) { // Add host intentional pause if previous broadcast is different than // current @@ -2983,7 +3011,7 @@ public class BassClientService extends ProfileService { TAG, "Switch Broadcast Source: " + ("device: " + device) - + (", old SourceId: " + sourceId) + + (", old SourceId: " + sourceIdToRemove) + (", new broadcastId: " + sourceMetadata.getBroadcastId()) + (", new broadcastName: " + sourceMetadata.getBroadcastName())); @@ -2993,7 +3021,9 @@ public class BassClientService extends ProfileService { // mark group op for both remove and add source // so setSourceGroupManaged will be updated accordingly in callbacks enqueueSourceGroupOp( - device, BassClientStateMachine.REMOVE_BCAST_SOURCE, sourceId); + device, + BassClientStateMachine.REMOVE_BCAST_SOURCE, + sourceIdToRemove); enqueueSourceGroupOp( device, BassClientStateMachine.ADD_BCAST_SOURCE, sourceMetadata); } @@ -3004,7 +3034,7 @@ public class BassClientService extends ProfileService { Message message = stateMachine.obtainMessage(BassClientStateMachine.SWITCH_BCAST_SOURCE); message.obj = sourceMetadata; - message.arg1 = sourceId; + message.arg1 = sourceIdToRemove; stateMachine.sendMessage(message); } else { mCallbacks.notifySourceAddFailed( @@ -3014,22 +3044,14 @@ public class BassClientService extends ProfileService { } continue; } - if (!isValidBroadcastSourceAddition(device, sourceMetadata)) { - log("addSource: not a valid broadcast source addition"); - mCallbacks.notifySourceAddFailed( - device, - sourceMetadata, - BluetoothStatusCodes.ERROR_LE_BROADCAST_ASSISTANT_DUPLICATE_ADDITION); - continue; - } - if ((code != null) && (code.length != 0)) { - if ((code.length > 16) || (code.length < 4)) { - log( - "Invalid broadcast code length: " - + code.length - + ", should be between 4 and 16 octets"); + if (!leaudioBroadcastResyncHelper()) { + int sourceId = checkDuplicateSourceAdditionAndGetSourceId(device, sourceMetadata); + if (sourceId != BassConstants.INVALID_SOURCE_ID) { + log("addSource: not a valid broadcast source addition"); mCallbacks.notifySourceAddFailed( - device, sourceMetadata, BluetoothStatusCodes.ERROR_BAD_PARAMETERS); + device, + sourceMetadata, + BluetoothStatusCodes.ERROR_LE_BROADCAST_ASSISTANT_DUPLICATE_ADDITION); continue; } } @@ -3106,14 +3128,24 @@ public class BassClientService extends ProfileService { BluetoothDevice device = deviceSourceIdPair.getKey(); Integer deviceSourceId = deviceSourceIdPair.getValue(); BassClientStateMachine stateMachine = getOrCreateStateMachine(device); - int statusCode = - areValidParametersToModifySource( - updatedMetadata, stateMachine, deviceSourceId, device); + validateParametersForSourceOperation( + stateMachine, device, updatedMetadata, deviceSourceId); if (statusCode != BluetoothStatusCodes.SUCCESS) { mCallbacks.notifySourceModifyFailed(device, sourceId, statusCode); continue; } + if (stateMachine.hasPendingSourceOperation()) { + Log.w( + TAG, + "modifySource: source operation already pending, device: " + + device + + ", broadcastId: " + + updatedMetadata.getBroadcastId()); + mCallbacks.notifySourceModifyFailed( + device, sourceId, BluetoothStatusCodes.ERROR_ALREADY_IN_TARGET_STATE); + continue; + } sEventLogger.logd( TAG, @@ -3158,32 +3190,17 @@ public class BassClientService extends ProfileService { Map<BluetoothDevice, Integer> devices = getGroupManagedDeviceSources(sink, sourceId).second; for (Map.Entry<BluetoothDevice, Integer> deviceSourceIdPair : devices.entrySet()) { BluetoothDevice device = deviceSourceIdPair.getKey(); - Integer deviceSourceId = deviceSourceIdPair.getValue(); - BassClientStateMachine stateMachine = getOrCreateStateMachine(device); - /* Removes metadata for sink device if not paused */ if (!mPausedBroadcastSinks.contains(device)) { mBroadcastMetadataMap.remove(device); } - if (stateMachine == null) { - log("removeSource: Error bad parameters: device = " + device); - mCallbacks.notifySourceRemoveFailed( - device, sourceId, BluetoothStatusCodes.ERROR_BAD_PARAMETERS); - continue; - } - if (deviceSourceId == BassConstants.INVALID_SOURCE_ID) { - log("removeSource: no such sourceId for device: " + device); - mCallbacks.notifySourceRemoveFailed( - device, - sourceId, - BluetoothStatusCodes.ERROR_LE_BROADCAST_ASSISTANT_INVALID_SOURCE_ID); - continue; - } - if (getConnectionState(device) != BluetoothProfile.STATE_CONNECTED) { - log("removeSource: device is not connected"); - mCallbacks.notifySourceRemoveFailed( - device, sourceId, BluetoothStatusCodes.ERROR_REMOTE_LINK_ERROR); + Integer deviceSourceId = deviceSourceIdPair.getValue(); + BassClientStateMachine stateMachine = getOrCreateStateMachine(device); + int statusCode = + validateParametersForSourceOperation(stateMachine, device, deviceSourceId); + if (statusCode != BluetoothStatusCodes.SUCCESS) { + mCallbacks.notifySourceRemoveFailed(device, sourceId, statusCode); continue; } @@ -3796,36 +3813,7 @@ public class BassClientService extends ProfileService { || activeSyncedSrc.contains( getSyncHandleForBroadcastId(metadata.getBroadcastId())))) { int sourceId = receiveState.get().getSourceId(); - int statusCode = - areValidParametersToModifySource( - metadata, stateMachine, sourceId, sink); - - if (statusCode != BluetoothStatusCodes.SUCCESS) { - mCallbacks.notifySourceModifyFailed(sink, sourceId, statusCode); - // remove the device from mPausedBroadcastSinks - iterator.remove(); - continue; - } - - sEventLogger.logd( - TAG, - "Modify Broadcast Source (resume): " - + ("device: " + sink) - + (", sourceId: " + sourceId) - + (", updatedBroadcastId: " + metadata.getBroadcastId()) - + (", updatedBroadcastName: " + metadata.getBroadcastName())); - Message message = - stateMachine.obtainMessage(BassClientStateMachine.UPDATE_BCAST_SOURCE); - message.arg1 = sourceId; - message.arg2 = - DeviceConfig.getBoolean( - DeviceConfig.NAMESPACE_BLUETOOTH, - "persist.vendor.service.bt.defNoPAS", - false) - ? BassConstants.PA_SYNC_PAST_NOT_AVAILABLE - : BassConstants.PA_SYNC_PAST_AVAILABLE; - message.obj = metadata; - stateMachine.sendMessage(message); + updateSourceToResumeBroadcast(sink, sourceId, metadata); } else { addSource(sink, metadata, false); } @@ -3848,6 +3836,44 @@ public class BassClientService extends ProfileService { logPausedBroadcastsAndSinks(); } + private void updateSourceToResumeBroadcast( + BluetoothDevice sink, int sourceId, BluetoothLeBroadcastMetadata metadata) { + BassClientStateMachine stateMachine = getOrCreateStateMachine(sink); + int statusCode = + validateParametersForSourceOperation(stateMachine, sink, metadata, sourceId); + if (statusCode != BluetoothStatusCodes.SUCCESS) { + return; + } + if (stateMachine.hasPendingSourceOperation()) { + Log.w( + TAG, + "updateSourceToResumeBroadcast: source operation already pending, device: " + + sink + + ", broadcastId: " + + metadata.getBroadcastId()); + return; + } + + sEventLogger.logd( + TAG, + "Modify Broadcast Source (resume): " + + ("device: " + sink) + + (", sourceId: " + sourceId) + + (", updatedBroadcastId: " + metadata.getBroadcastId()) + + (", updatedBroadcastName: " + metadata.getBroadcastName())); + Message message = stateMachine.obtainMessage(BassClientStateMachine.UPDATE_BCAST_SOURCE); + message.arg1 = sourceId; + message.arg2 = + DeviceConfig.getBoolean( + DeviceConfig.NAMESPACE_BLUETOOTH, + "persist.vendor.service.bt.defNoPAS", + false) + ? BassConstants.PA_SYNC_PAST_NOT_AVAILABLE + : BassConstants.PA_SYNC_PAST_AVAILABLE; + message.obj = metadata; + stateMachine.sendMessage(message); + } + /** Handle Unicast source stream status change */ public void handleUnicastSourceStreamStatusChange(int status) { mUnicastSourceStreamStatus = Optional.of(status); 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 021b73289b..5954b827b0 100644 --- a/android/app/src/com/android/bluetooth/bass_client/BassClientStateMachine.java +++ b/android/app/src/com/android/bluetooth/bass_client/BassClientStateMachine.java @@ -1151,6 +1151,7 @@ class BassClientStateMachine extends StateMachine { log("processBroadcastReceiverState: invalid index: " + recvState.getSourceId()); return; } + int sourceId = recvState.getSourceId(); BluetoothLeBroadcastReceiveState oldRecvState = mBluetoothLeBroadcastReceiveStates.get(characteristic.getInstanceId()); if (oldRecvState == null) { @@ -1178,7 +1179,7 @@ class BassClientStateMachine extends StateMachine { .notifySourceAdded( mDevice, recvState, BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST); if (mPendingMetadata != null) { - setCurrentBroadcastMetadata(recvState.getSourceId(), mPendingMetadata); + setCurrentBroadcastMetadata(sourceId, mPendingMetadata); mPendingMetadata = null; } checkAndUpdateBroadcastCode(recvState); @@ -1224,28 +1225,28 @@ class BassClientStateMachine extends StateMachine { } else { log("update to an existing recvState"); if (mPendingMetadata != null) { - setCurrentBroadcastMetadata(recvState.getSourceId(), mPendingMetadata); + setCurrentBroadcastMetadata(sourceId, mPendingMetadata); mPendingMetadata = null; } removeMessages(CANCEL_PENDING_SOURCE_OPERATION); mService.getCallbacks() .notifySourceModified( mDevice, - recvState.getSourceId(), + sourceId, BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST); checkAndUpdateBroadcastCode(recvState); processPASyncState(recvState); processSyncStateChangeStats(recvState); - if (isPendingRemove(recvState.getSourceId())) { + if (isPendingRemove(sourceId) && !isSyncedToTheSource(sourceId)) { Message message = obtainMessage(REMOVE_BCAST_SOURCE); - message.arg1 = recvState.getSourceId(); + message.arg1 = sourceId; sendMessage(message); } } } } - broadcastReceiverState(recvState, recvState.getSourceId()); + broadcastReceiverState(recvState, sourceId); } // Implements callback methods for GATT events that the app cares about. @@ -1916,7 +1917,7 @@ class BassClientStateMachine extends StateMachine { res[offset++] = (byte) numSubGroups; for (int i = 0; i < numSubGroups; i++) { - int bisIndexValue = existingState.getBisSyncState().get(i).intValue(); + int bisIndexValue = 0xFFFFFFFF; if (paSync == BassConstants.PA_SYNC_DO_NOT_SYNC) { bisIndexValue = 0; } else if (metaData != null @@ -1929,6 +1930,8 @@ class BassClientStateMachine extends StateMachine { if (bisIndexValue == 0) { bisIndexValue = 0xFFFFFFFF; } + } else if (i < existingState.getBisSyncState().size()) { + bisIndexValue = existingState.getBisSyncState().get(i).intValue(); } log("UPDATE_BCAST_SOURCE: bisIndexValue : " + bisIndexValue); // BIS_Sync diff --git a/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java b/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java index 4b563ac248..c75097f226 100644 --- a/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java +++ b/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java @@ -614,11 +614,24 @@ public class ActiveDeviceManager implements AdapterService.BluetoothStateCallbac if (device != null) { setHearingAidActiveDevice(null, true); } - if (Utils.isDualModeAudioEnabled() - && mAdapterService.isAllSupportedClassicAudioProfilesActive(device)) { - setLeAudioActiveDevice(device); - } else { - setLeAudioActiveDevice(null, true); + + if (Utils.isDualModeAudioEnabled()) { + if (device != null) { + boolean isDualModeDevice = + mAdapterService.isAllSupportedClassicAudioProfilesActive(device); + if (isDualModeDevice) { + setLeAudioActiveDevice(device); + } + } else { + boolean wasDualModeDevice = + mAdapterService.isAllSupportedClassicAudioProfilesActive( + mA2dpActiveDevice); + if (wasDualModeDevice) { + // remove LE audio active device when it was actived as dual mode device + // before + setLeAudioActiveDevice(null, true); + } + } } } // Just assign locally the new value @@ -677,28 +690,42 @@ public class ActiveDeviceManager implements AdapterService.BluetoothStateCallbac + device + ", mHfpActiveDevice=" + mHfpActiveDevice); + if (!Objects.equals(mHfpActiveDevice, device)) { if (device != null) { setHearingAidActiveDevice(null, true); } - if (Utils.isDualModeAudioEnabled() - && mAdapterService.isAllSupportedClassicAudioProfilesActive(device)) { - setLeAudioActiveDevice(device); - } else { + + if (Utils.isDualModeAudioEnabled()) { if (device != null) { - // remove LE audio active device when it is not null, and not dual mode - setLeAudioActiveDevice(null, true); + boolean isDualModeDevice = + mAdapterService.isAllSupportedClassicAudioProfilesActive(device); + if (isDualModeDevice) { + setLeAudioActiveDevice(device); + } } else { - Log.d( - TAG, - "HFP active device is null. Try to fallback to le audio active" - + " device"); + boolean wasDualModeDevice = + mAdapterService.isAllSupportedClassicAudioProfilesActive( + mA2dpActiveDevice); + if (wasDualModeDevice) { + // remove LE audio active device when it was actived as dual mode device + // before + setLeAudioActiveDevice(null, true); + } + + Log.d(TAG, "HFP active device is null. Try to fallback to le audio device"); synchronized (mLock) { - setFallbackDeviceActiveLocked(device); + setFallbackDeviceActiveLocked(null); } } + } else { + Log.d(TAG, "HFP active device is null. Try to fallback to le audio device"); + synchronized (mLock) { + setFallbackDeviceActiveLocked(null); + } } } + // Just assign locally the new value mHfpActiveDevice = device; diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterService.java b/android/app/src/com/android/bluetooth/btservice/AdapterService.java index 695ad6e138..ed4797ec2f 100644 --- a/android/app/src/com/android/bluetooth/btservice/AdapterService.java +++ b/android/app/src/com/android/bluetooth/btservice/AdapterService.java @@ -4327,6 +4327,55 @@ public class AdapterService extends Service { service.enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, null); return service.mDatabaseManager.getActiveAudioDevicePolicy(device); } + + @Override + public int setMicrophonePreferredForCalls( + BluetoothDevice device, boolean enabled, AttributionSource source) { + requireNonNull(device); + AdapterService service = getService(); + if (service == null) { + return BluetoothStatusCodes.ERROR_BLUETOOTH_NOT_ENABLED; + } + if (!callerIsSystemOrActiveOrManagedUser( + service, TAG, "setMicrophonePreferredForCalls")) { + 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, "AdapterService setMicrophonePreferredForCalls")) { + return BluetoothStatusCodes.ERROR_MISSING_BLUETOOTH_CONNECT_PERMISSION; + } + + service.enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, null); + return service.mDatabaseManager.setMicrophonePreferredForCalls(device, enabled); + } + + @Override + public boolean isMicrophonePreferredForCalls( + BluetoothDevice device, AttributionSource source) { + requireNonNull(device); + AdapterService service = getService(); + if (service == null) { + return true; + } + if (!callerIsSystemOrActiveOrManagedUser( + service, TAG, "isMicrophonePreferredForCalls")) { + throw new IllegalStateException( + "Caller is not the system or part of the active/managed user"); + } + if (!BluetoothAdapter.checkBluetoothAddress(device.getAddress())) { + throw new IllegalArgumentException("device cannot have an invalid address"); + } + if (!Utils.checkConnectPermissionForDataDelivery( + service, source, "AdapterService isMicrophonePreferredForCalls")) { + return true; + } + + service.enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, null); + return service.mDatabaseManager.isMicrophonePreferredForCalls(device); + } } /** @@ -5165,6 +5214,10 @@ public class AdapterService extends Service { */ mLeAudioService.removeActiveDevice(true /* hasFallbackDevice */); } else { + if (mA2dpService != null && mA2dpService.getActiveDevice() != null) { + // TODO: b/312396770 + mA2dpService.removeActiveDevice(false); + } mLeAudioService.setActiveDevice(device); } } diff --git a/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java b/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java index 6909bc6d49..6d5bb49338 100644 --- a/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java +++ b/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java @@ -545,6 +545,7 @@ final class BondStateMachine extends StateMachine { if (oldState == newState) { return; } + MetricsLogger.getInstance().logBondStateMachineEvent(device, newState); BluetoothStatsLog.write( BluetoothStatsLog.BLUETOOTH_BOND_STATE_CHANGED, mAdapterService.obfuscateAddress(device), diff --git a/android/app/src/com/android/bluetooth/btservice/MedicalDeviceBloomfilterGenerator.java b/android/app/src/com/android/bluetooth/btservice/MedicalDeviceBloomfilterGenerator.java new file mode 100644 index 0000000000..06055cfc8f --- /dev/null +++ b/android/app/src/com/android/bluetooth/btservice/MedicalDeviceBloomfilterGenerator.java @@ -0,0 +1,76 @@ +/* + * Copyright (C) 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. + */ +package com.android.bluetooth.btservice; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; + +/** Class to generate a medical device bloomfilter */ +public class MedicalDeviceBloomfilterGenerator { + + public static final String BLOOM_FILTER_DEFAULT = + "01070000003C01002106584044800850055" + + "002308488410020D9A00001138410510000" + + "000042004200000000000C2000000040064" + + "0120080020110412A500090520210040C40" + + "4002601040005004400148414006198A041" + + "00890000600400000800210041810600800" + + "0142208000721A030000028102448201110" + + "0002007120020101448C211490A2B000084" + + "C010004004C00C080808200026210608110" + + "200011200000015000000212C4400040802" + + "00111114840000001002080040186000404" + + "81C064400052381109017039900000200C9" + + "C0002E6480000101C40000601064001A018" + + "40440280A810001000040455A0404617034" + + "50000140040D020020C6204100804041600" + + "80840002000800804280028000440000122" + + "00808409905022000590000110448080400" + + "561004210020430092602000040C0090C00" + + "C18480020000519C1482100111011120390" + + "02C0000228208104800C050440000004040" + + "00871400882400140080000005308124900" + + "104000040002410508CA349000200000202" + + "90200920181890100800110220A20874820" + + "0428080054A0005101C0820060090080040" + + "6820C480F40081014010201800000018101" + + "208914100321008006520002030010800C4" + + "1022C000048206002010041220000008021" + + "002080314040000100030002008"; + + /** Provide byte[] version of a given string */ + public static byte[] hexStringToByteArray(String s) { + int len = s.length(); + byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + data[i / 2] = + (byte) + ((Character.digit(s.charAt(i), 16) << 4) + + Character.digit(s.charAt(i + 1), 16)); + } + return data; + } + + /** Generate bloom filter file given filePath */ + public static void generateDefaultBloomfilter(String filePath) throws IOException { + File outputFile = new File(filePath); + outputFile.createNewFile(); // if file already exists will do nothing + FileOutputStream fos = new FileOutputStream(filePath); + fos.write(hexStringToByteArray(BLOOM_FILTER_DEFAULT)); + fos.close(); + } +} diff --git a/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java b/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java index 98040486db..b74220c9ea 100644 --- a/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java +++ b/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java @@ -15,6 +15,7 @@ */ package com.android.bluetooth.btservice; +import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__BOND; import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__PROFILE_CONNECTION; import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__PROFILE_CONNECTION_A2DP; import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__PROFILE_CONNECTION_A2DP_SINK; @@ -31,6 +32,8 @@ import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVEN import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__PROFILE_CONNECTION_PAN; import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__PROFILE_CONNECTION_PBAP_CLIENT; import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__PROFILE_CONNECTION_VOLUME_CONTROL; +import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__STATE__STATE_BONDED; +import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__STATE__STATE_NONE; import static com.android.bluetooth.BtRestrictedStatsLog.RESTRICTED_BLUETOOTH_DEVICE_NAME_REPORTED; import android.app.AlarmManager; @@ -96,7 +99,10 @@ public class MetricsLogger { private static final String TAG = "BluetoothMetricsLogger"; private static final String BLOOMFILTER_PATH = "/data/misc/bluetooth"; private static final String BLOOMFILTER_FILE = "/devices_for_metrics_v3"; + private static final String MEDICAL_DEVICE_BLOOMFILTER_FILE = "/medical_devices_for_metrics_v1"; public static final String BLOOMFILTER_FULL_PATH = BLOOMFILTER_PATH + BLOOMFILTER_FILE; + public static final String MEDICAL_DEVICE_BLOOMFILTER_FULL_PATH = + BLOOMFILTER_PATH + MEDICAL_DEVICE_BLOOMFILTER_FILE; // 6 hours timeout for counter metrics private static final long BLUETOOTH_COUNTER_METRICS_ACTION_DURATION_MILLIS = 6L * 3600L * 1000L; @@ -114,6 +120,10 @@ public class MetricsLogger { private BloomFilter<byte[]> mBloomFilter = null; protected boolean mBloomFilterInitialized = false; + private BloomFilter<byte[]> mMedicalDeviceBloomFilter = null; + + protected boolean mMedicalDeviceBloomFilterInitialized = false; + private AlarmManager.OnAlarmListener mOnAlarmListener = new AlarmManager.OnAlarmListener() { @Override @@ -185,10 +195,48 @@ public class MetricsLogger { return true; } + /** Initialize medical device bloom filter */ + public boolean initMedicalDeviceBloomFilter(String path) { + try { + File medicalDeviceFile = new File(path); + if (!medicalDeviceFile.exists()) { + Log.w(TAG, "MetricsLogger is creating a new medical device Bloomfilter file"); + MedicalDeviceBloomfilterGenerator.generateDefaultBloomfilter(path); + } + + FileInputStream inputStream = new FileInputStream(new File(path)); + mMedicalDeviceBloomFilter = + BloomFilter.readFrom(inputStream, Funnels.byteArrayFunnel()); + mMedicalDeviceBloomFilterInitialized = true; + } catch (IOException e1) { + Log.w(TAG, "MetricsLogger can't read the medical device BloomFilter file."); + byte[] bloomfilterData = + MedicalDeviceBloomfilterGenerator.hexStringToByteArray( + MedicalDeviceBloomfilterGenerator.BLOOM_FILTER_DEFAULT); + try { + mMedicalDeviceBloomFilter = + BloomFilter.readFrom( + new ByteArrayInputStream(bloomfilterData), + Funnels.byteArrayFunnel()); + mMedicalDeviceBloomFilterInitialized = true; + Log.i(TAG, "The medical device bloomfilter is used"); + return true; + } catch (IOException e2) { + Log.w(TAG, "The medical device bloomfilter can't be used."); + } + return false; + } + return true; + } + protected void setBloomfilter(BloomFilter bloomfilter) { mBloomFilter = bloomfilter; } + protected void setMedicalDeviceBloomfilter(BloomFilter bloomfilter) { + mMedicalDeviceBloomFilter = bloomfilter; + } + void init(AdapterService adapterService, RemoteDevices remoteDevices) { if (mInitialized) { return; @@ -203,6 +251,12 @@ public class MetricsLogger { // We still want to use this class even if the bloomfilter isn't initialized // so still return true here. } + if (!initMedicalDeviceBloomFilter(MEDICAL_DEVICE_BLOOMFILTER_FULL_PATH)) { + Log.w(TAG, "MetricsLogger can't initialize the medical device bloomfilter"); + // The class is for multiple metrics tasks. + // We still want to use this class even if the bloomfilter isn't initialized + // so still return true here. + } IntentFilter filter = new IntentFilter(); filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); filter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED); @@ -289,7 +343,8 @@ public class MetricsLogger { BluetoothDevice device = connIntent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); int state = connIntent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1); int metricId = mAdapterService.getMetricId(device); - byte[] remoteDeviceInfoBytes = getRemoteDeviceInfoProto(device); + boolean includeMedicalDevices = false; + byte[] remoteDeviceInfoBytes = getRemoteDeviceInfoProto(device, includeMedicalDevices); if (state == BluetoothProfile.STATE_CONNECTING) { String deviceName = mRemoteDevices.getName(device); BluetoothStatsLog.write( @@ -417,6 +472,7 @@ public class MetricsLogger { mAdapterService = null; mInitialized = false; mBloomFilterInitialized = false; + mMedicalDeviceBloomFilterInitialized = false; } protected void cancelPendingDrain() { @@ -446,15 +502,31 @@ public class MetricsLogger { /** * Retrieves a byte array containing serialized remote device information for the specified - * BluetoothDevice. This data can be used for remote device identification and logging. + * BluetoothDevice. This data can be used for remote device identification and logging. Does not + * include medical remote devices. * * @param device The BluetoothDevice for which to retrieve device information. * @return A byte array containing the serialized remote device information. */ public byte[] getRemoteDeviceInfoProto(BluetoothDevice device) { - if (!mInitialized) { - return null; - } + return mInitialized ? buildRemoteDeviceInfoProto(device, false) : null; + } + + /** + * Retrieves a byte array containing serialized remote device information for the specified + * BluetoothDevice. This data can be used for remote device identification and logging. + * + * @param device The BluetoothDevice for which to retrieve device information. + * @param includeMedicalDevices Should be true only if logging as de-identified metric, + * otherwise false. + * @return A byte array containing the serialized remote device information. + */ + public byte[] getRemoteDeviceInfoProto(BluetoothDevice device, boolean includeMedicalDevices) { + return mInitialized ? buildRemoteDeviceInfoProto(device, includeMedicalDevices) : null; + } + + private byte[] buildRemoteDeviceInfoProto( + BluetoothDevice device, boolean includeMedicalDevices) { ProtoOutputStream proto = new ProtoOutputStream(); // write Allowlisted Device Name Hash @@ -463,7 +535,8 @@ public class MetricsLogger { ProtoOutputStream.FIELD_TYPE_STRING, ProtoOutputStream.FIELD_COUNT_SINGLE, BluetoothRemoteDeviceInformation.ALLOWLISTED_DEVICE_NAME_HASH_FIELD_NUMBER, - getAllowlistedDeviceNameHash(mAdapterService.getRemoteName(device))); + getAllowlistedDeviceNameHash( + mAdapterService.getRemoteName(device), includeMedicalDevices)); // write COD writeFieldIfNotNull( @@ -567,7 +640,7 @@ public class MetricsLogger { } } - private String getMatchedString(List<String> wordBreakdownList) { + private String getMatchedString(List<String> wordBreakdownList, boolean includeMedicalDevices) { if (!mBloomFilterInitialized || wordBreakdownList.isEmpty()) { return ""; } @@ -579,6 +652,21 @@ public class MetricsLogger { matchedString = word; } } + + return (matchedString.equals("") && includeMedicalDevices) + ? getMatchedStringForMedicalDevice(wordBreakdownList) + : matchedString; + } + + private String getMatchedStringForMedicalDevice(List<String> wordBreakdownList) { + String matchedString = ""; + for (String word : wordBreakdownList) { + byte[] sha256 = getSha256(word); + if (mMedicalDeviceBloomFilter.mightContain(sha256) + && word.length() > matchedString.length()) { + matchedString = word; + } + } return matchedString; } @@ -664,16 +752,18 @@ public class MetricsLogger { advDurationMs); } - protected String getAllowlistedDeviceNameHash(String deviceName) { + protected String getAllowlistedDeviceNameHash( + String deviceName, boolean includeMedicalDevices) { List<String> wordBreakdownList = getWordBreakdownList(deviceName); - String matchedString = getMatchedString(wordBreakdownList); + String matchedString = getMatchedString(wordBreakdownList, includeMedicalDevices); return getSha256String(matchedString); } protected String logAllowlistedDeviceNameHash( int metricId, String deviceName, boolean logRestrictedNames) { List<String> wordBreakdownList = getWordBreakdownList(deviceName); - String matchedString = getMatchedString(wordBreakdownList); + boolean includeMedicalDevices = false; + String matchedString = getMatchedString(wordBreakdownList, includeMedicalDevices); if (logRestrictedNames) { // Log the restricted bluetooth device name if (SdkLevel.isAtLeastU()) { @@ -695,7 +785,7 @@ public class MetricsLogger { public void logBluetoothEvent(BluetoothDevice device, int eventType, int state, int uid) { - if (mAdapterService.getMetricId(device) == 0 || !mInitialized) { + if (!mInitialized || mAdapterService.getMetricId(device) == 0) { return; } @@ -705,7 +795,7 @@ public class MetricsLogger { state, uid, mAdapterService.getMetricId(device), - getRemoteDeviceInfoProto(device)); + getRemoteDeviceInfoProto(device, false)); } protected static String getSha256String(String name) { @@ -815,6 +905,27 @@ public class MetricsLogger { sessionStatus); } + /** Logs Bond State Machine event */ + public void logBondStateMachineEvent(BluetoothDevice device, int bondState) { + switch (bondState) { + case BluetoothDevice.BOND_NONE: + logBluetoothEvent( + device, + BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__BOND, + BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__STATE__STATE_NONE, + 0); + break; + case BluetoothDevice.BOND_BONDED: + logBluetoothEvent( + device, + BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__BOND, + BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__STATE__STATE_BONDED, + 0); + break; + default: + } + } + /** Logs LE Audio Broadcast audio sync. */ public void logLeAudioBroadcastAudioSync( BluetoothDevice device, @@ -836,6 +947,6 @@ public class MetricsLogger { latencyPaSyncMs, latencyBisSyncMs, syncStatus, - getRemoteDeviceInfoProto(device)); + getRemoteDeviceInfoProto(device, false)); } } diff --git a/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java b/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java index 1dcef80a66..be7af84c0d 100644 --- a/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java +++ b/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java @@ -281,16 +281,23 @@ public class PhonePolicy implements AdapterService.BluetoothStateCallback { return isLeAudioOnlyGroup(device); } + private static final String SYSPROP_HAP_ENABLED = "bluetooth.profile.hap.enabled_by_default"; + // return true if device support Hearing Access Service and it has not been manually disabled private boolean shouldEnableHapByDefault(BluetoothDevice device, ParcelUuid[] uuids) { if (!Flags.enableHapByDefault()) { - Log.i(TAG, "shouldDefaultToHap: Flag enableHapByDefault is disabled"); + Log.i(TAG, "shouldEnableHapByDefault: Flag is disabled"); return false; } HapClientService hap = mFactory.getHapClientService(); if (hap == null) { - Log.e(TAG, "shouldDefaultToHap: HapClient is null"); + Log.e(TAG, "shouldEnableHapByDefault: No HapClientService"); + return false; + } + + if (!SystemProperties.getBoolean(SYSPROP_HAP_ENABLED, true)) { + Log.i(TAG, "shouldEnableHapByDefault: SystemProperty is overridden to false"); return false; } 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 32379933d9..1d8b7f9dc7 100644 --- a/android/app/src/com/android/bluetooth/btservice/storage/DatabaseManager.java +++ b/android/app/src/com/android/bluetooth/btservice/storage/DatabaseManager.java @@ -1093,6 +1093,56 @@ public class DatabaseManager { } /** + * Sets the preferred microphone for calls enable status for this device. See {@link + * BluetoothDevice#setMicrophonePreferredForCalls()} for more details. + * + * @param device is the remote device for which we set the preferred microphone for calls enable + * status + * @param enabled {@code true} to enable the preferred microphone for calls + * @return whether the preferred microphone for call enable status was set properly + */ + public int setMicrophonePreferredForCalls(BluetoothDevice device, boolean enabled) { + 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, "setMicrophoneForCallEnabled(" + device + ", " + enabled + ")"); + metadata.is_preferred_microphone_for_calls = enabled; + + updateDatabase(metadata); + } + return BluetoothStatusCodes.SUCCESS; + } + + /** + * Gets the preferred microphone for calls enable status for this device. See {@link + * BluetoothDevice#isMicrophonePreferredForCalls()} for more details. + * + * @param device is the remote device for which we get the preferred microphone for calls enable + * status + * @return {@code true} if the preferred microphone is enabled for calls + */ + public boolean isMicrophonePreferredForCalls(BluetoothDevice device) { + synchronized (mMetadataCache) { + String address = device.getAddress(); + + if (!mMetadataCache.containsKey(address)) { + Log.e(TAG, "device is not bonded"); + return true; + } + + Metadata metadata = mMetadataCache.get(address); + + return metadata.is_preferred_microphone_for_calls; + } + } + + /** * Get the {@link Looper} for the handler thread. This is used in testing and helper objects * * @return {@link Looper} for the handler thread 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 3e86bf9229..43bd50afb1 100644 --- a/android/app/src/com/android/bluetooth/btservice/storage/Metadata.java +++ b/android/app/src/com/android/bluetooth/btservice/storage/Metadata.java @@ -28,13 +28,11 @@ import androidx.room.Embedded; import androidx.room.Entity; import androidx.room.PrimaryKey; -import com.android.internal.annotations.VisibleForTesting; - import java.util.ArrayList; import java.util.List; @Entity(tableName = "metadata") -@VisibleForTesting + public class Metadata { @PrimaryKey @NonNull private String address; @@ -73,6 +71,9 @@ public class Metadata { /** This is used to indicate whether device's active audio policy */ public int active_audio_device_policy; + /** This is used to indicate whether device's microphone prefer to use during calls */ + public boolean is_preferred_microphone_for_calls; + Metadata(String address) { this(address, false, false); } @@ -91,6 +92,7 @@ public class Metadata { preferred_output_only_profile = 0; preferred_duplex_profile = 0; active_audio_device_policy = BluetoothDevice.ACTIVE_AUDIO_DEVICE_POLICY_DEFAULT; + is_preferred_microphone_for_calls = true; } static final class Builder { @@ -117,7 +119,6 @@ public class Metadata { } } - @VisibleForTesting public String getAddress() { return address; } @@ -205,7 +206,6 @@ public class Metadata { } } - @VisibleForTesting public int getProfileConnectionPolicy(int profile) { switch (profile) { case BluetoothProfile.A2DP: @@ -345,7 +345,6 @@ public class Metadata { } } - @VisibleForTesting public byte[] getCustomizedMeta(int key) { byte[] value = null; switch (key) { @@ -470,6 +469,8 @@ public class Metadata { .append(publicMetadata) .append("), hfp client audio policy(") .append(audioPolicyMetadata) + .append("), is_preferred_microphone_for_calls(") + .append(is_preferred_microphone_for_calls) .append(")}"); return builder.toString(); 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 fd580b00fc..0a9df7f70d 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 = 120) + version = 121) public abstract class MetadataDatabase extends RoomDatabase { /** The metadata database file name */ public static final String DATABASE_NAME = "bluetooth_db"; @@ -70,6 +70,7 @@ public abstract class MetadataDatabase extends RoomDatabase { .addMigrations(MIGRATION_117_118) .addMigrations(MIGRATION_118_119) .addMigrations(MIGRATION_119_120) + .addMigrations(MIGRATION_120_121) .allowMainThreadQueries() .build(); } @@ -671,4 +672,26 @@ public abstract class MetadataDatabase extends RoomDatabase { } } }; + + @VisibleForTesting + static final Migration MIGRATION_120_121 = + new Migration(120, 121) { + @Override + public void migrate(SupportSQLiteDatabase database) { + try { + database.execSQL( + "ALTER TABLE metadata ADD COLUMN" + + " `is_preferred_microphone_for_calls` INTEGER NOT NULL" + + " DEFAULT 1"); + } 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("is_preferred_microphone_for_calls") + == -1) { + throw ex; + } + } + } + }; } diff --git a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java index 1b78fef4e5..850fb72819 100644 --- a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java +++ b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java @@ -120,7 +120,8 @@ public class DistanceMeasurementManager { startRssiTracker(tracker); break; case DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_CHANNEL_SOUNDING: - if (!mAdapterService.isConnected(params.getDevice())) { + if (!mAdapterService.isLeChannelSoundingSupported() + || !mAdapterService.isConnected(params.getDevice())) { Log.e(TAG, "Device " + params.getDevice() + " is not connected"); invokeStartFail( callback, 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 0683607ef5..2e0a80c2df 100644 --- a/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java +++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java @@ -25,6 +25,7 @@ import static com.android.bluetooth.bass_client.BassConstants.INVALID_BROADCAST_ import static com.android.bluetooth.flags.Flags.leaudioAllowedContextMask; import static com.android.bluetooth.flags.Flags.leaudioBigDependsOnAudioState; import static com.android.bluetooth.flags.Flags.leaudioBroadcastAssistantPeripheralEntrustment; +import static com.android.bluetooth.flags.Flags.leaudioBroadcastApiManagePrimaryGroup; import static com.android.bluetooth.flags.Flags.leaudioUseAudioModeListener; import static com.android.modules.utils.build.SdkLevel.isAtLeastU; @@ -2943,6 +2944,22 @@ public class LeAudioService extends ProfileService { } } + private void notifyBroadcastToUnicastFallbackGroupChanged(int groupId) { + synchronized (mLeAudioCallbacks) { + int n = mLeAudioCallbacks.beginBroadcast(); + for (int i = 0; i < n; i++) { + try { + mLeAudioCallbacks + .getBroadcastItem(i) + .onBroadcastToUnicastFallbackGroupChanged(groupId); + } catch (RemoteException e) { + continue; + } + } + mLeAudioCallbacks.finishBroadcast(); + } + } + private void setGroupAllowedContextMask( int groupId, int sinkContextTypes, int sourceContextTypes) { if (!mLeAudioNativeIsInitialized) { @@ -5075,6 +5092,11 @@ public class LeAudioService extends ProfileService { * @param groupId group id to update */ private void updateFallbackUnicastGroupIdForBroadcast(int groupId) { + if (leaudioBroadcastApiManagePrimaryGroup() + && mUnicastGroupIdDeactivatedForBroadcastTransition == groupId) { + Log.d(TAG, "Skip updateFallbackUnicastGroupIdForBroadcast, already is primary"); + return; + } Log.i( TAG, "Update unicast fallback active group from: " @@ -5097,6 +5119,10 @@ public class LeAudioService extends ProfileService { } finally { Binder.restoreCallingIdentity(callingIdentity); } + + if (leaudioBroadcastApiManagePrimaryGroup()) { + mHandler.post(() -> notifyBroadcastToUnicastFallbackGroupChanged(groupId)); + } } private boolean isAudioModeChangedFromCommunicationToNormal(int previousMode, int currentMode) { diff --git a/android/app/src/com/android/bluetooth/vc/VolumeControlInputDescriptor.java b/android/app/src/com/android/bluetooth/vc/VolumeControlInputDescriptor.java index 4e81095a31..1b2be24648 100644 --- a/android/app/src/com/android/bluetooth/vc/VolumeControlInputDescriptor.java +++ b/android/app/src/com/android/bluetooth/vc/VolumeControlInputDescriptor.java @@ -16,38 +16,49 @@ package com.android.bluetooth.vc; +import static com.android.bluetooth.Utils.RemoteExceptionIgnoringConsumer; + +import static java.util.Objects.requireNonNull; + +import android.bluetooth.AudioInputControl.AudioInputStatus; +import android.bluetooth.AudioInputControl.AudioInputType; +import android.bluetooth.AudioInputControl.GainMode; +import android.bluetooth.AudioInputControl.Mute; +import android.bluetooth.BluetoothDevice; +import android.bluetooth.IAudioInputCallback; +import android.os.RemoteCallbackList; import android.util.Log; import com.android.bluetooth.btservice.ProfileService; -import bluetooth.constants.AudioInputType; -import bluetooth.constants.aics.AudioInputStatus; -import bluetooth.constants.aics.GainMode; -import bluetooth.constants.aics.Mute; - class VolumeControlInputDescriptor { private static final String TAG = VolumeControlInputDescriptor.class.getSimpleName(); + final VolumeControlNativeInterface mNativeInterface; + final BluetoothDevice mDevice; final Descriptor[] mVolumeInputs; - VolumeControlInputDescriptor(int numberOfExternalInputs) { + VolumeControlInputDescriptor( + VolumeControlNativeInterface nativeInterface, + BluetoothDevice device, + int numberOfExternalInputs) { + mNativeInterface = requireNonNull(nativeInterface); + mDevice = requireNonNull(device); mVolumeInputs = new Descriptor[numberOfExternalInputs]; - // Stack delivers us number of audio inputs. ids are countinous from [0;n[ + // Stack delivers us number of AICSs instances. ids are countinous from [0;n[ for (int i = 0; i < numberOfExternalInputs; i++) { mVolumeInputs[i] = new Descriptor(); } } private static class Descriptor { - int mStatus = AudioInputStatus.INACTIVE; + @AudioInputStatus int mStatus = bluetooth.constants.aics.AudioInputStatus.INACTIVE; - int mType = AudioInputType.UNSPECIFIED; + @AudioInputType int mType = bluetooth.constants.AudioInputType.UNSPECIFIED; int mGainSetting = 0; - - int mGainMode = GainMode.MANUAL_ONLY; - - int mMute = Mute.DISABLED; + @Mute int mMute = bluetooth.constants.aics.Mute.DISABLED; + @GainMode int mGainMode = bluetooth.constants.aics.GainMode.MANUAL_ONLY; /* See AICS 1.0 * The Gain_Setting (mGainSetting) field is a signed value for which a single increment or @@ -57,10 +68,32 @@ class VolumeControlInputDescriptor { */ int mGainSettingsUnits = 0; - int mGainSettingsMaxSetting = 0; - int mGainSettingsMinSetting = 0; + int mGainSettingsMax = 0; + int mGainSettingsMin = 0; String mDescription = ""; + boolean mDescriptionIsWritable = false; + + private final RemoteCallbackList<IAudioInputCallback> mCallbacks = + new RemoteCallbackList<>(); + + void registerCallback(IAudioInputCallback callback) { + mCallbacks.register(callback); + } + + void unregisterCallback(IAudioInputCallback callback) { + mCallbacks.unregister(callback); + } + + synchronized void broadcast( + String logAction, RemoteExceptionIgnoringConsumer<IAudioInputCallback> action) { + final int itemCount = mCallbacks.beginBroadcast(); + Log.d(TAG, "Broadcasting " + logAction + "() to " + itemCount + " receivers."); + for (int i = 0; i < itemCount; i++) { + action.accept(mCallbacks.getBroadcastItem(i)); + } + mCallbacks.finishBroadcast(); + } } int size() { @@ -75,19 +108,40 @@ class VolumeControlInputDescriptor { return true; } - void setStatus(int id, int status) { + void registerCallback(int id, IAudioInputCallback callback) { + if (!isValidId(id)) return; + mVolumeInputs[id].registerCallback(callback); + } + + void unregisterCallback(int id, IAudioInputCallback callback) { + if (!isValidId(id)) return; + mVolumeInputs[id].unregisterCallback(callback); + } + + void onStatusChanged(int id, @AudioInputStatus int status) { if (!isValidId(id)) return; mVolumeInputs[id].mStatus = status; + mVolumeInputs[id].broadcast("onStatusChanged", (c) -> c.onStatusChanged(status)); } int getStatus(int id) { - if (!isValidId(id)) return AudioInputStatus.INACTIVE; + if (!isValidId(id)) return bluetooth.constants.aics.AudioInputStatus.INACTIVE; return mVolumeInputs[id].mStatus; } - void setDescription(int id, String description) { - if (!isValidId(id)) return; - mVolumeInputs[id].mDescription = description; + boolean isDescriptionWritable(int id) { + if (!isValidId(id)) return false; + return mVolumeInputs[id].mDescriptionIsWritable; + } + + boolean setDescription(int id, String description) { + if (!isValidId(id)) return false; + + if (!mVolumeInputs[id].mDescriptionIsWritable) { + throw new IllegalStateException("Description is not writable"); + } + + return mNativeInterface.setExtAudioInDescription(mDevice, id, description); } String getDescription(int id) { @@ -95,48 +149,136 @@ class VolumeControlInputDescriptor { return mVolumeInputs[id].mDescription; } + void onDescriptionChanged(int id, String description, boolean isWritable) { + if (!isValidId(id)) return; + Descriptor desc = mVolumeInputs[id]; + + desc.mDescription = description; + desc.mDescriptionIsWritable = isWritable; + desc.broadcast("onDescriptionChanged", c -> c.onDescriptionChanged(description)); + } + void setType(int id, int type) { if (!isValidId(id)) return; mVolumeInputs[id].mType = type; } int getType(int id) { - if (!isValidId(id)) return AudioInputType.UNSPECIFIED; + if (!isValidId(id)) return bluetooth.constants.AudioInputType.UNSPECIFIED; return mVolumeInputs[id].mType; } + void onGainSettingsPropertiesChanged(int id, int gainUnit, int gainMin, int gainMax) { + if (!isValidId(id)) return; + + mVolumeInputs[id].mGainSettingsUnits = gainUnit; + mVolumeInputs[id].mGainSettingsMin = gainMin; + mVolumeInputs[id].mGainSettingsMax = gainMax; + } + + int getGainSettingUnit(int id) { + if (!isValidId(id)) return 0; + return mVolumeInputs[id].mGainSettingsUnits; + } + + int getGainSettingMin(int id) { + if (!isValidId(id)) return 0; + return mVolumeInputs[id].mGainSettingsMin; + } + + int getGainSettingMax(int id) { + if (!isValidId(id)) return 0; + return mVolumeInputs[id].mGainSettingsMax; + } + + void onStateChanged(int id, int gainSetting, @Mute int mute, @GainMode int gainMode) { + if (!isValidId(id)) return; + + Descriptor desc = mVolumeInputs[id]; + + if (gainSetting > desc.mGainSettingsMax || gainSetting < desc.mGainSettingsMin) { + Log.e(TAG, "Request fail. Illegal gainSetting argument: " + gainSetting); + return; + } + + desc.mGainSetting = gainSetting; + desc.mMute = mute; + desc.mGainMode = gainMode; + + mVolumeInputs[id].broadcast( + "onStateChanged", (c) -> c.onStateChanged(gainSetting, mute, gainMode)); + } + int getGainSetting(int id) { if (!isValidId(id)) return 0; return mVolumeInputs[id].mGainSetting; } + boolean setGainSetting(int id, int gainSetting) { + if (!isValidId(id)) return false; + + Descriptor desc = mVolumeInputs[id]; + + if (gainSetting > desc.mGainSettingsMax || gainSetting < desc.mGainSettingsMin) { + throw new IllegalArgumentException("Illegal gainSetting argument: " + gainSetting); + } + + if (desc.mGainMode == bluetooth.constants.aics.GainMode.AUTOMATIC + || desc.mGainMode == bluetooth.constants.aics.GainMode.AUTOMATIC_ONLY) { + throw new IllegalStateException("Disallowed due to gain mode being " + desc.mGainMode); + } + + return mNativeInterface.setExtAudioInGainSetting(mDevice, id, gainSetting); + } + + void onSetGainSettingFailed(int id) { + if (!isValidId(id)) return; + mVolumeInputs[id].broadcast("onSetGainSettingFailed", (c) -> c.onSetGainSettingFailed()); + } + + @Mute int getMute(int id) { - if (!isValidId(id)) return Mute.DISABLED; + if (!isValidId(id)) return bluetooth.constants.aics.Mute.DISABLED; return mVolumeInputs[id].mMute; } - void setPropSettings(int id, int gainUnit, int gainMin, int gainMax) { - if (!isValidId(id)) return; + boolean setMute(int id, @Mute int mute) { + if (!isValidId(id)) return false; - mVolumeInputs[id].mGainSettingsUnits = gainUnit; - mVolumeInputs[id].mGainSettingsMinSetting = gainMin; - mVolumeInputs[id].mGainSettingsMaxSetting = gainMax; + if (mVolumeInputs[id].mMute == bluetooth.constants.aics.Mute.DISABLED) { + throw new IllegalStateException("Disallowed due to mute being disabled"); + } + + return mNativeInterface.setExtAudioInMute(mDevice, id, mute); } - void setState(int id, int gainSetting, int mute, int gainMode) { + void onSetMuteFailed(int id) { if (!isValidId(id)) return; + mVolumeInputs[id].broadcast("onSetMuteFailed", (c) -> c.onSetMuteFailed()); + } + + @GainMode + int getGainMode(int id) { + if (!isValidId(id)) return bluetooth.constants.aics.GainMode.AUTOMATIC_ONLY; + return mVolumeInputs[id].mGainMode; + } + + boolean setGainMode(int id, @GainMode int gainMode) { + if (!isValidId(id)) return false; Descriptor desc = mVolumeInputs[id]; - if (gainSetting > desc.mGainSettingsMaxSetting - || gainSetting < desc.mGainSettingsMinSetting) { - Log.e(TAG, "Request fail. Illegal gainSetting argument: " + gainSetting); - return; + if (desc.mGainMode == bluetooth.constants.aics.GainMode.MANUAL_ONLY + || desc.mGainMode == bluetooth.constants.aics.GainMode.AUTOMATIC_ONLY) { + throw new IllegalStateException("Disallowed due to gain mode being " + desc.mGainMode); } - desc.mGainSetting = gainSetting; - desc.mGainMode = gainMode; - desc.mMute = mute; + return mNativeInterface.setExtAudioInGainMode(mDevice, id, gainMode); + } + + void onSetGainModeFailed(int id) { + if (!isValidId(id)) return; + mVolumeInputs[id].broadcast("onSetGainModeFailed", (c) -> c.onSetGainModeFailed()); } void dump(StringBuilder sb) { @@ -150,8 +292,8 @@ class VolumeControlInputDescriptor { ProfileService.println(sb, " gainMode: " + desc.mGainMode); ProfileService.println(sb, " mute: " + desc.mMute); ProfileService.println(sb, " units:" + desc.mGainSettingsUnits); - ProfileService.println(sb, " minGain:" + desc.mGainSettingsMinSetting); - ProfileService.println(sb, " maxGain:" + desc.mGainSettingsMaxSetting); + ProfileService.println(sb, " minGain:" + desc.mGainSettingsMin); + ProfileService.println(sb, " maxGain:" + desc.mGainSettingsMax); } } } diff --git a/android/app/src/com/android/bluetooth/vc/VolumeControlNativeCallback.java b/android/app/src/com/android/bluetooth/vc/VolumeControlNativeCallback.java index 56f4cde699..be86010bc2 100644 --- a/android/app/src/com/android/bluetooth/vc/VolumeControlNativeCallback.java +++ b/android/app/src/com/android/bluetooth/vc/VolumeControlNativeCallback.java @@ -25,6 +25,10 @@ import static com.android.bluetooth.vc.VolumeControlStackEvent.EVENT_TYPE_VOLUME import static java.util.Objects.requireNonNull; +import android.bluetooth.AudioInputControl.AudioInputStatus; +import android.bluetooth.AudioInputControl.AudioInputType; +import android.bluetooth.AudioInputControl.GainMode; +import android.bluetooth.AudioInputControl.Mute; import android.bluetooth.BluetoothDevice; import android.util.Log; @@ -151,7 +155,8 @@ class VolumeControlNativeCallback { } @VisibleForTesting - void onExtAudioInStateChanged(int id, int gainSetting, int gainMode, int mute, byte[] address) { + void onExtAudioInStateChanged( + int id, int gainSetting, @Mute int mute, @GainMode int gainMode, byte[] address) { sendMessageToService( s -> s.onExtAudioInStateChanged( @@ -159,23 +164,45 @@ class VolumeControlNativeCallback { } @VisibleForTesting - void onExtAudioInStatusChanged(int id, int status, byte[] address) { + void onExtAudioInSetGainSettingFailed(int id, byte[] address) { + sendMessageToService(s -> s.onExtAudioInSetGainSettingFailed(getDevice(address), id)); + } + + @VisibleForTesting + void onExtAudioInSetMuteFailed(int id, byte[] address) { + sendMessageToService(s -> s.onExtAudioInSetMuteFailed(getDevice(address), id)); + } + + @VisibleForTesting + void onExtAudioInSetGainModeFailed(int id, byte[] address) { + sendMessageToService(s -> s.onExtAudioInSetGainModeFailed(getDevice(address), id)); + } + + @VisibleForTesting + void onExtAudioInStatusChanged(int id, @AudioInputStatus int status, byte[] address) { sendMessageToService(s -> s.onExtAudioInStatusChanged(getDevice(address), id, status)); } @VisibleForTesting - void onExtAudioInTypeChanged(int id, int type, byte[] address) { + void onExtAudioInTypeChanged(int id, @AudioInputType int type, byte[] address) { sendMessageToService(s -> s.onExtAudioInTypeChanged(getDevice(address), id, type)); } @VisibleForTesting - void onExtAudioInDescriptionChanged(int id, String descr, byte[] address) { - sendMessageToService(s -> s.onExtAudioInDescriptionChanged(getDevice(address), id, descr)); + void onExtAudioInDescriptionChanged( + int id, String description, boolean isWritable, byte[] address) { + sendMessageToService( + s -> + s.onExtAudioInDescriptionChanged( + getDevice(address), id, description, isWritable)); } @VisibleForTesting - void onExtAudioInGainPropsChanged(int id, int unit, int min, int max, byte[] address) { + void onExtAudioInGainSettingPropertiesChanged( + int id, int unit, int min, int max, byte[] address) { sendMessageToService( - s -> s.onExtAudioInGainPropsChanged(getDevice(address), id, unit, min, max)); + s -> + s.onExtAudioInGainSettingPropertiesChanged( + getDevice(address), id, unit, min, max)); } } diff --git a/android/app/src/com/android/bluetooth/vc/VolumeControlNativeInterface.java b/android/app/src/com/android/bluetooth/vc/VolumeControlNativeInterface.java index 95db676ae0..90add03ed7 100644 --- a/android/app/src/com/android/bluetooth/vc/VolumeControlNativeInterface.java +++ b/android/app/src/com/android/bluetooth/vc/VolumeControlNativeInterface.java @@ -138,12 +138,12 @@ public class VolumeControlNativeInterface { return setExtAudioInGainSettingNative(getByteAddress(device), externalInputId, gainSetting); } - boolean setExtAudioInGainMode(BluetoothDevice device, int externalInputId, boolean autoMode) { - return setExtAudioInGainModeNative(getByteAddress(device), externalInputId, autoMode); + boolean setExtAudioInGainMode(BluetoothDevice device, int externalInputId, int gainMode) { + return setExtAudioInGainModeNative(getByteAddress(device), externalInputId, gainMode); } - boolean setExtAudioInGainMute(BluetoothDevice device, int externalInputId, boolean mute) { - return setExtAudioInGainMuteNative(getByteAddress(device), externalInputId, mute); + boolean setExtAudioInMute(BluetoothDevice device, int externalInputId, int mute) { + return setExtAudioInMuteNative(getByteAddress(device), externalInputId, mute); } // Native methods that call into the JNI interface @@ -182,7 +182,7 @@ public class VolumeControlNativeInterface { private native boolean setExtAudioOutDescriptionNative( byte[] address, int externalOutputId, String descr); - /* Native methods for external audio inputs */ + /* Native methods for audio inputs control service */ private native boolean getExtAudioInStateNative(byte[] address, int externalInputId); private native boolean getExtAudioInStatusNative(byte[] address, int externalInputId); @@ -200,8 +200,7 @@ public class VolumeControlNativeInterface { byte[] address, int externalInputId, int gainSetting); private native boolean setExtAudioInGainModeNative( - byte[] address, int externalInputId, boolean modeAuto); + byte[] address, int externalInputId, int gainMode); - private native boolean setExtAudioInGainMuteNative( - byte[] address, int externalInputId, boolean mute); + private native boolean setExtAudioInMuteNative(byte[] address, int externalInputId, int mute); } diff --git a/android/app/src/com/android/bluetooth/vc/VolumeControlService.java b/android/app/src/com/android/bluetooth/vc/VolumeControlService.java index 23c287bd2d..bbdb35af65 100644 --- a/android/app/src/com/android/bluetooth/vc/VolumeControlService.java +++ b/android/app/src/com/android/bluetooth/vc/VolumeControlService.java @@ -32,9 +32,15 @@ import static java.util.Objects.requireNonNull; import static java.util.Objects.requireNonNullElseGet; import android.annotation.RequiresPermission; +import android.bluetooth.AudioInputControl.AudioInputStatus; +import android.bluetooth.AudioInputControl.AudioInputType; +import android.bluetooth.AudioInputControl.GainMode; +import android.bluetooth.AudioInputControl.Mute; +import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothUuid; +import android.bluetooth.IAudioInputCallback; import android.bluetooth.IBluetoothCsipSetCoordinator; import android.bluetooth.IBluetoothLeAudio; import android.bluetooth.IBluetoothVolumeControl; @@ -64,9 +70,6 @@ import com.android.internal.annotations.VisibleForTesting; import libcore.util.SneakyThrow; -import bluetooth.constants.AudioInputType; -import bluetooth.constants.aics.AudioInputStatus; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -74,11 +77,13 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import java.util.function.Function; public class VolumeControlService extends ProfileService { private static final String TAG = VolumeControlService.class.getSimpleName(); @@ -107,7 +112,8 @@ public class VolumeControlService extends ProfileService { private final Map<BluetoothDevice, VolumeControlStateMachine> mStateMachines = new HashMap<>(); private final Map<BluetoothDevice, VolumeControlOffsetDescriptor> mAudioOffsets = new HashMap<>(); - private final Map<BluetoothDevice, VolumeControlInputDescriptor> mAudioInputs = new HashMap<>(); + private final Map<BluetoothDevice, VolumeControlInputDescriptor> mAudioInputs = + new ConcurrentHashMap<>(); private final Map<Integer, Integer> mGroupVolumeCache = new HashMap<>(); private final Map<Integer, Boolean> mGroupMuteCache = new HashMap<>(); private final Map<BluetoothDevice, Integer> mDeviceVolumeCache = new HashMap<>(); @@ -785,12 +791,13 @@ public class VolumeControlService extends ProfileService { + (", flags: " + flags)); /* We are here, because system has just started and LeAudio device is connected. If * remote device has User Persistent flag set, Android sets the volume to local cache - * and to the audio system. + * and to the audio system if not already streaming to other devices. * If Reset Flag is set, then Android sets to remote devices either cached volume volume * taken from audio manager. * Note, to match BR/EDR behavior, don't show volume change in UI here */ - if ((flags & VOLUME_FLAGS_PERSISTED_USER_SET_VOLUME_MASK) == 0x01) { + if (((flags & VOLUME_FLAGS_PERSISTED_USER_SET_VOLUME_MASK) == 0x01) + && (getConnectedDevices().size() == 1)) { updateGroupCacheAndAudioSystem(groupId, volume, mute, false); return; } @@ -948,7 +955,9 @@ public class VolumeControlService extends ProfileService { return; } - mAudioInputs.put(device, new VolumeControlInputDescriptor(numberOfExternalInputs)); + mAudioInputs.put( + device, + new VolumeControlInputDescriptor(mNativeInterface, device, numberOfExternalInputs)); } void handleDeviceAvailable( @@ -1031,7 +1040,11 @@ public class VolumeControlService extends ProfileService { } void onExtAudioInStateChanged( - BluetoothDevice device, int id, int gainSetting, int mute, int gainMode) { + BluetoothDevice device, + int id, + int gainSetting, + @Mute int mute, + @GainMode int gainMode) { String logInfo = "onExtAudioInStateChanged(" + ("device:" + device) @@ -1048,15 +1061,54 @@ public class VolumeControlService extends ProfileService { } Log.d(TAG, logInfo); - input.setState(id, gainSetting, mute, gainMode); + input.onStateChanged(id, gainSetting, mute, gainMode); + } + + void onExtAudioInSetGainSettingFailed(BluetoothDevice device, int id) { + String logInfo = "onExtAudioInSetGainSettingFailed(" + device + ", " + id + ")"; + + VolumeControlInputDescriptor input = mAudioInputs.get(device); + if (input == null) { + Log.e(TAG, logInfo + " This device has no audio input control"); + return; + } + + Log.d(TAG, logInfo); + input.onSetGainSettingFailed(id); + } + + void onExtAudioInSetMuteFailed(BluetoothDevice device, int id) { + String logInfo = "onExtAudioInSetMuteFailed(" + device + ", " + id + ")"; + + VolumeControlInputDescriptor input = mAudioInputs.get(device); + if (input == null) { + Log.e(TAG, logInfo + " This device has no audio input control"); + return; + } + + Log.d(TAG, logInfo); + input.onSetMuteFailed(id); + } + + void onExtAudioInSetGainModeFailed(BluetoothDevice device, int id) { + String logInfo = "onExtAudioInSetGainModeFailed(" + device + ", " + id + ")"; + + VolumeControlInputDescriptor input = mAudioInputs.get(device); + if (input == null) { + Log.e(TAG, logInfo + " This device has no audio input control"); + return; + } + + Log.d(TAG, logInfo); + input.onSetGainModeFailed(id); } - void onExtAudioInStatusChanged(BluetoothDevice device, int id, int status) { + void onExtAudioInStatusChanged(BluetoothDevice device, int id, @AudioInputStatus int status) { String logInfo = "onExtAudioInStatusChanged(" - + ("device:" + device) - + (", id" + id) - + (", status" + status) + + ("device=" + device) + + (", id=" + id) + + (", status=" + status) + ")"; VolumeControlInputDescriptor input = mAudioInputs.get(device); @@ -1065,21 +1117,22 @@ public class VolumeControlService extends ProfileService { return; } - if (status != AudioInputStatus.INACTIVE && status != AudioInputStatus.ACTIVE) { + if (status != bluetooth.constants.aics.AudioInputStatus.INACTIVE + && status != bluetooth.constants.aics.AudioInputStatus.ACTIVE) { Log.e(TAG, logInfo + ": Invalid status argument"); return; } Log.d(TAG, logInfo); - input.setStatus(id, status); + input.onStatusChanged(id, status); } - void onExtAudioInTypeChanged(BluetoothDevice device, int id, int type) { + void onExtAudioInTypeChanged(BluetoothDevice device, int id, @AudioInputType int type) { String logInfo = "onExtAudioInTypeChanged(" - + ("device:" + device) - + (", id" + id) - + (", type" + type) + + ("device=" + device) + + (", id=" + id) + + (", type=" + type) + ")"; VolumeControlInputDescriptor input = mAudioInputs.get(device); @@ -1088,21 +1141,18 @@ public class VolumeControlService extends ProfileService { return; } - if (type > AudioInputType.AMBIENT) { - Log.e(TAG, logInfo + ": Invalid type argument"); - return; - } - Log.d(TAG, logInfo); input.setType(id, type); } - void onExtAudioInDescriptionChanged(BluetoothDevice device, int id, String description) { + void onExtAudioInDescriptionChanged( + BluetoothDevice device, int id, String description, boolean isWritable) { String logInfo = "onExtAudioInDescriptionChanged(" - + ("device:" + device) - + (", id" + id) - + (", description" + description) + + ("device=" + device) + + (", id=" + id) + + (", description=" + description) + + (", isWritable=" + isWritable) + ")"; VolumeControlInputDescriptor input = mAudioInputs.get(device); @@ -1117,15 +1167,18 @@ public class VolumeControlService extends ProfileService { } Log.d(TAG, logInfo); - input.setDescription(id, description); + input.onDescriptionChanged(id, description, isWritable); } - void onExtAudioInGainPropsChanged(BluetoothDevice device, int id, int unit, int min, int max) { + void onExtAudioInGainSettingPropertiesChanged( + BluetoothDevice device, int id, int unit, int min, int max) { String logInfo = - "onExtAudioInGainPropsChanged(" - + ("device:" + device) - + (", id" + id) - + (" unit: " + unit + " min" + min + " max:" + max) + "onExtAudioInGainSettingPropertiesChanged(" + + ("device=" + device) + + (", id=" + id) + + (", unit=" + unit) + + (", min=" + min) + + (", max=" + max) + ")"; VolumeControlInputDescriptor input = mAudioInputs.get(device); @@ -1135,15 +1188,15 @@ public class VolumeControlService extends ProfileService { } Log.d(TAG, logInfo); - input.setPropSettings(id, unit, min, max); + input.onGainSettingsPropertiesChanged(id, unit, min, max); } - void messageFromNative(VolumeControlStackEvent stackEvent) { + void handleStackEvent(VolumeControlStackEvent stackEvent) { if (!isAvailable()) { Log.e(TAG, "Event ignored, service not available: " + stackEvent); return; } - Log.d(TAG, "messageFromNative: " + stackEvent); + Log.d(TAG, "handleStackEvent: " + stackEvent); if (stackEvent.type == VolumeControlStackEvent.EVENT_TYPE_VOLUME_STATE_CHANGED) { handleVolumeControlChanged( @@ -1182,20 +1235,36 @@ public class VolumeControlService extends ProfileService { return; } + Log.e(TAG, "Unhandled event: " + stackEvent); + } + + void messageFromNative(VolumeControlStackEvent stackEvent) { + Log.d(TAG, "messageFromNative: " + stackEvent); + + // Group events should be handled here directly + boolean isGroupEvent = (stackEvent.device == null); + if (isGroupEvent) { + handleStackEvent(stackEvent); + return; + } + + // Other device events should be serialized via their state machines so they are processed + // in the same order they were sent from the native code. synchronized (mStateMachines) { - VolumeControlStateMachine sm = mStateMachines.get(device); + VolumeControlStateMachine sm = mStateMachines.get(stackEvent.device); if (sm == null) { if (stackEvent.type == VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED) { switch (stackEvent.valueInt1) { case STATE_CONNECTED, STATE_CONNECTING -> { - sm = getOrCreateStateMachine(device); + sm = getOrCreateStateMachine(stackEvent.device); } } } } if (sm == null) { - Log.e(TAG, "Cannot process stack event: no state machine: " + stackEvent); + Log.w(TAG, "Cannot forward stack event: no state machine: " + stackEvent); + handleStackEvent(stackEvent); return; } sm.sendMessage(VolumeControlStateMachine.MESSAGE_STACK_EVENT, stackEvent); @@ -1652,7 +1721,7 @@ public class VolumeControlService extends ProfileService { } @Override - public void notifyNewRegisteredCallback( + public void unregisterCallback( IBluetoothVolumeControlCallback callback, AttributionSource source) { requireNonNull(callback); @@ -1662,11 +1731,11 @@ public class VolumeControlService extends ProfileService { } service.enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, null); - postAndWait(service.mHandler, () -> service.notifyNewRegisteredCallback(callback)); + postAndWait(service.mHandler, () -> service.unregisterCallback(callback)); } @Override - public void unregisterCallback( + public void notifyNewRegisteredCallback( IBluetoothVolumeControlCallback callback, AttributionSource source) { requireNonNull(callback); @@ -1676,7 +1745,214 @@ public class VolumeControlService extends ProfileService { } service.enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, null); - postAndWait(service.mHandler, () -> service.unregisterCallback(callback)); + postAndWait(service.mHandler, () -> service.notifyNewRegisteredCallback(callback)); + } + + private void validateBluetoothDevice(BluetoothDevice device) { + requireNonNull(device); + String address = device.getAddress(); + if (!BluetoothAdapter.checkBluetoothAddress(address)) { + throw new IllegalArgumentException("Invalid device address: " + address); + } + } + + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + private <R> R aicsWrapper( + AttributionSource source, + BluetoothDevice device, + Function<VolumeControlInputDescriptor, R> fn, + R defaultValue) { + validateBluetoothDevice(device); + + VolumeControlService service = getService(source); + if (service == null) { + return defaultValue; + } + + service.enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, null); + + VolumeControlInputDescriptor inputs = service.mAudioInputs.get(device); + if (inputs == null) { + Log.w(TAG, "No audio inputs for " + device); + return defaultValue; + } + + return fn.apply(inputs); + } + + @Override + public int getNumberOfAudioInputControlServices( + AttributionSource source, BluetoothDevice device) { + validateBluetoothDevice(device); + Log.d(TAG, "getNumberOfAudioInputControlServices(" + device + ")"); + return aicsWrapper(source, device, i -> i.size(), 0); + } + + @Override + public void registerAudioInputControlCallback( + AttributionSource source, + BluetoothDevice device, + int instanceId, + IAudioInputCallback callback) { + requireNonNull(callback); + Log.d( + TAG, + "registerAudioInputControlCallback(" + + (device + ", " + instanceId + ", " + callback) + + ")"); + aicsWrapper( + source, + device, + i -> { + i.registerCallback(instanceId, callback); + return null; + }, + null); + } + + @Override + public void unregisterAudioInputControlCallback( + AttributionSource source, + BluetoothDevice device, + int instanceId, + IAudioInputCallback callback) { + requireNonNull(callback); + Log.d( + TAG, + "unregisterAudioInputControlCallback(" + + (device + ", " + instanceId + ", " + callback) + + ")"); + aicsWrapper( + source, + device, + i -> { + i.unregisterCallback(instanceId, callback); + return null; + }, + null); + } + + @Override + public int getAudioInputGainSettingUnit( + AttributionSource source, BluetoothDevice device, int instanceId) { + Log.d(TAG, "getAudioInputGainSettingUnit(" + device + ", " + instanceId + ")"); + return aicsWrapper(source, device, i -> i.getGainSettingUnit(instanceId), 0); + } + + @Override + public int getAudioInputGainSettingMin( + AttributionSource source, BluetoothDevice device, int instanceId) { + Log.d(TAG, "getAudioInputGainSettingMin(" + device + ", " + instanceId + ")"); + return aicsWrapper(source, device, i -> i.getGainSettingMin(instanceId), 0); + } + + @Override + public int getAudioInputGainSettingMax( + AttributionSource source, BluetoothDevice device, int instanceId) { + Log.d(TAG, "getAudioInputGainSettingMax(" + device + ", " + instanceId + ")"); + return aicsWrapper(source, device, i -> i.getGainSettingMax(instanceId), 0); + } + + @Override + public String getAudioInputDescription( + AttributionSource source, BluetoothDevice device, int instanceId) { + Log.d(TAG, "getAudioInputDescription(" + device + ", " + instanceId + ")"); + return aicsWrapper(source, device, i -> i.getDescription(instanceId), ""); + } + + @Override + public boolean isAudioInputDescriptionWritable( + AttributionSource source, BluetoothDevice device, int instanceId) { + Log.d(TAG, "isAudioInputDescriptionWritable(" + device + ", " + instanceId + ")"); + return aicsWrapper(source, device, i -> i.isDescriptionWritable(instanceId), false); + } + + @Override + public boolean setAudioInputDescription( + AttributionSource source, + BluetoothDevice device, + int instanceId, + String description) { + requireNonNull(description); + Log.d(TAG, "setAudioInputDescription(" + device + ", " + instanceId + ")"); + return aicsWrapper( + source, device, i -> i.setDescription(instanceId, description), false); + } + + @Override + public @AudioInputStatus int getAudioInputStatus( + AttributionSource source, BluetoothDevice device, int instanceId) { + Log.d(TAG, "getAudioInputStatus(" + device + ", " + instanceId + ")"); + return aicsWrapper( + source, + device, + i -> i.getStatus(instanceId), + (int) bluetooth.constants.aics.AudioInputStatus.INACTIVE); + } + + @Override + public @AudioInputType int getAudioInputType( + AttributionSource source, BluetoothDevice device, int instanceId) { + Log.d(TAG, "getAudioInputType(" + device + ", " + instanceId + ")"); + return aicsWrapper( + source, + device, + i -> i.getType(instanceId), + bluetooth.constants.AudioInputType.UNSPECIFIED); + } + + @Override + public int getAudioInputGainSetting( + AttributionSource source, BluetoothDevice device, int instanceId) { + Log.d(TAG, "getAudioInputGainSetting(" + device + ", " + instanceId + ")"); + return aicsWrapper(source, device, i -> i.getGainSetting(instanceId), 0); + } + + @Override + public boolean setAudioInputGainSetting( + AttributionSource source, BluetoothDevice device, int instanceId, int gainSetting) { + Log.d(TAG, "setAudioInputGainSetting(" + device + ", " + instanceId + ")"); + return aicsWrapper( + source, device, i -> i.setGainSetting(instanceId, gainSetting), false); + } + + @Override + public @GainMode int getAudioInputGainMode( + AttributionSource source, BluetoothDevice device, int instanceId) { + Log.d(TAG, "getAudioInputGainMode(" + device + ", " + instanceId + ")"); + return aicsWrapper( + source, + device, + i -> i.getGainMode(instanceId), + (int) bluetooth.constants.aics.GainMode.AUTOMATIC_ONLY); + } + + @Override + public boolean setAudioInputGainMode( + AttributionSource source, + BluetoothDevice device, + int instanceId, + @GainMode int gainMode) { + Log.d(TAG, "setAudioInputGainMode(" + device + ", " + instanceId + ")"); + return aicsWrapper(source, device, i -> i.setGainMode(instanceId, gainMode), false); + } + + @Override + public @Mute int getAudioInputMute( + AttributionSource source, BluetoothDevice device, int instanceId) { + Log.d(TAG, "getAudioInputMute(" + device + ", " + instanceId + ")"); + return aicsWrapper( + source, + device, + i -> i.getMute(instanceId), + (int) bluetooth.constants.aics.Mute.DISABLED); + } + + @Override + public boolean setAudioInputMute( + AttributionSource source, BluetoothDevice device, int instanceId, @Mute int mute) { + Log.d(TAG, "setAudioInputMute(" + device + ", " + instanceId + ")"); + return aicsWrapper(source, device, i -> i.setMute(instanceId, mute), false); } } diff --git a/android/app/src/com/android/bluetooth/vc/VolumeControlStackEvent.java b/android/app/src/com/android/bluetooth/vc/VolumeControlStackEvent.java index b1f2840631..e662921d5f 100644 --- a/android/app/src/com/android/bluetooth/vc/VolumeControlStackEvent.java +++ b/android/app/src/com/android/bluetooth/vc/VolumeControlStackEvent.java @@ -102,8 +102,6 @@ public class VolumeControlStackEvent { private static String eventTypeValue2ToString(int type, int value) { switch (type) { - case EVENT_TYPE_CONNECTION_STATE_CHANGED: - return BluetoothProfile.getConnectionStateName(value); case EVENT_TYPE_VOLUME_STATE_CHANGED: return "{volume:" + value + "}"; case EVENT_TYPE_DEVICE_AVAILABLE: diff --git a/android/app/src/com/android/bluetooth/vc/VolumeControlStateMachine.java b/android/app/src/com/android/bluetooth/vc/VolumeControlStateMachine.java index 1e1ca9aa16..71f520cbd9 100644 --- a/android/app/src/com/android/bluetooth/vc/VolumeControlStateMachine.java +++ b/android/app/src/com/android/bluetooth/vc/VolumeControlStateMachine.java @@ -157,7 +157,10 @@ class VolumeControlStateMachine extends StateMachine { case VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED -> { processConnectionEvent(event.valueInt1); } - default -> Log.e(TAG, "Disconnected: ignoring stack event: " + event); + default -> { + Log.e(TAG, "Disconnected: forwarding stack event: " + event); + mService.handleStackEvent(event); + } } } default -> { @@ -262,7 +265,14 @@ class VolumeControlStateMachine extends StateMachine { case VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED -> { processConnectionEvent(event.valueInt1); } - default -> Log.e(TAG, "Connecting: ignoring stack event: " + event); + case VolumeControlStackEvent.EVENT_TYPE_VOLUME_STATE_CHANGED -> { + Log.w(TAG, "Defer volume change received while connecting: " + mDevice); + deferMessage(message); + } + default -> { + Log.e(TAG, "Connecting: forwarding stack event: " + event); + mService.handleStackEvent(event); + } } } default -> { @@ -355,7 +365,10 @@ class VolumeControlStateMachine extends StateMachine { case VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED -> { processConnectionEvent(event.valueInt1); } - default -> Log.e(TAG, "Disconnecting: ignoring stack event: " + event); + default -> { + Log.e(TAG, "Disconnecting: forwarding stack event: " + event); + mService.handleStackEvent(event); + } } } default -> { @@ -452,7 +465,8 @@ class VolumeControlStateMachine extends StateMachine { processConnectionEvent(event.valueInt1); } default -> { - Log.e(TAG, "Connected: ignoring stack event: " + event); + Log.e(TAG, "Connected: forwarding stack event: " + event); + mService.handleStackEvent(event); } } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientStateMachineTest.java index 696526bb26..685bd05839 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientStateMachineTest.java @@ -2701,6 +2701,60 @@ public class BassClientStateMachineTest { assertThat(mBassClientStateMachine.mPendingSourceId).isEqualTo(sourceId); } + @Test + public void updateBroadcastSource_pendingSourceToRemove() { + prepareInitialReceiveStateForGatt(); + + generateBroadcastReceiveStatesAndVerify( + mSourceTestDevice, + TEST_SOURCE_ID, + BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_SYNCHRONIZED, + BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING, + 0x1L); + + BassClientStateMachine.BluetoothGattTestableWrapper btGatt = + Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); + mBassClientStateMachine.mBluetoothGatt = btGatt; + BluetoothGattCharacteristic scanControlPoint = + Mockito.mock(BluetoothGattCharacteristic.class); + mBassClientStateMachine.mBroadcastScanControlPoint = scanControlPoint; + + BluetoothLeBroadcastMetadata metadata = createBroadcastMetadata(); + mBassClientStateMachine.mPendingMetadata = metadata; + + sendMessageAndVerifyTransition( + mBassClientStateMachine.obtainMessage( + UPDATE_BCAST_SOURCE, + TEST_SOURCE_ID, + BassConstants.PA_SYNC_DO_NOT_SYNC, + metadata), + BassClientStateMachine.ConnectedProcessing.class); + assertThat(mBassClientStateMachine.mPendingOperation).isEqualTo(UPDATE_BCAST_SOURCE); + assertThat(mBassClientStateMachine.mPendingSourceId).isEqualTo(TEST_SOURCE_ID); + + mBassClientStateMachine.mPendingOperation = 0; + mBassClientStateMachine.mPendingSourceId = 0; + // Verify not removing source when PA is still synced + generateBroadcastReceiveStatesAndVerify( + mSourceTestDevice, + TEST_SOURCE_ID, + BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_SYNCHRONIZED, + BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + 0x0L); + assertThat(mBassClientStateMachine.mPendingOperation).isEqualTo(0); + assertThat(mBassClientStateMachine.mPendingSourceId).isEqualTo(0); + + // Verify removing source when PA is unsynced + generateBroadcastReceiveStatesAndVerify( + mSourceTestDevice, + TEST_SOURCE_ID, + BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE, + BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_NOT_ENCRYPTED, + 0x0L); + assertThat(mBassClientStateMachine.mPendingOperation).isEqualTo(REMOVE_BCAST_SOURCE); + assertThat(mBassClientStateMachine.mPendingSourceId).isEqualTo(TEST_SOURCE_ID); + } + private void initToConnectingState() { allowConnection(true); allowConnectGatt(true); diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/ActiveDeviceManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/ActiveDeviceManagerTest.java index 9acb612ff0..6bd8682727 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/ActiveDeviceManagerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/ActiveDeviceManagerTest.java @@ -645,6 +645,20 @@ public class ActiveDeviceManagerTest { } @Test + public void a2dpDeactivated_makeSureToNotRemoveLeAudioDevice() { + a2dpActiveDeviceChanged(null); + mTestLooper.dispatchAll(); + verify(mLeAudioService, never()).removeActiveDevice(anyBoolean()); + } + + @Test + public void hfpDeactivated_makeSureToNotRemoveLeAudioDevice() { + headsetActiveDeviceChanged(null); + mTestLooper.dispatchAll(); + verify(mLeAudioService, never()).removeActiveDevice(anyBoolean()); + } + + @Test public void a2dpActivated_whileActivatingA2dpHeadset() { a2dpConnected(mA2dpDevice, false); a2dpConnected(mA2dpHeadsetDevice, true); @@ -1477,9 +1491,8 @@ public class ActiveDeviceManagerTest { headsetActiveDeviceChanged(mDualModeAudioDevice); mTestLooper.dispatchAll(); - // When A2DP device is getting active, first LeAudio device is removed from active devices - // and later added - verify(mLeAudioService).removeActiveDevice(anyBoolean()); + // When Hfp device is getting active and it is dual mode device LeAudioDevice will be added. + verify(mLeAudioService, never()).removeActiveDevice(anyBoolean()); verify(mLeAudioService).setActiveDevice(mDualModeAudioDevice); Assert.assertEquals(mDualModeAudioDevice, mActiveDeviceManager.getA2dpActiveDevice()); diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/MetricsLoggerTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/MetricsLoggerTest.java index 3f0331f2b8..018fccff17 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/MetricsLoggerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/MetricsLoggerTest.java @@ -270,6 +270,28 @@ public class MetricsLoggerTest { } @Test + public void testGetAllowlistedDeviceNameHashForMedicalDevice() { + String deviceName = "Sam's rphonak hearing aid"; + String expectMedicalDeviceSha256 = MetricsLogger.getSha256String("rphonakhearingaid"); + + String actualMedicalDeviceSha256 = + mTestableMetricsLogger.getAllowlistedDeviceNameHash(deviceName, true); + + Assert.assertEquals(expectMedicalDeviceSha256, actualMedicalDeviceSha256); + } + + @Test + public void testGetAllowlistedDeviceNameHashForMedicalDeviceIdentifiedLogging() { + String deviceName = "Sam's rphonak hearing aid"; + String expectMedicalDeviceSha256 = ""; + + String actualMedicalDeviceSha256 = + mTestableMetricsLogger.getAllowlistedDeviceNameHash(deviceName, false); + + Assert.assertEquals(expectMedicalDeviceSha256, actualMedicalDeviceSha256); + } + + @Test public void uploadEmptyDeviceName() { initTestingBloomfilter(); Assert.assertEquals("", mTestableMetricsLogger.logAllowlistedDeviceNameHash(1, "", true)); 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 be78d86463..5f1b8e0f97 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 @@ -1550,6 +1550,30 @@ public final class DatabaseManagerTest { } } + @Test + public void testDatabaseMigration_120_121() throws IOException { + // Create a database with version 120 + SupportSQLiteDatabase db = testHelper.createDatabase(DB_NAME, 120); + // 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 120 to 121 + db.close(); + db = + testHelper.runMigrationsAndValidate( + DB_NAME, 121, true, MetadataDatabase.MIGRATION_120_121); + Cursor cursor = db.query("SELECT * FROM metadata"); + assertHasColumn(cursor, "is_preferred_microphone_for_calls", true); + while (cursor.moveToNext()) { + // Check the new columns was added with default value + assertColumnIntData(cursor, "is_preferred_microphone_for_calls", 1); + } + } + /** Helper function to check whether the database has the expected column */ void assertHasColumn(Cursor cursor, String columnName, boolean hasColumn) { if (hasColumn) { diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/schemas/com.android.bluetooth.btservice.storage.MetadataDatabase/121.json b/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/schemas/com.android.bluetooth.btservice.storage.MetadataDatabase/121.json new file mode 100644 index 0000000000..9543c80acc --- /dev/null +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/schemas/com.android.bluetooth.btservice.storage.MetadataDatabase/121.json @@ -0,0 +1,351 @@ +{ + "formatVersion": 1, + "database": { + "version": 121, + "identityHash": "f336d3b688901f1507adeb711e50f781", + "entities": [ + { + "tableName": "metadata", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`address` TEXT NOT NULL, `migrated` INTEGER NOT NULL, `a2dpSupportsOptionalCodecs` INTEGER NOT NULL, `a2dpOptionalCodecsEnabled` INTEGER NOT NULL, `last_active_time` INTEGER NOT NULL, `is_active_a2dp_device` INTEGER NOT NULL, `isActiveHfpDevice` INTEGER NOT NULL, `preferred_output_only_profile` INTEGER NOT NULL, `preferred_duplex_profile` INTEGER NOT NULL, `active_audio_device_policy` INTEGER NOT NULL, `is_preferred_microphone_for_calls` INTEGER NOT NULL, `a2dp_connection_policy` INTEGER, `a2dp_sink_connection_policy` INTEGER, `hfp_connection_policy` INTEGER, `hfp_client_connection_policy` INTEGER, `hid_host_connection_policy` INTEGER, `pan_connection_policy` INTEGER, `pbap_connection_policy` INTEGER, `pbap_client_connection_policy` INTEGER, `map_connection_policy` INTEGER, `sap_connection_policy` INTEGER, `hearing_aid_connection_policy` INTEGER, `hap_client_connection_policy` INTEGER, `map_client_connection_policy` INTEGER, `le_audio_connection_policy` INTEGER, `volume_control_connection_policy` INTEGER, `csip_set_coordinator_connection_policy` INTEGER, `le_call_control_connection_policy` INTEGER, `bass_client_connection_policy` INTEGER, `battery_connection_policy` INTEGER, `manufacturer_name` BLOB, `model_name` BLOB, `software_version` BLOB, `hardware_version` BLOB, `companion_app` BLOB, `main_icon` BLOB, `is_untethered_headset` BLOB, `untethered_left_icon` BLOB, `untethered_right_icon` BLOB, `untethered_case_icon` BLOB, `untethered_left_battery` BLOB, `untethered_right_battery` BLOB, `untethered_case_battery` BLOB, `untethered_left_charging` BLOB, `untethered_right_charging` BLOB, `untethered_case_charging` BLOB, `enhanced_settings_ui_uri` BLOB, `device_type` BLOB, `main_battery` BLOB, `main_charging` BLOB, `main_low_battery_threshold` BLOB, `untethered_left_low_battery_threshold` BLOB, `untethered_right_low_battery_threshold` BLOB, `untethered_case_low_battery_threshold` BLOB, `spatial_audio` BLOB, `fastpair_customized` BLOB, `le_audio` BLOB, `gmcs_cccd` BLOB, `gtbs_cccd` BLOB, `exclusive_manager` BLOB, `call_establish_audio_policy` INTEGER, `connecting_time_audio_policy` INTEGER, `in_band_ringtone_audio_policy` INTEGER, PRIMARY KEY(`address`))", + "fields": [ + { + "fieldPath": "address", + "columnName": "address", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "migrated", + "columnName": "migrated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "a2dpSupportsOptionalCodecs", + "columnName": "a2dpSupportsOptionalCodecs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "a2dpOptionalCodecsEnabled", + "columnName": "a2dpOptionalCodecsEnabled", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "last_active_time", + "columnName": "last_active_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "is_active_a2dp_device", + "columnName": "is_active_a2dp_device", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isActiveHfpDevice", + "columnName": "isActiveHfpDevice", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "preferred_output_only_profile", + "columnName": "preferred_output_only_profile", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "preferred_duplex_profile", + "columnName": "preferred_duplex_profile", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "active_audio_device_policy", + "columnName": "active_audio_device_policy", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "is_preferred_microphone_for_calls", + "columnName": "is_preferred_microphone_for_calls", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "profileConnectionPolicies.a2dp_connection_policy", + "columnName": "a2dp_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.a2dp_sink_connection_policy", + "columnName": "a2dp_sink_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.hfp_connection_policy", + "columnName": "hfp_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.hfp_client_connection_policy", + "columnName": "hfp_client_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.hid_host_connection_policy", + "columnName": "hid_host_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.pan_connection_policy", + "columnName": "pan_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.pbap_connection_policy", + "columnName": "pbap_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.pbap_client_connection_policy", + "columnName": "pbap_client_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.map_connection_policy", + "columnName": "map_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.sap_connection_policy", + "columnName": "sap_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.hearing_aid_connection_policy", + "columnName": "hearing_aid_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.hap_client_connection_policy", + "columnName": "hap_client_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.map_client_connection_policy", + "columnName": "map_client_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.le_audio_connection_policy", + "columnName": "le_audio_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.volume_control_connection_policy", + "columnName": "volume_control_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.csip_set_coordinator_connection_policy", + "columnName": "csip_set_coordinator_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.le_call_control_connection_policy", + "columnName": "le_call_control_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.bass_client_connection_policy", + "columnName": "bass_client_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.battery_connection_policy", + "columnName": "battery_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "publicMetadata.manufacturer_name", + "columnName": "manufacturer_name", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.model_name", + "columnName": "model_name", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.software_version", + "columnName": "software_version", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.hardware_version", + "columnName": "hardware_version", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.companion_app", + "columnName": "companion_app", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.main_icon", + "columnName": "main_icon", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.is_untethered_headset", + "columnName": "is_untethered_headset", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_left_icon", + "columnName": "untethered_left_icon", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_right_icon", + "columnName": "untethered_right_icon", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_case_icon", + "columnName": "untethered_case_icon", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_left_battery", + "columnName": "untethered_left_battery", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_right_battery", + "columnName": "untethered_right_battery", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_case_battery", + "columnName": "untethered_case_battery", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_left_charging", + "columnName": "untethered_left_charging", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_right_charging", + "columnName": "untethered_right_charging", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_case_charging", + "columnName": "untethered_case_charging", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.enhanced_settings_ui_uri", + "columnName": "enhanced_settings_ui_uri", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.device_type", + "columnName": "device_type", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.main_battery", + "columnName": "main_battery", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.main_charging", + "columnName": "main_charging", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.main_low_battery_threshold", + "columnName": "main_low_battery_threshold", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_left_low_battery_threshold", + "columnName": "untethered_left_low_battery_threshold", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_right_low_battery_threshold", + "columnName": "untethered_right_low_battery_threshold", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_case_low_battery_threshold", + "columnName": "untethered_case_low_battery_threshold", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.spatial_audio", + "columnName": "spatial_audio", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.fastpair_customized", + "columnName": "fastpair_customized", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.le_audio", + "columnName": "le_audio", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.gmcs_cccd", + "columnName": "gmcs_cccd", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.gtbs_cccd", + "columnName": "gtbs_cccd", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.exclusive_manager", + "columnName": "exclusive_manager", + "affinity": "BLOB" + }, + { + "fieldPath": "audioPolicyMetadata.callEstablishAudioPolicy", + "columnName": "call_establish_audio_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "audioPolicyMetadata.connectingTimeAudioPolicy", + "columnName": "connecting_time_audio_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "audioPolicyMetadata.inBandRingtoneAudioPolicy", + "columnName": "in_band_ringtone_audio_policy", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "address" + ] + } + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'f336d3b688901f1507adeb711e50f781')" + ] + } +} 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 7261d369bf..1543cd6ac3 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 @@ -35,6 +35,7 @@ import android.os.IBinder; import android.os.Looper; import android.os.ParcelUuid; import android.os.RemoteException; +import android.platform.test.annotations.EnableFlags; import android.platform.test.flag.junit.SetFlagsRule; import androidx.test.filters.MediumTest; @@ -86,6 +87,7 @@ public class LeAudioBroadcastServiceTest { private LeAudioService mService; private LeAudioIntentReceiver mLeAudioIntentReceiver; private LinkedBlockingQueue<Intent> mIntentQueue; + private boolean onBroadcastToUnicastFallbackGroupChangedCallbackCalled = false; @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock private ActiveDeviceManager mActiveDeviceManager; @@ -1593,6 +1595,58 @@ public class LeAudioBroadcastServiceTest { Assert.assertEquals(mService.mUnicastGroupIdDeactivatedForBroadcastTransition, groupId2); } + @Test + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_API_MANAGE_PRIMARY_GROUP) + public void testOnBroadcastToUnicastFallbackGroupChanged() { + int groupId1 = 1; + int groupId2 = 2; + int broadcastId = 243; + byte[] code = {0x00, 0x01, 0x00, 0x02}; + + onBroadcastToUnicastFallbackGroupChangedCallbackCalled = false; + + IBluetoothLeAudioCallback leAudioCallbacks = + new IBluetoothLeAudioCallback.Stub() { + @Override + public void onCodecConfigChanged(int gid, BluetoothLeAudioCodecStatus status) {} + + @Override + public void onGroupStatusChanged(int gid, int gStatus) {} + + @Override + public void onGroupNodeAdded(BluetoothDevice device, int gid) {} + + @Override + public void onGroupNodeRemoved(BluetoothDevice device, int gid) {} + + @Override + public void onGroupStreamStatusChanged(int groupId, int groupStreamStatus) {} + + @Override + public void onBroadcastToUnicastFallbackGroupChanged(int groupId) { + onBroadcastToUnicastFallbackGroupChangedCallbackCalled = true; + Assert.assertEquals(groupId1, groupId); + } + }; + + synchronized (mService.mLeAudioCallbacks) { + mService.mLeAudioCallbacks.register(leAudioCallbacks); + } + + initializeNative(); + prepareConnectedUnicastDevice(groupId2, mDevice2); + prepareHandoverStreamingBroadcast(groupId1, broadcastId, code); + + TestUtils.waitForLooperToFinishScheduledTask(mService.getMainLooper()); + Assert.assertEquals(groupId1, mService.mUnicastGroupIdDeactivatedForBroadcastTransition); + Assert.assertTrue(onBroadcastToUnicastFallbackGroupChangedCallbackCalled); + + onBroadcastToUnicastFallbackGroupChangedCallbackCalled = false; + synchronized (mService.mLeAudioCallbacks) { + mService.mLeAudioCallbacks.unregister(leAudioCallbacks); + } + } + private class LeAudioIntentReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { 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 6b9668f9cf..162b980088 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 @@ -2229,6 +2229,9 @@ public class LeAudioServiceTest { @Override public void onGroupStreamStatusChanged(int groupId, int groupStreamStatus) {} + + @Override + public void onBroadcastToUnicastFallbackGroupChanged(int groupId) {} }; synchronized (mService.mLeAudioCallbacks) { @@ -2287,6 +2290,9 @@ public class LeAudioServiceTest { assertThat(gid == groupId).isTrue(); assertThat(gStreamStatus == groupStreamStatus).isTrue(); } + + @Override + public void onBroadcastToUnicastFallbackGroupChanged(int groupId) {} }; synchronized (mService.mLeAudioCallbacks) { @@ -2400,6 +2406,9 @@ public class LeAudioServiceTest { @Override public void onGroupStreamStatusChanged(int groupId, int groupStreamStatus) {} + + @Override + public void onBroadcastToUnicastFallbackGroupChanged(int groupId) {} }; synchronized (mService.mLeAudioCallbacks) { @@ -2484,6 +2493,9 @@ public class LeAudioServiceTest { @Override public void onGroupStreamStatusChanged(int groupId, int groupStreamStatus) {} + + @Override + public void onBroadcastToUnicastFallbackGroupChanged(int groupId) {} }; synchronized (mService.mLeAudioCallbacks) { @@ -2577,6 +2589,9 @@ public class LeAudioServiceTest { @Override public void onGroupStreamStatusChanged(int groupId, int groupStreamStatus) {} + + @Override + public void onBroadcastToUnicastFallbackGroupChanged(int groupId) {} }; synchronized (mService.mLeAudioCallbacks) { diff --git a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlInputDescriptorTest.java b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlInputDescriptorTest.java index 0811f4e2e0..9c85116a79 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlInputDescriptorTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlInputDescriptorTest.java @@ -19,34 +19,49 @@ import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.*; +import android.bluetooth.AudioInputControl.AudioInputStatus; +import android.bluetooth.AudioInputControl.AudioInputType; +import android.bluetooth.AudioInputControl.GainMode; +import android.bluetooth.AudioInputControl.Mute; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; import android.platform.test.flag.junit.SetFlagsRule; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; -import bluetooth.constants.aics.Mute; +import com.android.bluetooth.TestUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; @SmallTest @RunWith(AndroidJUnit4.class) public class VolumeControlInputDescriptorTest { + @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); + @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule(); + + @Mock private VolumeControlNativeInterface mNativeInterface; + private static final int NUMBER_OF_INPUT = 3; private static final int NUMBER_OF_FIELD_IN_STRUCT = 9; private static final int VALID_ID = 1; private static final int INVALID_ID = NUMBER_OF_INPUT; private static final int INVALID_ID2 = -1; - @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule(); + private final BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter(); + private final BluetoothDevice mDevice = TestUtils.getTestDevice(mAdapter, 0x42); private VolumeControlInputDescriptor mDescriptor; @Before public void setUp() { - mDescriptor = new VolumeControlInputDescriptor(NUMBER_OF_INPUT); + mDescriptor = new VolumeControlInputDescriptor(mNativeInterface, mDevice, NUMBER_OF_INPUT); } @Test @@ -61,99 +76,108 @@ public class VolumeControlInputDescriptorTest { @Test public void setFoo_withAllValidId_valuesAreUpdated() { for (int i = 0; i < NUMBER_OF_INPUT; i++) { - assertThat(mDescriptor.getStatus(i)).isEqualTo(0); // AudioInputStatus.INACTIVE); - mDescriptor.setStatus(i, 1); // AudioInputStatus.ACTIVE); - assertThat(mDescriptor.getStatus(i)).isEqualTo(1); // AudioInputStatus.ACTIVE); + assertThat(mDescriptor.getStatus(i)) + .isEqualTo(bluetooth.constants.aics.AudioInputStatus.INACTIVE); + mDescriptor.onStatusChanged(i, bluetooth.constants.aics.AudioInputStatus.ACTIVE); + assertThat(mDescriptor.getStatus(i)) + .isEqualTo(bluetooth.constants.aics.AudioInputStatus.ACTIVE); } } @Test public void getStatus_whenNeverSet_defaultToInactive() { - assertThat(mDescriptor.getStatus(VALID_ID)).isEqualTo(0); // AudioInputStatus.INACTIVE); + assertThat(mDescriptor.getStatus(VALID_ID)) + .isEqualTo(bluetooth.constants.aics.AudioInputStatus.INACTIVE); } @Test public void setStatus_withValidId_valueIsUpdated() { - int newStatus = 1; // AudioInputStatus.ACTIVE; - mDescriptor.setStatus(VALID_ID, newStatus); + @AudioInputStatus int status = bluetooth.constants.aics.AudioInputStatus.ACTIVE; + mDescriptor.onStatusChanged(VALID_ID, status); - assertThat(mDescriptor.getStatus(VALID_ID)).isEqualTo(newStatus); + assertThat(mDescriptor.getStatus(VALID_ID)).isEqualTo(status); } @Test public void setStatus_withInvalidId_valueIsNotUpdated() { - int newStatus = 1; // AudioInputStatus.ACTIVE; - mDescriptor.setStatus(INVALID_ID, newStatus); + @AudioInputStatus int status = bluetooth.constants.aics.AudioInputStatus.ACTIVE; + mDescriptor.onStatusChanged(INVALID_ID, status); - assertThat(mDescriptor.getStatus(INVALID_ID)).isNotEqualTo(newStatus); + assertThat(mDescriptor.getStatus(INVALID_ID)).isNotEqualTo(status); } @Test public void getType_whenNeverSet_defaultToUnspecified() { - assertThat(mDescriptor.getType(VALID_ID)).isEqualTo(0); // AudioInputType.UNSPECIFIED); + assertThat(mDescriptor.getType(VALID_ID)) + .isEqualTo(bluetooth.constants.AudioInputType.UNSPECIFIED); } @Test public void setType_withValidId_valueIsUpdated() { - int newType = 7; // AudioInputType.AMBIENT; - mDescriptor.setType(VALID_ID, newType); + @AudioInputType int type = bluetooth.constants.AudioInputType.AMBIENT; + mDescriptor.setType(VALID_ID, type); - assertThat(mDescriptor.getType(VALID_ID)).isEqualTo(newType); + assertThat(mDescriptor.getType(VALID_ID)).isEqualTo(type); } @Test public void setType_withInvalidId_valueIsNotUpdated() { - int newType = 1; // AudioInputType.BLUETOOTH; - mDescriptor.setType(INVALID_ID2, newType); + @AudioInputType int type = bluetooth.constants.AudioInputType.BLUETOOTH; + mDescriptor.setType(INVALID_ID2, type); - assertThat(mDescriptor.getType(INVALID_ID2)).isNotEqualTo(newType); + assertThat(mDescriptor.getType(INVALID_ID2)).isNotEqualTo(type); } @Test public void setState_withValidIdButIncorrectSettings_valueIsNotUpdated() { - int newGainValue = 42; - int newGainMode = 42; - int mute = Mute.NOT_MUTED; - mDescriptor.setState(VALID_ID, newGainMode, newGainMode, mute); - - assertThat(mDescriptor.getGainSetting(VALID_ID)).isNotEqualTo(newGainValue); - // assertThat(mDescriptor.getGainMode(VALID_ID)).isNotEqualTo(newGainMode); - assertThat(mDescriptor.getMute(VALID_ID)).isNotEqualTo(mute); + mDescriptor.onStateChanged( + VALID_ID, + 34, + bluetooth.constants.aics.Mute.NOT_MUTED, + bluetooth.constants.aics.GainMode.MANUAL); + + assertThat(mDescriptor.getGainSetting(VALID_ID)).isEqualTo(0); + assertThat(mDescriptor.getGainMode(VALID_ID)) + .isEqualTo(bluetooth.constants.aics.GainMode.MANUAL_ONLY); + assertThat(mDescriptor.getMute(VALID_ID)).isEqualTo(bluetooth.constants.aics.Mute.DISABLED); } @Test public void setState_withValidIdAndCorrectSettings_valueIsUpdated() { - int newMax = 100; - int newMin = 0; - int newUnit = 1; - mDescriptor.setPropSettings(VALID_ID, newUnit, newMin, newMax); - - int newGainValue = 42; - int newGainMode = 42; - int mute = Mute.MUTED; - mDescriptor.setState(VALID_ID, newGainMode, mute, newGainMode); - - assertThat(mDescriptor.getGainSetting(VALID_ID)).isEqualTo(newGainValue); - // assertThat(mDescriptor.getGainMode(VALID_ID)).isNotEqualTo(newGainMode); + int max = 100; + int min = 0; + int unit = 1; + mDescriptor.onGainSettingsPropertiesChanged(VALID_ID, unit, min, max); + + int gainSetting = 42; + @Mute int mute = bluetooth.constants.aics.Mute.MUTED; + @GainMode int gainMode = bluetooth.constants.aics.GainMode.MANUAL; + mDescriptor.onStateChanged(VALID_ID, gainSetting, mute, gainMode); + + assertThat(mDescriptor.getGainSetting(VALID_ID)).isEqualTo(gainSetting); + assertThat(mDescriptor.getGainMode(VALID_ID)).isEqualTo(gainMode); assertThat(mDescriptor.getMute(VALID_ID)).isEqualTo(mute); } @Test public void setState_withInvalidId_valueIsNotUpdated() { - int newMax = 100; - int newMin = 0; - int newUnit = 1; + int max = 100; + int min = 0; + int unit = 1; // Should be no-op but we want to copy the working case test, just with an invalid id - mDescriptor.setPropSettings(INVALID_ID, newUnit, newMin, newMax); - - int newGainValue = 42; - int newGainMode = 42; - int mute = Mute.MUTED; - mDescriptor.setState(INVALID_ID, newGainMode, newGainMode, mute); - - assertThat(mDescriptor.getGainSetting(INVALID_ID)).isNotEqualTo(newGainValue); - // assertThat(mDescriptor.getGainMode(VALID_ID)).isNotEqualTo(newGainMode); - assertThat(mDescriptor.getMute(INVALID_ID)).isEqualTo(Mute.DISABLED); + mDescriptor.onGainSettingsPropertiesChanged(INVALID_ID, unit, min, max); + + mDescriptor.onStateChanged( + INVALID_ID, + 35, + bluetooth.constants.aics.Mute.MUTED, + bluetooth.constants.aics.GainMode.MANUAL); + + assertThat(mDescriptor.getGainSetting(INVALID_ID)).isEqualTo(0); + assertThat(mDescriptor.getGainMode(INVALID_ID)) + .isEqualTo(bluetooth.constants.aics.GainMode.AUTOMATIC_ONLY); + assertThat(mDescriptor.getMute(INVALID_ID)) + .isEqualTo(bluetooth.constants.aics.Mute.DISABLED); } @Test @@ -164,7 +188,7 @@ public class VolumeControlInputDescriptorTest { @Test public void setDescription_withValidId_valueIsUpdated() { String newDescription = "what a nice description"; - mDescriptor.setDescription(VALID_ID, newDescription); + mDescriptor.onDescriptionChanged(VALID_ID, newDescription, false); assertThat(mDescriptor.getDescription(VALID_ID)).isEqualTo(newDescription); } @@ -172,7 +196,7 @@ public class VolumeControlInputDescriptorTest { @Test public void setDescription_withInvalidId_valueIsNotUpdated() { String newDescription = "what a nice description"; - mDescriptor.setDescription(INVALID_ID, newDescription); + mDescriptor.onDescriptionChanged(INVALID_ID, newDescription, true); assertThat(mDescriptor.getDescription(INVALID_ID)).isNotEqualTo(newDescription); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeCallbackTest.java b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeCallbackTest.java index 51b5f57103..20e3fcd088 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeCallbackTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeCallbackTest.java @@ -189,20 +189,24 @@ public class VolumeControlNativeCallbackTest { @Test public void onExtAudioInDescriptionChanged() { int id = 2; - String descr = "microphone"; + String description = "microphone"; + boolean isWritable = true; - mNativeCallback.onExtAudioInDescriptionChanged(id, descr, null); - verify(mService).onExtAudioInDescriptionChanged(any(), eq(id), eq(descr)); + mNativeCallback.onExtAudioInDescriptionChanged(id, description, isWritable, null); + verify(mService) + .onExtAudioInDescriptionChanged(any(), eq(id), eq(description), eq(isWritable)); } @Test - public void onExtAudioInGainPropsChanged() { + public void onExtAudioInGainSettingPropertiesChanged() { int id = 2; int unit = 1; int min = 0; int max = 100; - mNativeCallback.onExtAudioInGainPropsChanged(id, unit, min, max, null); - verify(mService).onExtAudioInGainPropsChanged(any(), eq(id), eq(unit), eq(min), eq(max)); + mNativeCallback.onExtAudioInGainSettingPropertiesChanged(id, unit, min, max, null); + verify(mService) + .onExtAudioInGainSettingPropertiesChanged( + any(), eq(id), eq(unit), eq(min), eq(max)); } } 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 c753899100..18388e1223 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 @@ -610,8 +610,8 @@ public class VolumeControlServiceTest { (int) Math.round((double) (volumeDevice * MEDIA_MAX_VOL) / BT_LE_AUDIO_MAX_VOL); verify(mAudioManager).setStreamVolume(anyInt(), eq(expectedAfVol), anyInt()); - // Connect second device and read different volume. Expect it will be set to AF and to - // another set member + // Connect second device and read different volume. Expect it will NOT be set to AF + // and to another set member, but the existing volume gets applied to it generateDeviceAvailableMessageFromNative(mDeviceTwo, 1); generateConnectionMessageFromNative(mDeviceTwo, STATE_CONNECTED, STATE_DISCONNECTED); assertThat(mService.getConnectionState(mDeviceTwo)).isEqualTo(STATE_CONNECTED); @@ -625,9 +625,12 @@ public class VolumeControlServiceTest { flags, initialMuteState, initialAutonomousFlag); - expectedAfVol = + + expectedAfVol = volumeDevice; + int unexpectedAfVol = (int) Math.round((double) (volumeDeviceTwo * MEDIA_MAX_VOL) / BT_LE_AUDIO_MAX_VOL); - verify(mAudioManager).setStreamVolume(anyInt(), eq(expectedAfVol), anyInt()); + verify(mAudioManager, times(0)).setStreamVolume(anyInt(), eq(unexpectedAfVol), anyInt()); + verify(mNativeInterface).setGroupVolume(eq(groupId), eq(expectedAfVol)); } private void testConnectedDeviceWithResetFlag( @@ -1276,6 +1279,7 @@ public class VolumeControlServiceTest { stackEvent.valueBool1 = mute; stackEvent.valueBool2 = isAutonomous; mService.messageFromNative(stackEvent); + mLooper.dispatchAll(); } private void generateDeviceOffsetChangedMessageFromNative( @@ -1288,6 +1292,7 @@ public class VolumeControlServiceTest { event.valueInt1 = extOffsetIndex; // external output index event.valueInt2 = offset; // offset value mService.messageFromNative(event); + mLooper.dispatchAll(); } private void generateDeviceLocationChangedMessageFromNative( @@ -1300,6 +1305,7 @@ public class VolumeControlServiceTest { event.valueInt1 = extOffsetIndex; // external output index event.valueInt2 = location; // location mService.messageFromNative(event); + mLooper.dispatchAll(); } private void generateDeviceDescriptionChangedMessageFromNative( @@ -1312,6 +1318,7 @@ public class VolumeControlServiceTest { event.valueInt1 = extOffsetIndex; // external output index event.valueString1 = description; // description mService.messageFromNative(event); + mLooper.dispatchAll(); } @SafeVarargs diff --git a/flags/Android.bp b/flags/Android.bp index f9b84264f1..732af4e27a 100644 --- a/flags/Android.bp +++ b/flags/Android.bp @@ -83,6 +83,7 @@ java_aconfig_library { mode: "exported", visibility: [ "//frameworks/base", + "//frameworks/base/packages/SettingsLib", ], } diff --git a/flags/a2dp.aconfig b/flags/a2dp.aconfig index ba1943b944..0b8a749af1 100644 --- a/flags/a2dp.aconfig +++ b/flags/a2dp.aconfig @@ -148,7 +148,6 @@ flag { } } - flag { name: "a2dp_source_threading_fix" namespace: "bluetooth" @@ -158,3 +157,13 @@ flag { purpose: PURPOSE_BUGFIX } } + +flag { + name: "a2dp_clear_pending_start_on_session_restart" + namespace: "bluetooth" + description: "Clear the kPendingStart flag when the audio session is restarted for codec reconfiguration" + bug: "378524655" + metadata { + purpose: PURPOSE_BUGFIX + } +} diff --git a/flags/gap.aconfig b/flags/gap.aconfig index 2b2b5cdd55..36a83faa6f 100644 --- a/flags/gap.aconfig +++ b/flags/gap.aconfig @@ -236,6 +236,19 @@ flag { namespace: "bluetooth" description: "Support MSFT HCI extension for LE Scanning. go/bt-msft-aosp-dd" bug: "365787977" + metadata { + purpose: PURPOSE_BUGFIX + } +} + +flag { + name: "le_impl_ack_pause_disarmed" + namespace: "bluetooth" + description: "Let le_impl AckPause when disarmed to prevent stuck in pausing state" + bug: "357024179" + metadata { + purpose: PURPOSE_BUGFIX + } } flag { @@ -257,3 +270,13 @@ flag { purpose: PURPOSE_BUGFIX } } + +flag { + name: "initial_conn_params_p1" + namespace: "bluetooth" + description: "Use aggressive connection parameters when <2 connections exist. go/initial-connection-parameter-optimization" + bug: "378595485" + metadata { + purpose: PURPOSE_BUGFIX + } +}
\ No newline at end of file diff --git a/flags/hid.aconfig b/flags/hid.aconfig index 7ec7f03f3c..4226723f45 100644 --- a/flags/hid.aconfig +++ b/flags/hid.aconfig @@ -132,3 +132,23 @@ flag { purpose: PURPOSE_BUGFIX } } + +flag { + name: "remove_pending_hid_connection" + namespace: "bluetooth" + description: "Remove the pending BTA HH connection instance when the device is removed" + bug: "377705101" + metadata { + purpose: PURPOSE_BUGFIX + } +} + +flag { + name: "hogp_reconnection" + namespace: "bluetooth" + description: "Allow reconnection from HOGP device irrespective of disconnection reason" + bug: "378162528" + metadata { + purpose: PURPOSE_BUGFIX + } +} diff --git a/flags/opp.aconfig b/flags/opp.aconfig index adc94796d5..6e32ab0b75 100644 --- a/flags/opp.aconfig +++ b/flags/opp.aconfig @@ -28,3 +28,12 @@ flag { } } +flag { + name: "opp_set_insets_for_edge_to_edge" + namespace: "bluetooth" + description: "Set proper insets in BluetoothOppTransferHistory to adapt to edge-to-edge." + bug: "378813445" + metadata { + purpose: PURPOSE_BUGFIX + } +} diff --git a/flags/pairing.aconfig b/flags/pairing.aconfig index 6662aee382..152f262bcb 100644 --- a/flags/pairing.aconfig +++ b/flags/pairing.aconfig @@ -199,4 +199,14 @@ flag { metadata { purpose: PURPOSE_BUGFIX } +} + +flag { + name: "prevent_service_connections_on_remove_bond" + namespace: "bluetooth" + description: "Disable service connections on remove bond" + bug: "378736590" + metadata { + purpose: PURPOSE_BUGFIX + } }
\ No newline at end of file diff --git a/framework/Android.bp b/framework/Android.bp index 7c0d3e925f..0526650ac4 100644 --- a/framework/Android.bp +++ b/framework/Android.bp @@ -20,6 +20,7 @@ java_defaults { name: "framework-bluetooth-defaults", static_libs: [ "PlatformProperties", + "bluetooth_constants_java", "bluetooth_flags_java_lib", "modules-utils-build", "modules-utils-expresslog", diff --git a/framework/api/current.txt b/framework/api/current.txt index 4347504e24..6f27962380 100644 --- a/framework/api/current.txt +++ b/framework/api/current.txt @@ -52,6 +52,7 @@ package android.bluetooth { method @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public android.bluetooth.BluetoothServerSocket listenUsingInsecureRfcommWithServiceRecord(String, java.util.UUID) throws java.io.IOException; method @NonNull @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public android.bluetooth.BluetoothServerSocket listenUsingL2capChannel() throws java.io.IOException; method @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public android.bluetooth.BluetoothServerSocket listenUsingRfcommWithServiceRecord(String, java.util.UUID) throws java.io.IOException; + method @FlaggedApi("com.android.bluetooth.flags.socket_settings_api") @NonNull @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public android.bluetooth.BluetoothServerSocket listenUsingSocketSettings(@NonNull android.bluetooth.BluetoothSocketSettings) throws java.io.IOException; method @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public boolean setName(String); method @RequiresPermission(android.Manifest.permission.BLUETOOTH_SCAN) public boolean startDiscovery(); method @Deprecated @RequiresPermission(android.Manifest.permission.BLUETOOTH_SCAN) public boolean startLeScan(android.bluetooth.BluetoothAdapter.LeScanCallback); @@ -531,6 +532,7 @@ package android.bluetooth { method public android.bluetooth.BluetoothSocket createInsecureRfcommSocketToServiceRecord(java.util.UUID) throws java.io.IOException; method @NonNull public android.bluetooth.BluetoothSocket createL2capChannel(int) throws java.io.IOException; method public android.bluetooth.BluetoothSocket createRfcommSocketToServiceRecord(java.util.UUID) throws java.io.IOException; + method @FlaggedApi("com.android.bluetooth.flags.socket_settings_api") @NonNull public android.bluetooth.BluetoothSocket createUsingSocketSettings(@NonNull android.bluetooth.BluetoothSocketSettings) throws java.io.IOException; method public int describeContents(); method @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public boolean fetchUuidsWithSdp(); method public String getAddress(); @@ -1080,6 +1082,7 @@ package android.bluetooth { method public android.bluetooth.BluetoothDevice getRemoteDevice(); method public boolean isConnected(); field public static final int TYPE_L2CAP = 3; // 0x3 + field @FlaggedApi("com.android.bluetooth.flags.socket_settings_api") public static final int TYPE_LE = 4; // 0x4 field public static final int TYPE_RFCOMM = 1; // 0x1 field public static final int TYPE_SCO = 2; // 0x2 } @@ -1112,6 +1115,26 @@ package android.bluetooth { field public static final int UNSPECIFIED = 0; // 0x0 } + @FlaggedApi("com.android.bluetooth.flags.socket_settings_api") public final class BluetoothSocketSettings { + method @IntRange(from=128, to=255) public int getL2capPsm(); + method @Nullable public String getRfcommServiceName(); + method @Nullable public java.util.UUID getRfcommUuid(); + method public int getSocketType(); + method public boolean isAuthenticationRequired(); + method public boolean isEncryptionRequired(); + } + + @FlaggedApi("com.android.bluetooth.flags.socket_settings_api") public static final class BluetoothSocketSettings.Builder { + ctor public BluetoothSocketSettings.Builder(); + method @NonNull public android.bluetooth.BluetoothSocketSettings build(); + method @NonNull public android.bluetooth.BluetoothSocketSettings.Builder setAuthenticationRequired(boolean); + method @NonNull public android.bluetooth.BluetoothSocketSettings.Builder setEncryptionRequired(boolean); + method @NonNull public android.bluetooth.BluetoothSocketSettings.Builder setL2capPsm(@IntRange(from=128, to=255) int); + method @NonNull public android.bluetooth.BluetoothSocketSettings.Builder setRfcommServiceName(@NonNull String); + method @NonNull public android.bluetooth.BluetoothSocketSettings.Builder setRfcommUuid(@NonNull java.util.UUID); + method @NonNull public android.bluetooth.BluetoothSocketSettings.Builder setSocketType(int); + } + public final class BluetoothStatusCodes { field public static final int ERROR_BLUETOOTH_NOT_ALLOWED = 2; // 0x2 field public static final int ERROR_BLUETOOTH_NOT_ENABLED = 1; // 0x1 diff --git a/framework/api/system-current.txt b/framework/api/system-current.txt index 4934454873..10cb58064b 100644 --- a/framework/api/system-current.txt +++ b/framework/api/system-current.txt @@ -215,6 +215,7 @@ package android.bluetooth { method @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public boolean isConnected(); method @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public boolean isEncrypted(); method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public boolean isInSilenceMode(); + method @FlaggedApi("com.android.bluetooth.flags.metadata_api_microphone_for_call_enabled") @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public boolean isMicrophonePreferredForCalls(); method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int isRequestAudioPolicyAsSinkSupported(); method public void prepareToEnterProcess(@NonNull android.content.AttributionSource); method @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public boolean removeBond(); @@ -223,6 +224,7 @@ package android.bluetooth { 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[]); + method @FlaggedApi("com.android.bluetooth.flags.metadata_api_microphone_for_call_enabled") @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int setMicrophonePreferredForCalls(boolean); method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public boolean setPhonebookAccessPermission(int); method @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public boolean setPin(@NonNull String); method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public boolean setSilenceMode(boolean); @@ -517,6 +519,7 @@ package android.bluetooth { } public static interface BluetoothLeAudio.Callback { + method @FlaggedApi("com.android.bluetooth.flags.leaudio_broadcast_api_manage_primary_group") public default void onBroadcastToUnicastFallbackGroupChanged(int); method public void onCodecConfigChanged(int, @NonNull android.bluetooth.BluetoothLeAudioCodecStatus); method public void onGroupNodeAdded(@NonNull android.bluetooth.BluetoothDevice, int); method public void onGroupNodeRemoved(@NonNull android.bluetooth.BluetoothDevice, int); @@ -1272,7 +1275,7 @@ package android.bluetooth.le { method @Deprecated @RequiresPermission(android.Manifest.permission.BLUETOOTH_SCAN) public void startTruncatedScan(java.util.List<android.bluetooth.le.TruncatedFilter>, android.bluetooth.le.ScanSettings, android.bluetooth.le.ScanCallback); } - @FlaggedApi("com.android.bluetooth.flags.channel_sounding") public final class ChannelSoundingParams implements android.os.Parcelable { + public final class ChannelSoundingParams implements android.os.Parcelable { method public int describeContents(); method public int getCsSecurityLevel(); method public int getLocationType(); @@ -1301,8 +1304,8 @@ package android.bluetooth.le { } public final class DistanceMeasurementManager { - method @FlaggedApi("com.android.bluetooth.flags.channel_sounding") @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int getChannelSoundingMaxSupportedSecurityLevel(@NonNull android.bluetooth.BluetoothDevice); - method @FlaggedApi("com.android.bluetooth.flags.channel_sounding") @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int getLocalChannelSoundingMaxSupportedSecurityLevel(); + method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int getChannelSoundingMaxSupportedSecurityLevel(@NonNull android.bluetooth.BluetoothDevice); + method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int getLocalChannelSoundingMaxSupportedSecurityLevel(); method @NonNull @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public java.util.List<android.bluetooth.le.DistanceMeasurementMethod> getSupportedMethods(); method @Nullable @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public android.os.CancellationSignal startMeasurementSession(@NonNull android.bluetooth.le.DistanceMeasurementParams, @NonNull java.util.concurrent.Executor, @NonNull android.bluetooth.le.DistanceMeasurementSession.Callback); } @@ -1316,7 +1319,7 @@ package android.bluetooth.le { method public void writeToParcel(android.os.Parcel, int); field @NonNull public static final android.os.Parcelable.Creator<android.bluetooth.le.DistanceMeasurementMethod> CREATOR; field public static final int DISTANCE_MEASUREMENT_METHOD_AUTO = 0; // 0x0 - field @FlaggedApi("com.android.bluetooth.flags.channel_sounding") public static final int DISTANCE_MEASUREMENT_METHOD_CHANNEL_SOUNDING = 2; // 0x2 + field public static final int DISTANCE_MEASUREMENT_METHOD_CHANNEL_SOUNDING = 2; // 0x2 field public static final int DISTANCE_MEASUREMENT_METHOD_RSSI = 1; // 0x1 } @@ -1329,7 +1332,7 @@ package android.bluetooth.le { public final class DistanceMeasurementParams implements android.os.Parcelable { method public int describeContents(); - method @FlaggedApi("com.android.bluetooth.flags.channel_sounding") @Nullable public android.bluetooth.le.ChannelSoundingParams getChannelSoundingParams(); + method @Nullable public android.bluetooth.le.ChannelSoundingParams getChannelSoundingParams(); method public static int getDefaultDurationSeconds(); method @NonNull public android.bluetooth.BluetoothDevice getDevice(); method @IntRange(from=0) public int getDurationSeconds(); @@ -1346,7 +1349,7 @@ package android.bluetooth.le { public static final class DistanceMeasurementParams.Builder { ctor public DistanceMeasurementParams.Builder(@NonNull android.bluetooth.BluetoothDevice); method @NonNull public android.bluetooth.le.DistanceMeasurementParams build(); - method @FlaggedApi("com.android.bluetooth.flags.channel_sounding") @NonNull public android.bluetooth.le.DistanceMeasurementParams.Builder setChannelSoundingParams(@NonNull android.bluetooth.le.ChannelSoundingParams); + method @NonNull public android.bluetooth.le.DistanceMeasurementParams.Builder setChannelSoundingParams(@NonNull android.bluetooth.le.ChannelSoundingParams); method @NonNull public android.bluetooth.le.DistanceMeasurementParams.Builder setDurationSeconds(@IntRange(from=0) int); method @NonNull public android.bluetooth.le.DistanceMeasurementParams.Builder setFrequency(int); method @NonNull public android.bluetooth.le.DistanceMeasurementParams.Builder setMethodId(int); @@ -1356,25 +1359,25 @@ package android.bluetooth.le { method public int describeContents(); method @FloatRange(from=-90.0, to=90.0) public double getAltitudeAngle(); method @FloatRange(from=0.0, to=360.0) public double getAzimuthAngle(); - method @FlaggedApi("com.android.bluetooth.flags.channel_sounding") @FloatRange(from=0.0, to=1.0) public double getConfidenceLevel(); - method @FlaggedApi("com.android.bluetooth.flags.channel_sounding") public double getDelaySpreadMeters(); - method @FlaggedApi("com.android.bluetooth.flags.channel_sounding") public int getDetectedAttackLevel(); + method @FloatRange(from=0.0, to=1.0) public double getConfidenceLevel(); + method public double getDelaySpreadMeters(); + method public int getDetectedAttackLevel(); method public double getErrorAltitudeAngle(); method public double getErrorAzimuthAngle(); method @FloatRange(from=0.0) public double getErrorMeters(); method @FlaggedApi("com.android.bluetooth.flags.channel_sounding_25q2_apis") public long getMeasurementTimestampNanos(); method public double getResultMeters(); - method @FlaggedApi("com.android.bluetooth.flags.channel_sounding") public double getVelocityMetersPerSecond(); + method public double getVelocityMetersPerSecond(); method public void writeToParcel(android.os.Parcel, int); field @NonNull public static final android.os.Parcelable.Creator<android.bluetooth.le.DistanceMeasurementResult> CREATOR; - field @FlaggedApi("com.android.bluetooth.flags.channel_sounding") public static final int NADM_ATTACK_IS_EXTREMELY_LIKELY = 6; // 0x6 - field @FlaggedApi("com.android.bluetooth.flags.channel_sounding") public static final int NADM_ATTACK_IS_EXTREMELY_UNLIKELY = 0; // 0x0 - field @FlaggedApi("com.android.bluetooth.flags.channel_sounding") public static final int NADM_ATTACK_IS_LIKELY = 4; // 0x4 - field @FlaggedApi("com.android.bluetooth.flags.channel_sounding") public static final int NADM_ATTACK_IS_POSSIBLE = 3; // 0x3 - field @FlaggedApi("com.android.bluetooth.flags.channel_sounding") public static final int NADM_ATTACK_IS_UNLIKELY = 2; // 0x2 - field @FlaggedApi("com.android.bluetooth.flags.channel_sounding") public static final int NADM_ATTACK_IS_VERY_LIKELY = 5; // 0x5 - field @FlaggedApi("com.android.bluetooth.flags.channel_sounding") public static final int NADM_ATTACK_IS_VERY_UNLIKELY = 1; // 0x1 - field @FlaggedApi("com.android.bluetooth.flags.channel_sounding") public static final int NADM_UNKNOWN = 255; // 0xff + field public static final int NADM_ATTACK_IS_EXTREMELY_LIKELY = 6; // 0x6 + field public static final int NADM_ATTACK_IS_EXTREMELY_UNLIKELY = 0; // 0x0 + field public static final int NADM_ATTACK_IS_LIKELY = 4; // 0x4 + field public static final int NADM_ATTACK_IS_POSSIBLE = 3; // 0x3 + field public static final int NADM_ATTACK_IS_UNLIKELY = 2; // 0x2 + field public static final int NADM_ATTACK_IS_VERY_LIKELY = 5; // 0x5 + field public static final int NADM_ATTACK_IS_VERY_UNLIKELY = 1; // 0x1 + field public static final int NADM_UNKNOWN = 255; // 0xff } public static final class DistanceMeasurementResult.Builder { @@ -1382,13 +1385,13 @@ 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=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 setConfidenceLevel(@FloatRange(from=0.0, to=1.0) double); + method @NonNull public android.bluetooth.le.DistanceMeasurementResult.Builder setDelaySpreadMeters(double); + method @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); method @NonNull public android.bluetooth.le.DistanceMeasurementResult.Builder setErrorAzimuthAngle(@FloatRange(from=0.0, to=360.0) double); method @FlaggedApi("com.android.bluetooth.flags.channel_sounding_25q2_apis") @NonNull public android.bluetooth.le.DistanceMeasurementResult.Builder setMeasurementTimestampNanos(long); - method @FlaggedApi("com.android.bluetooth.flags.channel_sounding") @NonNull public android.bluetooth.le.DistanceMeasurementResult.Builder setVelocityMetersPerSecond(double); + method @NonNull public android.bluetooth.le.DistanceMeasurementResult.Builder setVelocityMetersPerSecond(double); } public final class DistanceMeasurementSession { diff --git a/framework/jarjar-rules.txt b/framework/jarjar-rules.txt index cff2b1aa31..ea92140499 100644 --- a/framework/jarjar-rules.txt +++ b/framework/jarjar-rules.txt @@ -11,3 +11,4 @@ rule com.google.android.mms.** com.android.bluetooth.jarjar.@0 rule com.android.internal.util.** com.android.bluetooth.jarjar.@0 rule com.android.modules.expresslog.** com.android.bluetooth.jarjar.@0 rule com.android.bluetooth.flags.** com.android.bluetooth.jarjar.@0 +rule bluetooth.constants.** com.android.bluetooth.jarjar.@0 diff --git a/framework/java/android/bluetooth/AudioInputControl.java b/framework/java/android/bluetooth/AudioInputControl.java new file mode 100644 index 0000000000..d700632bb7 --- /dev/null +++ b/framework/java/android/bluetooth/AudioInputControl.java @@ -0,0 +1,519 @@ +/* + * 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 android.bluetooth; + +import static android.Manifest.permission.BLUETOOTH_CONNECT; +import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothUtils.callService; +import static android.bluetooth.BluetoothUtils.logRemoteException; + +import static java.util.Objects.requireNonNull; + +import android.annotation.CallbackExecutor; +import android.annotation.IntDef; +import android.annotation.NonNull; +import android.annotation.RequiresNoPermission; +import android.annotation.RequiresPermission; +import android.bluetooth.annotations.RequiresBluetoothConnectPermission; +import android.content.AttributionSource; +import android.os.RemoteException; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.util.List; +import java.util.concurrent.Executor; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +/** + * This class provides APIs to control a remote AICS(Audio Input Control Service) + * + * @see BluetoothVolumeControl#getAudioInputControlPoints + * @hide + */ +public final class AudioInputControl { + private static final String TAG = AudioInputControl.class.getSimpleName(); + + /** Unspecified Input */ + public static final int AUDIO_INPUT_TYPE_UNSPECIFIED = + bluetooth.constants.AudioInputType.UNSPECIFIED; + + /** Bluetooth Audio Stream */ + public static final int AUDIO_INPUT_TYPE_BLUETOOTH = + bluetooth.constants.AudioInputType.BLUETOOTH; + + /** Microphone */ + public static final int AUDIO_INPUT_TYPE_MICROPHONE = + bluetooth.constants.AudioInputType.MICROPHONE; + + /** Analog Interface */ + public static final int AUDIO_INPUT_TYPE_ANALOG = bluetooth.constants.AudioInputType.ANALOG; + + /** Digital Interface */ + public static final int AUDIO_INPUT_TYPE_DIGITAL = bluetooth.constants.AudioInputType.DIGITAL; + + /** AM/FM/XM/etc. */ + public static final int AUDIO_INPUT_TYPE_RADIO = bluetooth.constants.AudioInputType.RADIO; + + /** Streaming Audio Source */ + public static final int AUDIO_INPUT_TYPE_STREAMING = + bluetooth.constants.AudioInputType.STREAMING; + + /** Transparency/Pass-through */ + public static final int AUDIO_INPUT_TYPE_AMBIENT = bluetooth.constants.AudioInputType.AMBIENT; + + /** @hide */ + @Retention(RetentionPolicy.SOURCE) + @IntDef( + prefix = {"AUDIO_INPUT_TYPE_"}, + value = { + AUDIO_INPUT_TYPE_UNSPECIFIED, + AUDIO_INPUT_TYPE_BLUETOOTH, + AUDIO_INPUT_TYPE_MICROPHONE, + AUDIO_INPUT_TYPE_ANALOG, + AUDIO_INPUT_TYPE_DIGITAL, + AUDIO_INPUT_TYPE_RADIO, + AUDIO_INPUT_TYPE_STREAMING, + AUDIO_INPUT_TYPE_AMBIENT, + }) + public @interface AudioInputType {} + + /** Inactive */ + public static final int AUDIO_INPUT_STATUS_INACTIVE = + bluetooth.constants.aics.AudioInputStatus.INACTIVE; + + /** Active */ + public static final int AUDIO_INPUT_STATUS_ACTIVE = + bluetooth.constants.aics.AudioInputStatus.ACTIVE; + + /** @hide */ + @Retention(RetentionPolicy.SOURCE) + @IntDef( + prefix = {"AUDIO_INPUT_STATUS_"}, + value = { + AUDIO_INPUT_STATUS_INACTIVE, + AUDIO_INPUT_STATUS_ACTIVE, + }) + public @interface AudioInputStatus {} + + /** Not Muted */ + public static final int MUTE_NOT_MUTED = bluetooth.constants.aics.Mute.NOT_MUTED; + + /** Muted */ + public static final int MUTE_MUTED = bluetooth.constants.aics.Mute.MUTED; + + /** Disabled */ + public static final int MUTE_DISABLED = bluetooth.constants.aics.Mute.DISABLED; + + /** @hide */ + @Retention(RetentionPolicy.SOURCE) + @IntDef( + prefix = {"MUTE_"}, + value = { + MUTE_NOT_MUTED, + MUTE_MUTED, + MUTE_DISABLED, + }) + public @interface Mute {} + + /** Manual Only */ + public static final int GAIN_MODE_MANUAL_ONLY = bluetooth.constants.aics.GainMode.MANUAL_ONLY; + + /** Automatic Only */ + public static final int GAIN_MODE_AUTOMATIC_ONLY = + bluetooth.constants.aics.GainMode.AUTOMATIC_ONLY; + + /** Manual */ + public static final int GAIN_MODE_MANUAL = bluetooth.constants.aics.GainMode.MANUAL; + + /** Automatic */ + public static final int GAIN_MODE_AUTOMATIC = bluetooth.constants.aics.GainMode.AUTOMATIC; + + /** @hide */ + @Retention(RetentionPolicy.SOURCE) + @IntDef( + prefix = {"GAIN_MODE_"}, + value = { + GAIN_MODE_MANUAL_ONLY, + GAIN_MODE_AUTOMATIC_ONLY, + GAIN_MODE_MANUAL, + GAIN_MODE_AUTOMATIC, + }) + public @interface GainMode {} + + private final IBluetoothVolumeControl mService; + private final @NonNull BluetoothDevice mDevice; + private final int mInstanceId; + private final AttributionSource mAttributionSource; + private final CallbackWrapper<AudioInputCallback, IBluetoothVolumeControl> mCallbackWrapper; + + /** @hide */ + public AudioInputControl( + @NonNull BluetoothDevice device, + int id, + @NonNull IBluetoothVolumeControl service, + @NonNull AttributionSource source) { + mDevice = requireNonNull(device); + mInstanceId = id; + mService = requireNonNull(service); + mAttributionSource = requireNonNull(source); + mCallbackWrapper = + new CallbackWrapper<AudioInputCallback, IBluetoothVolumeControl>( + this::registerCallbackFn, this::unregisterCallbackFn); + } + + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + private void registerCallbackFn(IBluetoothVolumeControl vcs) { + try { + vcs.registerAudioInputControlCallback( + mAttributionSource, mDevice, mInstanceId, mCallback); + } catch (RemoteException e) { + logRemoteException(TAG, e); + } + } + + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + private void unregisterCallbackFn(IBluetoothVolumeControl vcs) { + try { + vcs.unregisterAudioInputControlCallback( + mAttributionSource, mDevice, mInstanceId, mCallback); + } catch (RemoteException e) { + logRemoteException(TAG, e); + } + } + + private final IAudioInputCallback mCallback = + new IAudioInputCallback.Stub() { + @Override + @RequiresNoPermission + public void onDescriptionChanged(String description) { + mCallbackWrapper.forEach(cb -> cb.onDescriptionChanged(description)); + } + + @Override + @RequiresNoPermission + public void onStatusChanged(int status) { + mCallbackWrapper.forEach(cb -> cb.onStatusChanged(status)); + } + + @Override + @RequiresNoPermission + public void onStateChanged(int gainSetting, int mute, int gainMode) { + mCallbackWrapper.forEach(cb -> cb.onGainSettingChanged(gainSetting)); + mCallbackWrapper.forEach(cb -> cb.onMuteChanged(mute)); + mCallbackWrapper.forEach(cb -> cb.onGainModeChanged(gainMode)); + } + + @Override + @RequiresNoPermission + public void onSetGainSettingFailed() { + mCallbackWrapper.forEach(cb -> cb.onSetGainSettingFailed()); + } + + @Override + @RequiresNoPermission + public void onSetGainModeFailed() { + mCallbackWrapper.forEach(cb -> cb.onSetGainModeFailed()); + } + + @Override + @RequiresNoPermission + public void onSetMuteFailed() { + mCallbackWrapper.forEach(cb -> cb.onSetMuteFailed()); + } + }; + + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + static List<AudioInputControl> getAudioInputControlServices( + @NonNull IBluetoothVolumeControl service, + @NonNull AttributionSource source, + @NonNull BluetoothDevice device) { + requireNonNull(service); + requireNonNull(source); + requireNonNull(device); + int numberOfAics = 0; + try { + numberOfAics = service.getNumberOfAudioInputControlServices(source, device); + } catch (RemoteException e) { + logRemoteException(TAG, e); + } + return IntStream.range(0, numberOfAics) + .mapToObj(i -> new AudioInputControl(device, i, service, source)) + .collect(Collectors.toList()); + } + + /** + * This class provides a callback that is invoked when value changes on the remote device. + * + * @hide + */ + public interface AudioInputCallback { + /** @hide */ + default void onDescriptionChanged(@NonNull String description) {} + + /** @hide */ + default void onStatusChanged(@AudioInputStatus int status) {} + + /** @hide */ + default void onGainModeChanged(@GainMode int gainMode) {} + + /** @hide */ + default void onMuteChanged(@Mute int mute) {} + + /** @hide */ + default void onGainSettingChanged(int gainSetting) {} + + /** @hide */ + default void onSetGainSettingFailed() {} + + /** @hide */ + default void onSetGainModeFailed() {} + + /** @hide */ + default void onSetMuteFailed() {} + } + + /** + * Register a {@link AudioInputCallback} + * + * <p>Repeated registration of the same <var>callback</var> object will have no effect after the + * first call to this method, even when the <var>executor</var> is different. API caller would + * have to call {@link #unregisterCallback(Callback)} with the same callback object before + * registering it again. + * + * @param executor an {@link Executor} to execute given callback + * @param callback user implementation of the {@link AudioInputCallback} + * @throws IllegalArgumentException if callback is already registered + * @hide + */ + @RequiresBluetoothConnectPermission + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + public void registerCallback( + @NonNull @CallbackExecutor Executor executor, @NonNull AudioInputCallback callback) { + mCallbackWrapper.registerCallback(mService, callback, executor); + } + + /** + * Unregister the specified {@link AudioInputCallback}. + * + * <p>The same {@link AudioInputCallback} object used when calling {@link + * #registerCallback(Executor, AudioInputCallback)} must be used. + * + * <p>Callbacks are automatically unregistered when application process goes away + * + * @param callback user implementation of the {@link AudioInputCallback} + * @throws IllegalArgumentException when no callback is registered + * @hide + */ + @RequiresBluetoothConnectPermission + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + public void unregisterCallback(@NonNull AudioInputCallback callback) { + mCallbackWrapper.unregisterCallback(mService, callback); + } + + /** + * @return The Audio Input Type as defined in Audio Input Control Service 1.0 - 3.3. + * @hide + */ + @RequiresBluetoothConnectPermission + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + public @AudioInputType int getType() { + return callService( + mService, + s -> s.getAudioInputType(mAttributionSource, mDevice, mInstanceId), + bluetooth.constants.AudioInputType.UNSPECIFIED); + } + + /** + * @return The Gain Setting Units as defined in Audio Input Control Service 1.0 - 3.2.1 + * @hide + */ + @RequiresBluetoothConnectPermission + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + public int getGainSettingUnit() { + return callService( + mService, + s -> s.getAudioInputGainSettingUnit(mAttributionSource, mDevice, mInstanceId), + 0); + } + + /** + * @return The Gain Setting Units as defined in Audio Input Control Service 1.0 - 3.2.1 + * @hide + */ + @RequiresBluetoothConnectPermission + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + public int getGainSettingMin() { + return callService( + mService, + s -> s.getAudioInputGainSettingMin(mAttributionSource, mDevice, mInstanceId), + 0); + } + + /** + * @return The Gain Setting Units as defined in Audio Input Control Service 1.0 - 3.2.1 + * @hide + */ + @RequiresBluetoothConnectPermission + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + public int getGainSettingMax() { + return callService( + mService, + s -> s.getAudioInputGainSettingMax(mAttributionSource, mDevice, mInstanceId), + 0); + } + + /** + * @return The Gain Setting Units as defined in Audio Input Control Service 1.0 - 3.2.1 + * @hide + */ + @RequiresBluetoothConnectPermission + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + public @NonNull String getDescription() { + return callService( + mService, + s -> s.getAudioInputDescription(mAttributionSource, mDevice, mInstanceId), + ""); + } + + /** + * @return The Gain Setting Units as defined in Audio Input Control Service 1.0 - 3.2.1 + * @hide + */ + @RequiresBluetoothConnectPermission + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + public boolean isDescriptionWritable() { + return callService( + mService, + s -> s.isAudioInputDescriptionWritable(mAttributionSource, mDevice, mInstanceId), + false); + } + + /** + * @return The Gain Setting Units as defined in Audio Input Control Service 1.0 - 3.2.1 + * @hide + */ + @RequiresBluetoothConnectPermission + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + public boolean setDescription(@NonNull String description) { + return callService( + mService, + s -> + s.setAudioInputDescription( + mAttributionSource, mDevice, mInstanceId, description), + false); + } + + /** + * @return The Audio Input Status as defined in Audio Input Control Service 1.0 - 3.4. + * @hide + */ + @RequiresBluetoothConnectPermission + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + public @AudioInputStatus int getStatus() { + return callService( + mService, + s -> s.getAudioInputStatus(mAttributionSource, mDevice, mInstanceId), + (int) bluetooth.constants.aics.AudioInputStatus.INACTIVE); + } + + /** + * @return The Audio Input Status as defined in Audio Input Control Service 1.0 - 3.4. + * @hide + */ + @RequiresBluetoothConnectPermission + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + public int getGainSetting() { + return callService( + mService, + s -> s.getAudioInputGainSetting(mAttributionSource, mDevice, mInstanceId), + 0); + } + + /** + * @return The Audio Input Status as defined in Audio Input Control Service 1.0 - 3.4. + * @hide + */ + @RequiresBluetoothConnectPermission + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + public boolean setGainSetting(int gainSetting) { + return callService( + mService, + s -> + s.setAudioInputGainSetting( + mAttributionSource, mDevice, mInstanceId, gainSetting), + false); + } + + /** + * @return The Audio Input Status as defined in Audio Input Control Service 1.0 - 3.4. + * @hide + */ + @RequiresBluetoothConnectPermission + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + public @GainMode int getGainMode() { + return callService( + mService, + s -> s.getAudioInputGainMode(mAttributionSource, mDevice, mInstanceId), + (int) bluetooth.constants.aics.GainMode.AUTOMATIC_ONLY); + } + + /** + * @return The Audio Input Status as defined in Audio Input Control Service 1.0 - 3.4. + * @hide + */ + @RequiresBluetoothConnectPermission + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + public boolean setGainMode(@GainMode int gainMode) { + if (gainMode < GAIN_MODE_MANUAL_ONLY || gainMode > GAIN_MODE_AUTOMATIC) { + throw new IllegalArgumentException("Illegal GainMode value: " + gainMode); + } + return callService( + mService, + s -> s.setAudioInputGainMode(mAttributionSource, mDevice, mInstanceId, gainMode), + false); + } + + /** + * @return The Audio Input Status as defined in Audio Input Control Service 1.0 - 3.4. + * @hide + */ + @RequiresBluetoothConnectPermission + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + public @Mute int getMute() { + return callService( + mService, + s -> s.getAudioInputMute(mAttributionSource, mDevice, mInstanceId), + (int) bluetooth.constants.aics.Mute.DISABLED); + } + + /** + * @return The Audio Input Status as defined in Audio Input Control Service 1.0 - 3.4. + * @hide + */ + @RequiresBluetoothConnectPermission + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + public boolean setMute(@Mute int mute) { + if (mute < MUTE_NOT_MUTED || mute > MUTE_MUTED) { + throw new IllegalArgumentException("Illegal mute value: " + mute); + } + return callService( + mService, + s -> s.setAudioInputMute(mAttributionSource, mDevice, mInstanceId, mute), + false); + } +} diff --git a/framework/java/android/bluetooth/BluetoothAdapter.java b/framework/java/android/bluetooth/BluetoothAdapter.java index 64055909bc..8b814cb6bf 100644 --- a/framework/java/android/bluetooth/BluetoothAdapter.java +++ b/framework/java/android/bluetooth/BluetoothAdapter.java @@ -4542,8 +4542,7 @@ public final class BluetoothAdapter { * another Android device that is given the PSM value. * * @return an L2CAP CoC BluetoothServerSocket - * @throws IOException on error, for example Bluetooth not available, or insufficient - * permissions, or unable to start this CoC + * @throws IOException on error, for example Bluetooth not available or unable to start this CoC */ @RequiresLegacyBluetoothPermission @RequiresBluetoothConnectPermission @@ -4598,8 +4597,7 @@ public final class BluetoothAdapter { * socket from another Android device that is given the PSM value. * * @return an L2CAP CoC BluetoothServerSocket - * @throws IOException on error, for example Bluetooth not available, or insufficient - * permissions, or unable to start this CoC + * @throws IOException on error, for example Bluetooth not available or unable to start this CoC */ @RequiresLegacyBluetoothPermission @RequiresBluetoothConnectPermission @@ -4631,6 +4629,81 @@ public final class BluetoothAdapter { } /** + * Creates a listening server channel for Bluetooth connections with the specified socket + * settings {@link BluetoothSocketSettings}. + * + * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming connections from a listening + * {@link BluetoothServerSocket}. + * + * <p>This API supports {@link BluetoothSocket#TYPE_RFCOMM} and {{@link BluetoothSocket#TYPE_LE} + * only, which can be set using {@link BluetoothSocketSettings#setSocketType()}. + * <li>For `BluetoothSocket.TYPE_RFCOMM`: The RFCOMM UUID must be provided using {@link + * BluetoothSocketSettings#setRfcommUuid()}. + * <li>For `BluetoothSocket.TYPE_LE`: The system assigns a dynamic protocol/service multiplexer + * (PSM) value. This value can be read from {@link BluetoothServerSocket#getPsm()}. This + * value is released when the server socket is closed, Bluetooth is turned off, or the + * application exits unexpectedly. The mechanism for disclosing the PSM value to the client + * is application-defined. + * + * <p>Use {@link BluetoothDevice#createUsingSocketSettings(BluetoothSocketSettings)} to + * connect to this server socket from another Android device using the L2cap + * protocol/service multiplexer(PSM) value or the RFCOMM service UUID as input. + * + * @param settings Bluetooth socket settings {@link BluetoothSocketSettings}. + * @return a {@link BluetoothServerSocket} + * @throws IllegalArgumentException if BluetoothSocket#TYPE_RFCOMM socket is requested with no + * UUID. + * @throws IOException on error, for example Bluetooth not available or unable to start this LE + * Connection-oriented Channel (CoC). + */ + @RequiresBluetoothConnectPermission + @RequiresPermission(BLUETOOTH_CONNECT) + @FlaggedApi(Flags.FLAG_SOCKET_SETTINGS_API) + public @NonNull BluetoothServerSocket listenUsingSocketSettings( + @NonNull BluetoothSocketSettings settings) throws IOException { + + BluetoothServerSocket socket; + int type = settings.getSocketType(); + if (type == BluetoothSocket.TYPE_RFCOMM) { + if (settings.getRfcommUuid() == null) { + throw new IllegalArgumentException("RFCOMM server missing UUID"); + } + return createNewRfcommSocketAndRecord( + settings.getRfcommServiceName(), + settings.getRfcommUuid(), + settings.isAuthenticationRequired(), + settings.isEncryptionRequired()); + } else if (type == BluetoothSocket.TYPE_LE) { + socket = + new BluetoothServerSocket( + settings.getSocketType(), + settings.isAuthenticationRequired(), + settings.isEncryptionRequired(), + SOCKET_CHANNEL_AUTO_STATIC_NO_SDP, + false, + false); + } else { + throw new IOException("Error: Invalid socket type: " + type); + } + int errno = socket.mSocket.bindListen(); + if (errno != 0) { + throw new IOException("Error: " + errno); + } + if (type == BluetoothSocket.TYPE_LE) { + int assignedPsm = socket.mSocket.getPort(); + if (assignedPsm == 0) { + throw new IOException("Error: Unable to assign PSM value"); + } + if (DBG) { + Log.d(TAG, "listenUsingSocketSettings: set assigned PSM to " + assignedPsm); + } + socket.setChannel(assignedPsm); + } + + return socket; + } + + /** * Register a {@link #OnMetadataChangedListener} to receive update about metadata changes for * this {@link BluetoothDevice}. Registration must be done when Bluetooth is ON and will last * until {@link #removeOnMetadataChangedListener(BluetoothDevice)} is called, even when diff --git a/framework/java/android/bluetooth/BluetoothDevice.java b/framework/java/android/bluetooth/BluetoothDevice.java index 0fa2ad4789..ca3ba406db 100644 --- a/framework/java/android/bluetooth/BluetoothDevice.java +++ b/framework/java/android/bluetooth/BluetoothDevice.java @@ -3218,6 +3218,60 @@ public final class BluetoothDevice implements Parcelable, Attributable { } /** + * Creates a client socket to connect to a remote Bluetooth server with the specified socket + * settings {@link BluetoothSocketSettings} This API is used to connect to a remote server + * hosted using {@link BluetoothAdapter#listenUsingSocketSettings}. + * + * <ul> + * <li>For `BluetoothSocket.TYPE_RFCOMM`: The RFCOMM UUID must be provided using {@link + * BluetoothSocketSettings#setRfcommUuid()}. + * <li>For `BluetoothSocket.TYPE_LE`: The L2cap protocol/service multiplexer (PSM) value must + * be provided using {@link BluetoothSocketSettings#setL2capPsm()}. + * </ul> + * + * <p>Application using this API is responsible for obtaining protocol/service multiplexer (psm) + * value from remote device. + * + * <p>Use {@link BluetoothSocket#connect} to initiate the outgoing connection. + * + * @param settings Bluetooth socket settings {@link BluetoothSocketSettings}. + * @return a {@link BluetoothSocket} ready for an outgoing connection. + * @throws IllegalArgumentException if BluetoothSocket#TYPE_RFCOMM socket with no UUID is passed + * as input or if BluetoothSocket#TYPE_LE with invalid PSM is passed. + * @throws IOException on error, for example Bluetooth not available. + */ + @FlaggedApi(Flags.FLAG_SOCKET_SETTINGS_API) + public @NonNull BluetoothSocket createUsingSocketSettings( + @NonNull BluetoothSocketSettings settings) throws IOException { + if (!isBluetoothEnabled()) { + Log.e(TAG, "createUsingSocketSettings: Bluetooth is not enabled"); + throw new IOException(); + } + if (DBG) { + Log.d(TAG, "createUsingSocketSettings: =" + settings.getL2capPsm()); + } + ParcelUuid uuid = null; + int psm = settings.getL2capPsm(); + if (settings.getSocketType() == BluetoothSocket.TYPE_RFCOMM) { + if (settings.getRfcommUuid() == null) { + throw new IllegalArgumentException("null uuid: " + settings.getRfcommUuid()); + } + uuid = new ParcelUuid(settings.getRfcommUuid()); + } else if (settings.getSocketType() == BluetoothSocket.TYPE_LE) { + if (psm < 128 || psm > 255) { + throw new IllegalArgumentException("Invalid PSM/Channel value: " + psm); + } + } + return new BluetoothSocket( + this, + settings.getSocketType(), + settings.isAuthenticationRequired(), + settings.isEncryptionRequired(), + psm, + uuid); + } + + /** * Set a keyed metadata of this {@link BluetoothDevice} to a {@link String} value. Only bonded * devices's metadata will be persisted across Bluetooth restart. Metadata will be removed when * the device's bond state is moved to {@link #BOND_NONE}. @@ -3534,6 +3588,86 @@ public final class BluetoothDevice implements Parcelable, Attributable { return ACTIVE_AUDIO_DEVICE_POLICY_DEFAULT; } + /** @hide */ + @IntDef( + value = { + BluetoothStatusCodes.SUCCESS, + BluetoothStatusCodes.ERROR_BLUETOOTH_NOT_ENABLED, + BluetoothStatusCodes.ERROR_MISSING_BLUETOOTH_CONNECT_PERMISSION, + BluetoothStatusCodes.ERROR_DEVICE_NOT_BONDED + }) + @Retention(RetentionPolicy.SOURCE) + public @interface SetMicrophonePreferredForCallsReturnValues {} + + /** + * Sets whether this {@link BluetoothDevice} should be the preferred microphone for calls. + * + * <p>This API is for Bluetooth audio devices and only sets a preference. The caller is + * responsible for changing the audio input routing to reflect the preference. + * + * @param enabled {@code true} to set the device as the preferred microphone for calls, {@code + * false} otherwise. + * @return Whether the preferred microphone for calls was set properly. + * @throws IllegalArgumentException if the {@link BluetoothDevice} object has an invalid + * address. + * @hide + */ + @FlaggedApi(Flags.FLAG_METADATA_API_MICROPHONE_FOR_CALL_ENABLED) + @SystemApi + @RequiresBluetoothConnectPermission + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + public @SetMicrophonePreferredForCallsReturnValues int setMicrophonePreferredForCalls( + boolean enabled) { + if (DBG) log("setMicrophonePreferredForCalls(" + enabled + ")"); + if (!BluetoothAdapter.checkBluetoothAddress(getAddress())) { + throw new IllegalArgumentException("device cannot have an invalid address"); + } + + final IBluetooth service = getService(); + if (service == null || !isBluetoothEnabled()) { + Log.e(TAG, "Bluetooth is not enabled. Cannot set microphone for call enabled state."); + if (DBG) log(Log.getStackTraceString(new Throwable())); + } else { + try { + return service.setMicrophonePreferredForCalls(this, enabled, mAttributionSource); + } catch (RemoteException e) { + Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); + } + } + return BluetoothStatusCodes.ERROR_BLUETOOTH_NOT_ENABLED; + } + + /** + * Gets whether this {@link BluetoothDevice} should be the preferred microphone for calls. + * + * <p>This API returns the configured preference for whether this device should be the preferred + * microphone for calls and return {@code true} by default in case of error. It does not reflect + * the current audio routing. + * + * @return {@code true} if the device is the preferred microphone for calls, {@code false} + * otherwise. + * @hide + */ + @FlaggedApi(Flags.FLAG_METADATA_API_MICROPHONE_FOR_CALL_ENABLED) + @SystemApi + @RequiresBluetoothConnectPermission + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + public boolean isMicrophonePreferredForCalls() { + if (DBG) log("isMicrophoneForCallEnabled"); + final IBluetooth service = getService(); + if (service == null || !isBluetoothEnabled()) { + Log.e(TAG, "Bluetooth is not enabled. Cannot get microphone for call enabled state."); + if (DBG) log(Log.getStackTraceString(new Throwable())); + } else { + try { + return service.isMicrophonePreferredForCalls(this, mAttributionSource); + } catch (RemoteException e) { + Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); + } + } + return true; + } + private static void log(String msg) { Log.d(TAG, msg); } diff --git a/framework/java/android/bluetooth/BluetoothLeAudio.java b/framework/java/android/bluetooth/BluetoothLeAudio.java index 6bc4a73de9..adecd2d9ef 100644 --- a/framework/java/android/bluetooth/BluetoothLeAudio.java +++ b/framework/java/android/bluetooth/BluetoothLeAudio.java @@ -155,6 +155,24 @@ public final class BluetoothLeAudio implements BluetoothProfile, AutoCloseable { Log.d(TAG, " onGroupStreamStatusChanged is not implemented."); } } + + /** + * Callback invoked when the broadcast to unicast fallback group changes. + * + * <p>This callback provides the new broadcast to unicast fallback group ID. It is invoked + * when the broadcast to unicast fallback group is initially set, or when it subsequently + * changes. + * + * @param groupId The ID of the new broadcast to unicast fallback group. + * @hide + */ + @FlaggedApi(Flags.FLAG_LEAUDIO_BROADCAST_API_MANAGE_PRIMARY_GROUP) + @SystemApi + default void onBroadcastToUnicastFallbackGroupChanged(int groupId) { + if (DBG) { + Log.d(TAG, "onBroadcastToUnicastFallbackGroupChanged is not implemented."); + } + } } private final CallbackWrapper<Callback, IBluetoothLeAudio> mCallbackWrapper; @@ -189,6 +207,14 @@ public final class BluetoothLeAudio implements BluetoothProfile, AutoCloseable { mCallbackWrapper.forEach( (cb) -> cb.onGroupStreamStatusChanged(groupId, groupStreamStatus)); } + + @Override + public void onBroadcastToUnicastFallbackGroupChanged(int groupId) { + if (Flags.leaudioBroadcastApiManagePrimaryGroup()) { + mCallbackWrapper.forEach( + (cb) -> cb.onBroadcastToUnicastFallbackGroupChanged(groupId)); + } + } } /** diff --git a/framework/java/android/bluetooth/BluetoothSocket.java b/framework/java/android/bluetooth/BluetoothSocket.java index a104101f12..901407c00b 100644 --- a/framework/java/android/bluetooth/BluetoothSocket.java +++ b/framework/java/android/bluetooth/BluetoothSocket.java @@ -21,6 +21,7 @@ import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; import static android.Manifest.permission.LOCAL_MAC_ADDRESS; import android.annotation.FlaggedApi; +import android.annotation.IntDef; import android.annotation.NonNull; import android.annotation.RequiresNoPermission; import android.annotation.RequiresPermission; @@ -42,6 +43,8 @@ import java.io.FileDescriptor; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; @@ -112,6 +115,8 @@ public final class BluetoothSocket implements Closeable { /** * L2CAP socket on BR/EDR transport * + * <p>To be removed once Flags.FLAG_SOCKET_SETTINGS_API is removed + * * @hide */ public static final int TYPE_L2CAP_BREDR = TYPE_L2CAP; @@ -119,10 +124,28 @@ public final class BluetoothSocket implements Closeable { /** * L2CAP socket on LE transport * + * <p>To be removed once Flags.FLAG_SOCKET_SETTINGS_API is removed + * * @hide */ public static final int TYPE_L2CAP_LE = 4; + /** L2CAP socket on LE transport */ + @FlaggedApi(Flags.FLAG_SOCKET_SETTINGS_API) + public static final int TYPE_LE = 4; + + /** @hide */ + @IntDef( + prefix = {"BluetoothSocket.TYPE_"}, + value = { + BluetoothSocket.TYPE_RFCOMM, + BluetoothSocket.TYPE_SCO, + BluetoothSocket.TYPE_L2CAP, + BluetoothSocket.TYPE_LE, + }) + @Retention(RetentionPolicy.SOURCE) + public @interface SocketType {} + /*package*/ static final int EBADFD = 77; @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) @@ -195,12 +218,7 @@ public final class BluetoothSocket implements Closeable { * @throws IOException On error, for example Bluetooth not available, or insufficient privileges */ @RequiresPermission(allOf = {BLUETOOTH_CONNECT, LOCAL_MAC_ADDRESS}) - /*package*/ BluetoothSocket( - int type, - boolean auth, - boolean encrypt, - int port, - ParcelUuid uuid) + /*package*/ BluetoothSocket(int type, boolean auth, boolean encrypt, int port, ParcelUuid uuid) throws IOException { this(type, auth, encrypt, port, uuid, false, false); } diff --git a/framework/java/android/bluetooth/BluetoothSocketSettings.java b/framework/java/android/bluetooth/BluetoothSocketSettings.java new file mode 100644 index 0000000000..6fa8b0dc8b --- /dev/null +++ b/framework/java/android/bluetooth/BluetoothSocketSettings.java @@ -0,0 +1,349 @@ +/* + * Copyright 2024 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.bluetooth; + +import static android.bluetooth.BluetoothSocket.SocketType; + +import android.annotation.FlaggedApi; +import android.annotation.IntRange; +import android.annotation.NonNull; +import android.annotation.Nullable; +import android.annotation.RequiresNoPermission; + +import com.android.bluetooth.flags.Flags; + +import java.util.UUID; + +/** + * Defines parameters for creating Bluetooth server and client socket channels. + * + * <p>Used with {@link BluetoothAdapter#listenUsingSocketSettings} to create a server socket and + * {@link BluetoothDevice#createUsingSocketSettings} to create a client socket. + * + * @see BluetoothAdapter#listenUsingSocketSettings + * @see BluetoothDevice#createUsingSocketSettings + */ +@FlaggedApi(Flags.FLAG_SOCKET_SETTINGS_API) +public final class BluetoothSocketSettings { + + private static final int L2CAP_PSM_UNSPECIFIED = -1; + + /** Type of the Bluetooth socket */ + @SocketType private int mSocketType; + + /** Encryption requirement for the Bluetooth socket. */ + private boolean mEncryptionRequired; + + /** Authentication requirement for the Bluetooth socket. */ + private boolean mAuthenticationRequired; + + /** L2CAP Protocol/Service Multiplexer (PSM) for the Bluetooth Socket. */ + private int mL2capPsm; + + /** RFCOMM service name associated with the Bluetooth socket. */ + private String mRfcommServiceName; + + /** RFCOMM service UUID associated with the Bluetooth socket. */ + private UUID mRfcommUuid; + + /** + * Returns the type of the Bluetooth socket. + * + * <p>Defaults to {@code BluetoothSocket#TYPE_RFCOMM}. + */ + @RequiresNoPermission + @SocketType + public int getSocketType() { + return mSocketType; + } + + /** Returns the L2CAP PSM value used for a BluetoothSocket#TYPE_LE socket. */ + @RequiresNoPermission + public @IntRange(from = 128, to = 255) int getL2capPsm() { + return mL2capPsm; + } + + /** + * Returns the RFCOMM service name used for a BluetoothSocket#TYPE_RFCOMM socket. + * + * <p>Defaults to {@code null}. + */ + @Nullable + @RequiresNoPermission + public String getRfcommServiceName() { + return mRfcommServiceName; + } + + /** + * Returns the RFCOMM service UUID used for a BluetoothSocket#TYPE_RFCOMM socket. + * + * <p>Defaults to {@code null}. + */ + @Nullable + @RequiresNoPermission + public UUID getRfcommUuid() { + return mRfcommUuid; + } + + /** + * Checks if encryption is enabled for the Bluetooth socket. + * + * <p>Defaults to {@code false}. + */ + @RequiresNoPermission + public boolean isEncryptionRequired() { + return mEncryptionRequired; + } + + /** + * Checks if authentication is enabled for the Bluetooth socket. + * + * <p>Defaults to {@code false}. + */ + @RequiresNoPermission + public boolean isAuthenticationRequired() { + return mAuthenticationRequired; + } + + /** + * Returns a {@link String} that describes each BluetoothSocketSettings parameter current value. + */ + @Override + public String toString() { + if (mSocketType == BluetoothSocket.TYPE_RFCOMM) { + return "BluetoothSocketSettings{" + + "mSocketType=" + + mSocketType + + ", mEncryptionRequired=" + + mEncryptionRequired + + ", mAuthenticationRequired=" + + mAuthenticationRequired + + ", mRfcommServiceName=" + + mRfcommServiceName + + ", mRfcommUuid=" + + mRfcommUuid + + "}"; + } else { + return "BluetoothSocketSettings{" + + "mSocketType=" + + mSocketType + + ", mL2capPsm=" + + mL2capPsm + + ", mEncryptionRequired=" + + mEncryptionRequired + + ", mAuthenticationRequired=" + + mAuthenticationRequired + + "}"; + } + } + + private BluetoothSocketSettings( + int socketType, + int l2capPsm, + boolean encryptionRequired, + boolean authenticationRequired, + String rfcommServiceName, + UUID rfcommUuid) { + mSocketType = socketType; + mL2capPsm = l2capPsm; + mEncryptionRequired = encryptionRequired; + mAuthenticationRequired = authenticationRequired; + mRfcommUuid = rfcommUuid; + mRfcommServiceName = rfcommServiceName; + } + + /** Builder for {@link BluetoothSocketSettings}. */ + @FlaggedApi(Flags.FLAG_SOCKET_SETTINGS_API) + public static final class Builder { + private int mSocketType = BluetoothSocket.TYPE_RFCOMM; + private int mL2capPsm = L2CAP_PSM_UNSPECIFIED; + private boolean mEncryptionRequired = false; + private boolean mAuthenticationRequired = false; + private String mRfcommServiceName = null; + private UUID mRfcommUuid = null; + + public Builder() {} + + /** + * Sets the socket type. + * + * <p>Must be one of: + * + * <ul> + * <li>{@link BluetoothSocket#TYPE_RFCOMM} + * <li>{@link BluetoothSocket#TYPE_LE} + * </ul> + * + * <p>Defaults to {@code BluetoothSocket#TYPE_RFCOMM}. + * + * @param socketType The type of socket. + * @return This builder. + * @throws IllegalArgumentException If {@code socketType} is invalid. + */ + @NonNull + @RequiresNoPermission + public Builder setSocketType(@SocketType int socketType) { + if (socketType != BluetoothSocket.TYPE_RFCOMM + && socketType != BluetoothSocket.TYPE_LE) { + throw new IllegalArgumentException("invalid socketType - " + socketType); + } + mSocketType = socketType; + return this; + } + + /** + * Sets the L2CAP PSM (Protocol/Service Multiplexer) for the Bluetooth socket. + * + * <p>This is only used for {@link BluetoothSocket#TYPE_LE} sockets. + * + * <p>Valid PSM values for {@link BluetoothSocket#TYPE_LE} sockets is ranging from 128 + * (0x80) to 255 (0xFF). + * + * <p>Application using this API is responsible for obtaining protocol/service multiplexer + * (PSM) value from remote device. + * + * @param l2capPsm The L2CAP PSM value. + * @return This builder. + * @throws IllegalArgumentException If l2cap PSM is not in given range. + */ + @NonNull + @RequiresNoPermission + public Builder setL2capPsm(@IntRange(from = 128, to = 255) int l2capPsm) { + if (l2capPsm < 128 || l2capPsm > 255) { + throw new IllegalArgumentException("invalid L2cap PSM - " + l2capPsm); + } + mL2capPsm = l2capPsm; + return this; + } + + /** + * Sets the encryption requirement for the Bluetooth socket. + * + * <p>Defaults to {@code false}. + * + * @param encryptionRequired {@code true} if encryption is required for this socket, {@code + * false} otherwise. + * @return This builder. + */ + @NonNull + @RequiresNoPermission + public Builder setEncryptionRequired(boolean encryptionRequired) { + mEncryptionRequired = encryptionRequired; + return this; + } + + /** + * Sets the authentication requirement for the Bluetooth socket. + * + * <p>Defaults to {@code false}. + * + * @param authenticationRequired {@code true} if authentication is required for this socket, + * {@code false} otherwise. + * @return This builder. + */ + @NonNull + @RequiresNoPermission + public Builder setAuthenticationRequired(boolean authenticationRequired) { + mAuthenticationRequired = authenticationRequired; + return this; + } + + /** + * Sets the RFCOMM service name associated with the Bluetooth socket. + * + * <p>This name is used to identify the service when a remote device searches for it using + * SDP. + * + * <p>This is only used for {@link BluetoothSocket#TYPE_RFCOMM} sockets. + * + * <p>Defaults to {@code null}. + * + * @param rfcommServiceName The RFCOMM service name. + * @return This builder. + */ + @NonNull + @RequiresNoPermission + public Builder setRfcommServiceName(@NonNull String rfcommServiceName) { + mRfcommServiceName = rfcommServiceName; + return this; + } + + /** + * Sets the RFCOMM service UUID associated with the Bluetooth socket. + * + * <p>This UUID is used to uniquely identify the service when a remote device searches for + * it using SDP. + * + * <p>This is only used for {@link BluetoothSocket#TYPE_RFCOMM} sockets. + * + * <p>Defaults to {@code null}. + * + * @param rfcommUuid The RFCOMM service UUID. + * @return This builder. + */ + @NonNull + @RequiresNoPermission + public Builder setRfcommUuid(@NonNull UUID rfcommUuid) { + mRfcommUuid = rfcommUuid; + return this; + } + + /** + * Builds a {@link BluetoothSocketSettings} object. + * + * @return A new {@link BluetoothSocketSettings} object with the configured parameters. + * @throws IllegalArgumentException on invalid parameters + */ + @NonNull + @RequiresNoPermission + public BluetoothSocketSettings build() { + if (mSocketType == BluetoothSocket.TYPE_RFCOMM) { + if (mRfcommUuid == null) { + throw new IllegalArgumentException("RFCOMM socket with missing uuid"); + } + if (mL2capPsm != L2CAP_PSM_UNSPECIFIED) { + throw new IllegalArgumentException( + "Invalid Socket config: " + + " Socket type: " + + mSocketType + + " L2cap PSM: " + + mL2capPsm); + } + } + if (mSocketType == BluetoothSocket.TYPE_LE) { + if (mRfcommUuid != null) { + throw new IllegalArgumentException( + "Invalid Socket config: " + + "Socket type: " + + mSocketType + + " Rfcomm Service Name: " + + mRfcommServiceName + + " Rfcomm Uuid: " + + mRfcommUuid); + } + } + + return new BluetoothSocketSettings( + mSocketType, + mL2capPsm, + mEncryptionRequired, + mAuthenticationRequired, + mRfcommServiceName, + mRfcommUuid); + } + } +} diff --git a/framework/java/android/bluetooth/BluetoothUtils.java b/framework/java/android/bluetooth/BluetoothUtils.java index a2b0393499..d7a09929f0 100644 --- a/framework/java/android/bluetooth/BluetoothUtils.java +++ b/framework/java/android/bluetooth/BluetoothUtils.java @@ -381,6 +381,11 @@ public final class BluetoothUtils { } } + public static <S, R> R callService( + S service, RemoteExceptionIgnoringFunction<S, R> function, R defaultValue) { + return function.apply(service, defaultValue); + } + public static <S, R> R callServiceIfEnabled( BluetoothAdapter adapter, Supplier<S> provider, @@ -395,7 +400,7 @@ public final class BluetoothUtils { Log.d(TAG, "Proxy not attached to service"); return defaultValue; } - return function.apply(service, defaultValue); + return callService(service, function, defaultValue); } public static <S> void callServiceIfEnabled( diff --git a/framework/java/android/bluetooth/BluetoothVolumeControl.java b/framework/java/android/bluetooth/BluetoothVolumeControl.java index 983802d817..f6985676db 100644 --- a/framework/java/android/bluetooth/BluetoothVolumeControl.java +++ b/framework/java/android/bluetooth/BluetoothVolumeControl.java @@ -396,7 +396,7 @@ public final class BluetoothVolumeControl implements BluetoothProfile, AutoClose * * @param executor an {@link Executor} to execute given callback * @param callback user implementation of the {@link Callback} - * @throws IllegalArgumentException if a null executor, sink, or callback is given + * @throws IllegalArgumentException if a null executor, or callback is given * @hide */ @SystemApi @@ -704,6 +704,26 @@ public final class BluetoothVolumeControl implements BluetoothProfile, AutoClose s -> s.setDeviceVolume(device, volume, isGroupOperation, mAttributionSource)); } + /** + * @return The list of {@code AudioInputControl} associated with a device + * @hide + */ + @RequiresBluetoothConnectPermission + @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) + public @NonNull List<AudioInputControl> getAudioInputControlPoints( + @NonNull BluetoothDevice device) { + requireNonNull(device); + Log.d(TAG, "getAudioInputControlPoints(" + device + ")"); + if (!isValidDevice(device)) { + throw new IllegalArgumentException("Invalid device " + device); + } + return callServiceIfEnabled( + mAdapter, + this::getService, + s -> AudioInputControl.getAudioInputControlServices(s, mAttributionSource, device), + Collections.emptyList()); + } + private static boolean isValidDevice(@Nullable BluetoothDevice device) { return device != null && BluetoothAdapter.checkBluetoothAddress(device.getAddress()); } diff --git a/framework/java/android/bluetooth/le/ChannelSoundingParams.java b/framework/java/android/bluetooth/le/ChannelSoundingParams.java index 7c6baf1cff..ab5b8b4b40 100644 --- a/framework/java/android/bluetooth/le/ChannelSoundingParams.java +++ b/framework/java/android/bluetooth/le/ChannelSoundingParams.java @@ -16,15 +16,12 @@ package android.bluetooth.le; -import android.annotation.FlaggedApi; import android.annotation.IntDef; import android.annotation.NonNull; import android.annotation.SystemApi; import android.os.Parcel; import android.os.Parcelable; -import com.android.bluetooth.flags.Flags; - import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -35,7 +32,6 @@ import java.lang.annotation.RetentionPolicy; * * @hide */ -@FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi public final class ChannelSoundingParams implements Parcelable { diff --git a/framework/java/android/bluetooth/le/DistanceMeasurementManager.java b/framework/java/android/bluetooth/le/DistanceMeasurementManager.java index 75ef152ef6..7a5eb37268 100644 --- a/framework/java/android/bluetooth/le/DistanceMeasurementManager.java +++ b/framework/java/android/bluetooth/le/DistanceMeasurementManager.java @@ -19,7 +19,6 @@ package android.bluetooth.le; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; -import android.annotation.FlaggedApi; import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.RequiresPermission; @@ -36,8 +35,6 @@ import android.os.ParcelUuid; import android.os.RemoteException; import android.util.Log; -import com.android.bluetooth.flags.Flags; - import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -169,7 +166,6 @@ public final class DistanceMeasurementManager { * when Channel Sounding is not supported or encounters an internal error. * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi @RequiresBluetoothConnectPermission @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) @@ -200,7 +196,6 @@ public final class DistanceMeasurementManager { * when Channel Sounding is not supported or encounters an internal error. * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi @RequiresBluetoothConnectPermission @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) diff --git a/framework/java/android/bluetooth/le/DistanceMeasurementMethod.java b/framework/java/android/bluetooth/le/DistanceMeasurementMethod.java index 12b1a940f1..eb4032057d 100644 --- a/framework/java/android/bluetooth/le/DistanceMeasurementMethod.java +++ b/framework/java/android/bluetooth/le/DistanceMeasurementMethod.java @@ -73,7 +73,6 @@ public final class DistanceMeasurementMethod implements Parcelable { * * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi public static final int DISTANCE_MEASUREMENT_METHOD_CHANNEL_SOUNDING = 2; diff --git a/framework/java/android/bluetooth/le/DistanceMeasurementParams.java b/framework/java/android/bluetooth/le/DistanceMeasurementParams.java index f3116ed95a..04b3febe55 100644 --- a/framework/java/android/bluetooth/le/DistanceMeasurementParams.java +++ b/framework/java/android/bluetooth/le/DistanceMeasurementParams.java @@ -16,7 +16,6 @@ package android.bluetooth.le; -import android.annotation.FlaggedApi; import android.annotation.IntDef; import android.annotation.IntRange; import android.annotation.NonNull; @@ -27,8 +26,6 @@ import android.bluetooth.le.DistanceMeasurementMethod.DistanceMeasurementMethodI 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; @@ -143,7 +140,6 @@ public final class DistanceMeasurementParams implements Parcelable { * * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi public @Nullable ChannelSoundingParams getChannelSoundingParams() { return mChannelSoundingParams; @@ -312,7 +308,6 @@ public final class DistanceMeasurementParams implements Parcelable { * @return the same Builder instance * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi public @NonNull Builder setChannelSoundingParams( @NonNull ChannelSoundingParams channelSoundingParams) { diff --git a/framework/java/android/bluetooth/le/DistanceMeasurementResult.java b/framework/java/android/bluetooth/le/DistanceMeasurementResult.java index 9fb3416a85..e69e895fba 100644 --- a/framework/java/android/bluetooth/le/DistanceMeasurementResult.java +++ b/framework/java/android/bluetooth/le/DistanceMeasurementResult.java @@ -64,7 +64,6 @@ public final class DistanceMeasurementResult implements Parcelable { * * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi public static final int NADM_ATTACK_IS_EXTREMELY_UNLIKELY = 0; @@ -73,7 +72,6 @@ public final class DistanceMeasurementResult implements Parcelable { * * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi public static final int NADM_ATTACK_IS_VERY_UNLIKELY = 1; @@ -82,7 +80,6 @@ public final class DistanceMeasurementResult implements Parcelable { * * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi public static final int NADM_ATTACK_IS_UNLIKELY = 2; @@ -91,7 +88,6 @@ public final class DistanceMeasurementResult implements Parcelable { * * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi public static final int NADM_ATTACK_IS_POSSIBLE = 3; @@ -100,7 +96,6 @@ public final class DistanceMeasurementResult implements Parcelable { * * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi public static final int NADM_ATTACK_IS_LIKELY = 4; @@ -109,7 +104,6 @@ public final class DistanceMeasurementResult implements Parcelable { * * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi public static final int NADM_ATTACK_IS_VERY_LIKELY = 5; @@ -118,7 +112,6 @@ public final class DistanceMeasurementResult implements Parcelable { * * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi public static final int NADM_ATTACK_IS_EXTREMELY_LIKELY = 6; @@ -127,7 +120,6 @@ public final class DistanceMeasurementResult implements Parcelable { * * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi public static final int NADM_UNKNOWN = 0xFF; @@ -269,7 +261,6 @@ public final class DistanceMeasurementResult implements Parcelable { * @return delay spread in meters in degrees or Double.NaN if not available * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi public double getDelaySpreadMeters() { return mDelaySpreadMeters; @@ -282,7 +273,6 @@ public final class DistanceMeasurementResult implements Parcelable { * @return confidence of estimated distance or Double.NaN if not available * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi @FloatRange(from = 0.0, to = 1.0) public double getConfidenceLevel() { @@ -295,7 +285,6 @@ public final class DistanceMeasurementResult implements Parcelable { * @return Nadm that represents the chance of being attacked for the measurement. * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi @Nadm public int getDetectedAttackLevel() { @@ -310,7 +299,6 @@ public final class DistanceMeasurementResult implements Parcelable { * object in meters/sec. * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi public double getVelocityMetersPerSecond() { return mVelocityMetersPerSecond; @@ -532,7 +520,6 @@ public final class DistanceMeasurementResult implements Parcelable { * @throws IllegalArgumentException if value is invalid * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi @NonNull public Builder setDelaySpreadMeters(double delaySpreadMeters) { @@ -551,7 +538,6 @@ public final class DistanceMeasurementResult implements Parcelable { * @throws IllegalArgumentException if value is invalid * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi @NonNull public Builder setConfidenceLevel( @@ -573,7 +559,6 @@ public final class DistanceMeasurementResult implements Parcelable { * @throws IllegalArgumentException if value is invalid * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi @NonNull public Builder setDetectedAttackLevel(@Nadm int detectedAttackLevel) { @@ -601,7 +586,6 @@ public final class DistanceMeasurementResult implements Parcelable { * @param velocityMetersPerSecond estimated velocity in meters/sec. * @hide */ - @FlaggedApi(Flags.FLAG_CHANNEL_SOUNDING) @SystemApi @NonNull public Builder setVelocityMetersPerSecond(double velocityMetersPerSecond) { diff --git a/framework/tests/bumble/src/android/bluetooth/RfcommTest.kt b/framework/tests/bumble/src/android/bluetooth/RfcommTest.kt index 404847df68..9a55a02242 100644 --- a/framework/tests/bumble/src/android/bluetooth/RfcommTest.kt +++ b/framework/tests/bumble/src/android/bluetooth/RfcommTest.kt @@ -19,15 +19,22 @@ import android.Manifest import android.annotation.SuppressLint import android.bluetooth.test_utils.EnableBluetoothRule 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 android.util.Log import androidx.test.core.app.ApplicationProvider 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 com.google.common.truth.Truth import com.google.protobuf.ByteString +import java.io.IOException import java.time.Duration import java.util.UUID import java.util.concurrent.TimeUnit +import kotlin.concurrent.thread import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import org.junit.After @@ -42,7 +49,6 @@ import org.mockito.kotlin.timeout import org.mockito.kotlin.verify import pandora.RfcommProto import pandora.RfcommProto.ServerId -import pandora.RfcommProto.StartServerRequest @SuppressLint("MissingPermission") @RunWith(AndroidJUnit4::class) @@ -52,9 +58,13 @@ class RfcommTest { private val mManager = mContext.getSystemService(BluetoothManager::class.java) private val mAdapter = mManager!!.adapter - // Gives shell permissions during the test. @Rule(order = 0) @JvmField + val mCheckFlagsRule: CheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule() + + // Gives shell permissions during the test. + @Rule(order = 1) + @JvmField val mPermissionsRule = AdoptShellPermissionsRule( InstrumentationRegistry.getInstrumentation().getUiAutomation(), @@ -64,15 +74,21 @@ class RfcommTest { ) // Set up a Bumble Pandora device for the duration of the test. - @Rule(order = 1) @JvmField val mBumble = PandoraDevice() + @Rule(order = 2) @JvmField val mBumble = PandoraDevice() - @Rule(order = 2) @JvmField val enableBluetoothRule = EnableBluetoothRule(false, true) + @Rule(order = 3) @JvmField val enableBluetoothRule = EnableBluetoothRule(false, true) private lateinit var mRemoteDevice: BluetoothDevice private lateinit var host: Host private var mConnectionCounter = 1 private var mProfileServiceListener = mock<BluetoothProfile.ServiceListener>() + @OptIn(ExperimentalStdlibApi::class) + private val bdAddrFormat = HexFormat { bytes { byteSeparator = ":" } } + @OptIn(ExperimentalStdlibApi::class) + private val mLocalAddress: ByteString = + ByteString.copyFrom("DA:4C:10:DE:17:00".hexToByteArray(bdAddrFormat)) + /* Setup: 1. Initialize host and mRemoteDevice @@ -381,6 +397,37 @@ class RfcommTest { } } + /* + Test Steps: + 1. Create listening socket and connect + 2. Disconnect RFCOMM from remote device + */ + @RequiresFlagsEnabled(Flags.FLAG_TRIGGER_SEC_PROC_ON_INC_ACCESS_REQ) + @Test + fun serverSecureConnectThenRemoteDisconnect() { + // connect + val (serverSock, connection) = connectRemoteToListeningSocket() + val disconnectRequest = + RfcommProto.DisconnectionRequest.newBuilder().setConnection(connection).build() + // disconnect from remote + mBumble.rfcommBlocking().disconnect(disconnectRequest) + Truth.assertThat(serverSock.channel).isEqualTo(-1) // ensure disconnected at RFCOMM Layer + } + + /* + Test Steps: + 1. Create listening socket and connect + 2. Disconnect RFCOMM from local device + */ + @RequiresFlagsEnabled(Flags.FLAG_TRIGGER_SEC_PROC_ON_INC_ACCESS_REQ) + @Test + fun serverSecureConnectThenLocalDisconnect() { + // connect + val (serverSock, _) = connectRemoteToListeningSocket() + serverSock.close() + Truth.assertThat(serverSock.channel).isEqualTo(-1) // ensure disconnected at RFCOMM Layer + } + private fun createConnectAcceptSocket( isSecure: Boolean, server: ServerId, @@ -428,7 +475,8 @@ class RfcommTest { uuid: String = TEST_UUID, block: (ServerId) -> Unit, ) { - val request = StartServerRequest.newBuilder().setName(name).setUuid(uuid).build() + val request = + RfcommProto.StartServerRequest.newBuilder().setName(name).setUuid(uuid).build() val response = mBumble.rfcommBlocking().startServer(request) try { @@ -443,6 +491,33 @@ class RfcommTest { } } + private fun connectRemoteToListeningSocket( + name: String = TEST_SERVER_NAME, + uuid: String = TEST_UUID, + ): Pair<BluetoothServerSocket, RfcommProto.RfcommConnection> { + var connection: RfcommProto.RfcommConnection? = null + val connectRequest = + RfcommProto.ConnectionRequest.newBuilder() + .setAddress(mLocalAddress) + .setUuid(uuid) + .build() + val t = thread { + val connectResponse = mBumble.rfcommBlocking().connectToServer(connectRequest) + connection = connectResponse.connection + } + val socket = mAdapter.listenUsingRfcommWithServiceRecord(name, UUID.fromString(uuid)) + + try { + socket.accept(3000) // 3 second timeout + } catch (e: IOException) { + Log.e(TAG, "Unexpected IOException: $e") + } + t.join() + Truth.assertThat(connection).isNotNull() + + return Pair(socket, connection!!) + } + private fun getProfileProxy(context: Context, profile: Int): BluetoothProfile { mAdapter.getProfileProxy(context, mProfileServiceListener, profile) val proxyCaptor = argumentCaptor<BluetoothProfile>() diff --git a/pandora/server/bumble_experimental/rfcomm.py b/pandora/server/bumble_experimental/rfcomm.py index aa59566cf9..2f7c05ed4c 100644 --- a/pandora/server/bumble_experimental/rfcomm.py +++ b/pandora/server/bumble_experimental/rfcomm.py @@ -17,10 +17,13 @@ from typing import Dict, Optional from bumble import core from bumble.device import Device +from bumble.hci import Address from bumble.rfcomm import ( - Server, - make_service_sdp_records, + Client, DLC, + make_service_sdp_records, + find_rfcomm_channel_with_uuid, + Server, ) from bumble.pandora import utils import grpc @@ -30,6 +33,8 @@ from pandora_experimental.rfcomm_pb2 import ( AcceptConnectionResponse, ConnectionRequest, ConnectionResponse, + DisconnectionRequest, + DisconnectionResponse, RfcommConnection, RxRequest, RxResponse, @@ -59,9 +64,12 @@ class RFCOMMService(RFCOMMServicer): class Connection: - def __init__(self, dlc): + client: Optional[Client] + + def __init__(self, dlc, client=None): self.dlc = dlc self.data_queue = asyncio.Queue() + self.client = client class ServerPort: @@ -84,6 +92,27 @@ class RFCOMMService(RFCOMMServicer): self.saved_dlc = dlc @utils.rpc + async def ConnectToServer(self, request: ConnectionRequest, context: grpc.ServicerContext) -> ConnectionResponse: + logging.info(f"ConnectToServer") + address = Address(address=bytes(reversed(request.address)), address_type=Address.PUBLIC_DEVICE_ADDRESS) + acl_connection = self.device.find_connection_by_bd_addr(address, transport=0) # BR/EDR + if acl_connection is None: + acl_connection = await self.device.connect(address, transport=0) # BR/EDR transport + + channel = await find_rfcomm_channel_with_uuid(acl_connection, request.uuid) + + client = Client(acl_connection) + mux = await client.start() + assert mux is not None + + dlc = await mux.open_dlc(channel) + id = self.next_conn_id + self.next_conn_id += 1 + self.connections[id] = self.Connection(dlc=dlc, client=client) + self.connections[id].dlc.sink = self.connections[id].data_queue.put_nowait + return ConnectionResponse(connection=RfcommConnection(id=id)) + + @utils.rpc async def StartServer(self, request: StartServerRequest, context: grpc.ServicerContext) -> StartServerResponse: uuid = core.UUID(request.uuid) logging.info(f"StartServer {uuid}") @@ -119,6 +148,16 @@ class RFCOMMService(RFCOMMServicer): return AcceptConnectionResponse(connection=RfcommConnection(id=id)) @utils.rpc + async def Disconnect(self, request: DisconnectionRequest, context: grpc.ServicerContext) -> DisconnectionResponse: + logging.info(f"Disconnect") + rfcomm_connection = self.connections[request.connection.id] + assert rfcomm_connection is not None + if rfcomm_connection.client is not None: + await rfcomm_connection.client.shutdown() + del rfcomm_connection + return DisconnectionResponse() + + @utils.rpc async def StopServer(self, request: StopServerRequest, context: grpc.ServicerContext) -> StopServerResponse: logging.info(f"StopServer") assert self.server_ports[request.server.id] is not None diff --git a/sysprop/Android.bp b/sysprop/Android.bp index 1b72eb4cb7..e9d820b2f1 100644 --- a/sysprop/Android.bp +++ b/sysprop/Android.bp @@ -12,6 +12,7 @@ sysprop_library { "bta.sysprop", "device_id.sysprop", "gap.sysprop", + "hardware.sysprop", "hfp.sysprop", ], property_owner: "Platform", diff --git a/sysprop/BUILD.gn b/sysprop/BUILD.gn index 407b7a88fc..9cdbf48530 100644 --- a/sysprop/BUILD.gn +++ b/sysprop/BUILD.gn @@ -8,6 +8,7 @@ sysprop("libcom.android.sysprop.bluetooth") { "bta.sysprop", "device_id.sysprop", "gap.sysprop", + "hardware.sysprop", "hfp.sysprop", ] deps = [ "//bt/floss/android-base:android-base" ] diff --git a/sysprop/exported_include/android_bluetooth_sysprop.h b/sysprop/exported_include/android_bluetooth_sysprop.h index 8d5122d8e2..24053123ac 100644 --- a/sysprop/exported_include/android_bluetooth_sysprop.h +++ b/sysprop/exported_include/android_bluetooth_sysprop.h @@ -22,4 +22,5 @@ #include <bta.sysprop.h> #include <device_id.sysprop.h> #include <gap.sysprop.h> +#include <hardware.sysprop.h> #include <hfp.sysprop.h> diff --git a/sysprop/hardware.sysprop b/sysprop/hardware.sysprop new file mode 100644 index 0000000000..07c09134bb --- /dev/null +++ b/sysprop/hardware.sysprop @@ -0,0 +1,10 @@ +module: "android.sysprop.bluetooth.hardware" +owner: Platform + +prop { + api_name: "wakeup_supported" + type: Boolean + scope: Internal + access: Readonly + prop_name: "bluetooth.hardware.wakeup_supported" +} diff --git a/system/BUILD.gn b/system/BUILD.gn index 62ced34597..783428604a 100644 --- a/system/BUILD.gn +++ b/system/BUILD.gn @@ -78,7 +78,6 @@ config("target_defaults") { "//bt/flags/exported_include", "//bt/sysprop/exported_include", "//bt/system/linux_include", - "//bt/system/types", "//bt/system/include", "//bt/system/gd", diff --git a/system/audio_bluetooth_hw/device_port_proxy_hidl.h b/system/audio_bluetooth_hw/device_port_proxy_hidl.h index 640ff95fb1..edc3e2a3ed 100644 --- a/system/audio_bluetooth_hw/device_port_proxy_hidl.h +++ b/system/audio_bluetooth_hw/device_port_proxy_hidl.h @@ -115,4 +115,4 @@ public: } // namespace hidl } // namespace audio } // namespace bluetooth -} // namespace android
\ No newline at end of file +} // namespace android diff --git a/system/audio_hal_interface/Android.bp b/system/audio_hal_interface/Android.bp index 987b859214..f485de80aa 100644 --- a/system/audio_hal_interface/Android.bp +++ b/system/audio_hal_interface/Android.bp @@ -187,6 +187,7 @@ cc_test { "libbluetooth_log", "libbt-common", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libflagtest", "libfmq", "libgmock", @@ -246,6 +247,7 @@ cc_defaults { "libbtif", "libbtif-core", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libcutils", "libevent", "libg722codec", diff --git a/system/audio_hal_interface/a2dp_encoding.h b/system/audio_hal_interface/a2dp_encoding.h index 84e31a82c6..5c8e68cc2f 100644 --- a/system/audio_hal_interface/a2dp_encoding.h +++ b/system/audio_hal_interface/a2dp_encoding.h @@ -55,6 +55,7 @@ public: return BluetoothAudioStatus::FAILURE; } virtual BluetoothAudioStatus SuspendStream() const { return BluetoothAudioStatus::FAILURE; } + virtual BluetoothAudioStatus StopStream() const { return SuspendStream(); } virtual BluetoothAudioStatus SetLatencyMode(bool /*low_latency*/) const { return BluetoothAudioStatus::FAILURE; } diff --git a/system/audio_hal_interface/a2dp_encoding_host.cc b/system/audio_hal_interface/a2dp_encoding_host.cc index 9bd8149535..65c5eba23f 100644 --- a/system/audio_hal_interface/a2dp_encoding_host.cc +++ b/system/audio_hal_interface/a2dp_encoding_host.cc @@ -232,6 +232,10 @@ static BluetoothAudioPort const* bluetooth_audio_port = &null_audio_port; // Initialize BluetoothAudio HAL: openProvider bool init(bluetooth::common::MessageLoopThread* /*message_loop*/, BluetoothAudioPort const* audio_port, bool /*offload_enabled*/) { + if (a2dp_uipc != nullptr) { + log::warn("Re-init-ing UIPC that is already running"); + cleanup(); + } a2dp_uipc = UIPC_Init(); total_bytes_read_ = 0; data_position_ = {}; diff --git a/system/audio_hal_interface/aidl/a2dp/a2dp_encoding_aidl.cc b/system/audio_hal_interface/aidl/a2dp/a2dp_encoding_aidl.cc index f99fa9ba28..cde3eedd39 100644 --- a/system/audio_hal_interface/aidl/a2dp/a2dp_encoding_aidl.cc +++ b/system/audio_hal_interface/aidl/a2dp/a2dp_encoding_aidl.cc @@ -185,7 +185,7 @@ BluetoothAudioStatus A2dpTransport::SuspendRequest() { void A2dpTransport::StopRequest() { log::info(""); - auto status = bluetooth_audio_port_->SuspendStream(); + auto status = bluetooth_audio_port_->StopStream(); a2dp_pending_cmd_ = status == BluetoothAudioStatus::PENDING ? A2DP_CTRL_CMD_STOP : A2DP_CTRL_CMD_NONE; } diff --git a/system/audio_hal_interface/fuzzer/Android.bp b/system/audio_hal_interface/fuzzer/Android.bp index 93a734b02f..9a32f910e3 100644 --- a/system/audio_hal_interface/fuzzer/Android.bp +++ b/system/audio_hal_interface/fuzzer/Android.bp @@ -83,6 +83,7 @@ cc_defaults { "libbtif", "libbtif-core", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libcutils", "libevent", "libexpresslog", diff --git a/system/audio_hearing_aid_hw/Android.bp b/system/audio_hearing_aid_hw/Android.bp index 19694cac77..e8e83e86c8 100644 --- a/system/audio_hearing_aid_hw/Android.bp +++ b/system/audio_hearing_aid_hw/Android.bp @@ -15,7 +15,6 @@ cc_defaults { "packages/modules/Bluetooth/system", "packages/modules/Bluetooth/system/gd", "packages/modules/Bluetooth/system/include", - "packages/modules/Bluetooth/system/types", ], } @@ -59,6 +58,7 @@ cc_test { static_libs: [ "audio.hearing_aid.default", "libbluetooth_log", + "libcom.android.sysprop.bluetooth.wrapped", "libosi", ], min_sdk_version: "29", diff --git a/system/audio_hearing_aid_hw/test/audio_hearing_aid_hw_test.cc b/system/audio_hearing_aid_hw/test/audio_hearing_aid_hw_test.cc index 69bcfbc641..95f3dc6288 100644 --- a/system/audio_hearing_aid_hw/test/audio_hearing_aid_hw_test.cc +++ b/system/audio_hearing_aid_hw/test/audio_hearing_aid_hw_test.cc @@ -111,13 +111,13 @@ TEST_F(AudioA2dpHwTest, test_compute_buffer_size) { } uint32_t sample_rate = codec_sample_rate2value(codec_sample_rate); - EXPECT_TRUE(sample_rate != 0); + EXPECT_NE(0u, sample_rate); uint32_t bits_per_sample = codec_bits_per_sample2value(codec_bits_per_sample); - EXPECT_TRUE(bits_per_sample != 0); + EXPECT_NE(0u, bits_per_sample); uint32_t number_of_channels = codec_channel_mode2value(codec_channel_mode); - EXPECT_TRUE(number_of_channels != 0); + EXPECT_NE(0u, number_of_channels); const uint64_t time_period_ms = 20; // TODO: Must be a parameter size_t expected_buffer_size = (time_period_ms * AUDIO_STREAM_OUTPUT_BUFFER_PERIODS * diff --git a/system/bta/Android.bp b/system/bta/Android.bp index 812c482fcb..f99f437bd4 100644 --- a/system/bta/Android.bp +++ b/system/bta/Android.bp @@ -447,6 +447,7 @@ cc_test { "libbt-platform-protos-lite", "libbtcore", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libgmock", "libosi", "libstatslog_bt", @@ -563,6 +564,7 @@ cc_test { "libbluetooth_log", "libbt-common", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libcutils", "libgmock", "libosi", @@ -610,6 +612,7 @@ cc_test { "libbluetooth_log", "libbt-common", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libgmock", "libosi", ], @@ -828,6 +831,7 @@ cc_test { "libbt-common", "libbt-platform-protos-lite", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "libflatbuffers-cpp", "libgmock", @@ -938,6 +942,7 @@ cc_test { "libbt-common", "libbt-platform-protos-lite", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "libflatbuffers-cpp", "libgmock", @@ -1027,6 +1032,7 @@ cc_test { "libbt-common", "libbt-platform-protos-lite", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "libflagtest", "libflatbuffers-cpp", diff --git a/system/bta/ag/bta_ag_at.cc b/system/bta/ag/bta_ag_at.cc index a42017c29b..8b1e3c6792 100644 --- a/system/bta/ag/bta_ag_at.cc +++ b/system/bta/ag/bta_ag_at.cc @@ -110,14 +110,12 @@ static void bta_ag_process_at(tBTA_AG_AT_CB* p_cb, char* p_end) { /* if no argument */ if (p_arg[0] == 0) { arg_type = BTA_AG_AT_NONE; - } - /* else if arg is '?' and it is last character */ - else if (p_arg[0] == '?' && p_arg[1] == 0) { + } else if (p_arg[0] == '?' && p_arg[1] == 0) { + /* else if arg is '?' and it is last character */ /* we have a read */ arg_type = BTA_AG_AT_READ; - } - /* else if arg is '=' */ - else if (p_arg[0] == '=' && p_arg[1] != 0) { + } else if (p_arg[0] == '=' && p_arg[1] != 0) { + /* else if arg is '=' */ if (p_arg[1] == '?' && p_arg[2] == 0) { /* we have a test */ arg_type = BTA_AG_AT_TEST; diff --git a/system/bta/ag/bta_ag_cmd.cc b/system/bta/ag/bta_ag_cmd.cc index 75e9bfb22a..458608021e 100644 --- a/system/bta/ag/bta_ag_cmd.cc +++ b/system/bta/ag/bta_ag_cmd.cc @@ -942,10 +942,9 @@ void bta_ag_at_hfp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, cha event = BTA_AG_ENABLE_EVT; bta_ag_send_error(p_scb, BTA_AG_ERR_OP_NOT_SUPPORTED); } - } - /* If dial cmd, make sure string contains only dial digits - ** Dial digits are 0-9, A-C, *, #, + */ - else { + } else { + /* If dial cmd, make sure string contains only dial digits + ** Dial digits are 0-9, A-C, *, #, + */ /* Some car kits may add some unwanted space characters in the ** input string. This workaround will trim the unwanted chars. */ remove_spaces(val.str); diff --git a/system/bta/ag/bta_ag_sco.cc b/system/bta/ag/bta_ag_sco.cc index c9b30693cd..dd14e86779 100644 --- a/system/bta/ag/bta_ag_sco.cc +++ b/system/bta/ag/bta_ag_sco.cc @@ -174,9 +174,8 @@ static void bta_ag_sco_conn_cback(uint16_t sco_idx) { /* match callback to scb; first check current sco scb */ if (bta_ag_cb.sco.p_curr_scb != nullptr && bta_ag_cb.sco.p_curr_scb->in_use) { handle = bta_ag_scb_to_idx(bta_ag_cb.sco.p_curr_scb); - } - /* then check for scb connected to this peer */ - else { + } else { + /* then check for scb connected to this peer */ /* Check if SLC is up */ handle = bta_ag_idx_by_bdaddr(BTM_ReadScoBdAddr(sco_idx)); p_scb = bta_ag_scb_by_idx(handle); diff --git a/system/bta/ag/bta_ag_sdp.cc b/system/bta/ag/bta_ag_sdp.cc index 038b3fffdf..3d0420b77b 100644 --- a/system/bta/ag/bta_ag_sdp.cc +++ b/system/bta/ag/bta_ag_sdp.cc @@ -466,17 +466,15 @@ void bta_ag_do_disc(tBTA_AG_SCB* p_scb, tBTA_SERVICE_MASK service) { attr_list[3] = ATTR_ID_SUPPORTED_FEATURES; num_attr = 4; uuid_list[0] = Uuid::From16Bit(UUID_SERVCLASS_HF_HANDSFREE); - } - /* HFP acceptor; get features */ - else if (service & BTA_HFP_SERVICE_MASK && p_scb->role == BTA_AG_ACP) { + } else if (service & BTA_HFP_SERVICE_MASK && p_scb->role == BTA_AG_ACP) { + /* HFP acceptor; get features */ attr_list[0] = ATTR_ID_SERVICE_CLASS_ID_LIST; attr_list[1] = ATTR_ID_BT_PROFILE_DESC_LIST; attr_list[2] = ATTR_ID_SUPPORTED_FEATURES; num_attr = 3; uuid_list[0] = Uuid::From16Bit(UUID_SERVCLASS_HF_HANDSFREE); - } - /* HSP initiator; get proto list */ - else if (service & BTA_HSP_SERVICE_MASK && p_scb->role == BTA_AG_INT) { + } else if (service & BTA_HSP_SERVICE_MASK && p_scb->role == BTA_AG_INT) { + /* HSP initiator; get proto list */ attr_list[0] = ATTR_ID_SERVICE_CLASS_ID_LIST; attr_list[1] = ATTR_ID_PROTOCOL_DESC_LIST; attr_list[2] = ATTR_ID_BT_PROFILE_DESC_LIST; diff --git a/system/bta/aics/aics.cc b/system/bta/aics/aics.cc index 5b5c0886f3..338885a532 100644 --- a/system/bta/aics/aics.cc +++ b/system/bta/aics/aics.cc @@ -13,9 +13,10 @@ #define LOG_TAG "aics" -#include <aics/api.h> #include <bluetooth/log.h> +#include "aics/api.h" + namespace bluetooth::aics { bool isValidAudioInputMuteValue(uint8_t data) { @@ -29,4 +30,15 @@ Mute parseMuteField(uint8_t data) { return static_cast<Mute>(data); } +bool isValidAudioInputGainModeValue(uint8_t data) { + return data >= static_cast<uint8_t>(GainMode::MANUAL_ONLY) && + data <= static_cast<uint8_t>(GainMode::AUTOMATIC); +} + +GainMode parseGainModeField(uint8_t data) { + log::assert_that(isValidAudioInputGainModeValue(data), "Not a valid GainMode Value"); + + return static_cast<GainMode>(data); +} + } // namespace bluetooth::aics diff --git a/system/bta/aics/include/aics/api.h b/system/bta/aics/include/aics/api.h index aba825d37e..b81132e324 100644 --- a/system/bta/aics/include/aics/api.h +++ b/system/bta/aics/include/aics/api.h @@ -14,18 +14,28 @@ #pragma once #ifndef TARGET_FLOSS +#include <bluetooth/constants/aics/GainMode.h> #include <bluetooth/constants/aics/Mute.h> #endif +#include <bluetooth/log.h> + #include <cstdint> namespace bluetooth::aics { #ifndef TARGET_FLOSS using Mute = bluetooth::constants::aics::Mute; +using GainMode = bluetooth::constants::aics::GainMode; #else // TODO: b/376941621 Support the aidl generation in FLOSS -enum class Mute : int8_t { NOT_MUTED = 0, MUTED = 1, DISABLED = 2 }; +enum class Mute : uint8_t { NOT_MUTED = 0x00, MUTED = 0x01, DISABLED = 0x02 }; +enum class GainMode : uint8_t { + MANUAL_ONLY = 0x00, + AUTOMATIC_ONLY = 0x01, + MANUAL = 0x02, + AUTOMATIC = 0x03 +}; #endif /** Check if the data is a correct Mute value */ @@ -33,4 +43,17 @@ bool isValidAudioInputMuteValue(uint8_t data); /** Convert valid data into a Mute value. Abort if data is not valid */ Mute parseMuteField(uint8_t data); + +/** Check if the data is a correct GainMode value */ +bool isValidAudioInputGainModeValue(uint8_t data); + +/** Convert valid data into a Mute value. Abort if data is not valid */ +GainMode parseGainModeField(uint8_t data); } // namespace bluetooth::aics + +namespace fmt { +template <> +struct formatter<bluetooth::aics::Mute> : enum_formatter<bluetooth::aics::Mute> {}; +template <> +struct formatter<bluetooth::aics::GainMode> : enum_formatter<bluetooth::aics::GainMode> {}; +} // namespace fmt diff --git a/system/bta/av/bta_av_act.cc b/system/bta/av/bta_av_act.cc index a01920504d..5a59222a33 100644 --- a/system/bta/av/bta_av_act.cc +++ b/system/bta/av/bta_av_act.cc @@ -1015,10 +1015,9 @@ void bta_av_rc_msg(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { memcpy(&av.remote_cmd.hdr, &p_data->rc_msg.msg.hdr, sizeof(tAVRC_HDR)); av.remote_cmd.label = p_data->rc_msg.label; } - } - /* else if this is a pass thru response */ - /* id response type is not impl, we have to release label */ - else if (p_data->rc_msg.msg.hdr.ctype >= AVRC_RSP_NOT_IMPL) { + } else if (p_data->rc_msg.msg.hdr.ctype >= AVRC_RSP_NOT_IMPL) { + /* else if this is a pass thru response */ + /* id response type is not impl, we have to release label */ /* set up for callback */ evt = BTA_AV_REMOTE_RSP_EVT; av.remote_rsp.rc_id = p_data->rc_msg.msg.pass.op_id; @@ -1036,15 +1035,13 @@ void bta_av_rc_msg(tBTA_AV_CB* p_cb, tBTA_AV_DATA* p_data) { memcpy(av.remote_rsp.p_data, p_data->rc_msg.msg.pass.p_pass_data, p_data->rc_msg.msg.pass.pass_len); } - } - /* must be a bad ctype -> reject*/ - else { + } else { + /* must be a bad ctype -> reject*/ p_data->rc_msg.msg.hdr.ctype = AVRC_RSP_REJ; AVRC_PassRsp(p_data->rc_msg.handle, p_data->rc_msg.label, &p_data->rc_msg.msg.pass); } - } - /* else if this is a vendor specific command or response */ - else if (p_data->rc_msg.opcode == AVRC_OP_VENDOR) { + } else if (p_data->rc_msg.opcode == AVRC_OP_VENDOR) { + /* else if this is a vendor specific command or response */ /* set up for callback */ av.vendor_cmd.code = p_data->rc_msg.msg.hdr.ctype; av.vendor_cmd.company_id = p_vendor->company_id; diff --git a/system/bta/av/bta_av_int.h b/system/bta/av/bta_av_int.h index 4f9773344e..a7ed265798 100644 --- a/system/bta/av/bta_av_int.h +++ b/system/bta/av/bta_av_int.h @@ -531,9 +531,9 @@ public: * is set according to RFC 6416 */ uint8_t co_started; /* non-zero, if stream started from call-out perspective */ bool recfg_sup; /* true if the first attempt to reconfigure the stream was - successful, else False if command fails */ - bool suspend_sup; /* true if Suspend stream is supported, else false if - suspend command fails */ + successful, false if command fails */ + bool suspend_sup; /* true if Suspend stream is supported, false if suspend command + fails */ bool deregistering; /* true if deregistering */ bool sco_suspend; /* true if SUSPEND is issued automatically for SCO */ uint8_t coll_mask; /* Mask to check incoming and outgoing collision */ diff --git a/system/bta/csis/csis_client_test.cc b/system/bta/csis/csis_client_test.cc index fa61fa1c1f..42ee0abb36 100644 --- a/system/bta/csis/csis_client_test.cc +++ b/system/bta/csis/csis_client_test.cc @@ -841,8 +841,7 @@ TEST_F(CsisClientTest, test_get_group_id) { EXPECT_CALL(*callbacks, OnDeviceAvailable(test_address, _, _, _, _)); InjectConnectedEvent(test_address, 1); GetSearchCompleteEvent(1); - int group_id = CsisClient::Get()->GetGroupId(test_address); - ASSERT_TRUE(group_id == 1); + ASSERT_EQ(1, CsisClient::Get()->GetGroupId(test_address)); TestAppUnregister(); } diff --git a/system/bta/dm/bta_dm_device_search.cc b/system/bta/dm/bta_dm_device_search.cc index 76219c3fbb..c80f76396a 100644 --- a/system/bta/dm/bta_dm_device_search.cc +++ b/system/bta/dm/bta_dm_device_search.cc @@ -137,10 +137,8 @@ static void bta_dm_search_cancel() { BTM_CancelInquiry(); bta_dm_search_cancel_notify(); bta_dm_search_cmpl(); - } - /* If no Service Search going on then issue cancel remote name in case it is - active */ - else if (!bta_dm_search_cb.name_discover_done) { + } else if (!bta_dm_search_cb.name_discover_done) { + /* If no Service Search going on then issue cancel remote name in case it is active */ if (get_stack_rnr_interface().BTM_CancelRemoteDeviceName() != tBTM_STATUS::BTM_CMD_STARTED) { log::warn("Unable to cancel RNR"); } diff --git a/system/bta/dm/bta_dm_disc_sdp.cc b/system/bta/dm/bta_dm_disc_sdp.cc index 8bdbc9ee8a..f4b1b13728 100644 --- a/system/bta/dm/bta_dm_disc_sdp.cc +++ b/system/bta/dm/bta_dm_disc_sdp.cc @@ -217,7 +217,6 @@ void bta_dm_sdp_result(tSDP_STATUS sdp_result, tBTA_DM_SDP_STATE* sdp_state) { } else { /* regular one service per search or PNP search */ break; } - } while (sdp_state->service_index <= BTA_MAX_SERVICE_ID); log::verbose("services_found = {:04x}", sdp_state->services_found); diff --git a/system/bta/dm/bta_dm_int.h b/system/bta/dm/bta_dm_int.h index fa382d11d8..d7757557dc 100644 --- a/system/bta/dm/bta_dm_int.h +++ b/system/bta/dm/bta_dm_int.h @@ -186,7 +186,6 @@ typedef struct { app_id, bta_sys_conn_status_text(state).c_str(), new_request ? "true" : "false"); } - } tBTA_DM_SRVCS; #ifndef BTA_DM_NUM_CONN_SRVS @@ -196,7 +195,6 @@ typedef struct { typedef struct { uint8_t count; tBTA_DM_SRVCS conn_srvc[BTA_DM_NUM_CONN_SRVS]; - } tBTA_DM_CONNECTED_SRVCS; typedef struct { @@ -257,7 +255,6 @@ typedef struct { uint16_t page_timeout; /* timeout for page in slots */ bool avoid_scatter; /* true to avoid scatternet when av is streaming (be the central) */ - } tBTA_DM_CFG; extern const uint32_t bta_service_id_to_btm_srv_id_lkup_tbl[]; @@ -266,7 +263,6 @@ typedef struct { uint8_t id; uint8_t app_id; uint8_t cfg; - } tBTA_DM_RM; extern const tBTA_DM_CFG* p_bta_dm_cfg; @@ -276,20 +272,17 @@ typedef struct { uint8_t id; uint8_t app_id; uint8_t spec_idx; /* index of spec table to use */ - } tBTA_DM_PM_CFG; typedef struct { tBTA_DM_PM_ACTION power_mode; uint16_t timeout; - } tBTA_DM_PM_ACTN; typedef struct { uint8_t allow_mask; /* mask of sniff/hold/park modes to allow */ uint8_t ssr; /* set SSR on conn open/unpark */ tBTA_DM_PM_ACTN actn_tbl[BTA_DM_PM_NUM_EVTS][2]; - } tBTA_DM_PM_SPEC; typedef struct { diff --git a/system/bta/dm/bta_dm_pm.cc b/system/bta/dm/bta_dm_pm.cc index ca3bb38058..9c0b869d30 100644 --- a/system/bta/dm/bta_dm_pm.cc +++ b/system/bta/dm/bta_dm_pm.cc @@ -393,9 +393,8 @@ static void bta_dm_sniff_cback(uint8_t id, uint8_t app_id, const RawAddress& pee /* first check if the first preference is ok */ if (!(failed_pm & p_act0->power_mode)) { timeout_ms = p_act0->timeout; - } - /* if first preference has already failed, try second preference */ - else if (!(failed_pm & p_act1->power_mode)) { + } else if (!(failed_pm & p_act1->power_mode)) { + /* if first preference has already failed, try second preference */ timeout_ms = p_act1->timeout; } @@ -649,9 +648,8 @@ static void bta_dm_pm_set_mode(const RawAddress& peer_addr, tBTA_DM_PM_ACTION pm timeout_ms = p_act0->timeout; } } - } - /* if first preference has already failed, try second preference */ - else if (!(failed_pm & p_act1->power_mode)) { + } else if (!(failed_pm & p_act1->power_mode)) { + /* if first preference has already failed, try second preference */ pref_modes |= p_act1->power_mode; if (p_act1->power_mode > pm_action) { diff --git a/system/bta/gatt/bta_gattc_act.cc b/system/bta/gatt/bta_gattc_act.cc index 1374cca1c5..c1a8e956ad 100644 --- a/system/bta/gatt/bta_gattc_act.cc +++ b/system/bta/gatt/bta_gattc_act.cc @@ -634,9 +634,7 @@ void bta_gattc_conn(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* p_data) { } else { /* cache is building */ p_clcb->state = BTA_GATTC_DISCOVER_ST; } - } - - else { + } else { /* a pending service handle change indication */ if (p_clcb->p_srcb->srvc_hdl_chg) { p_clcb->p_srcb->srvc_hdl_chg = false; @@ -932,9 +930,8 @@ void bta_gattc_start_discover(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* /* } bta_gattc_continue_with_version_and_cache_known(p_clcb, cache_support, is_svc_chg); - } - /* pending operation, wait until it finishes */ - else { + } else { + /* pending operation, wait until it finishes */ p_clcb->auto_update = BTA_GATTC_DISC_WAITING; if (p_clcb->p_srcb->state == BTA_GATTC_SERV_IDLE) { @@ -1021,9 +1018,8 @@ void bta_gattc_disc_cmpl(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_DATA* /* p_da /* start discovery again */ p_clcb->auto_update = BTA_GATTC_REQ_WAITING; bta_gattc_sm_execute(p_clcb, BTA_GATTC_INT_DISCOVER_EVT, NULL); - } - /* get any queued command to proceed */ - else if (p_q_cmd != NULL) { + } else if (p_q_cmd != NULL) { + /* get any queued command to proceed */ p_clcb->p_q_cmd = NULL; /* execute pending operation of link block still present */ if (bluetooth::stack::l2cap::get_interface().L2CA_IsLinkEstablished(p_clcb->p_srcb->server_bda, @@ -1713,9 +1709,8 @@ static void bta_gattc_process_indicate(tCONN_ID conn_id, tGATTC_OPTYPE op, if (p_clcb != NULL) { bta_gattc_proc_other_indication(p_clcb, op, p_data, ¬ify); } - } - /* no one intersted and need ack? */ - else if (op == GATTC_OPTYPE_INDICATION) { + } else if (op == GATTC_OPTYPE_INDICATION) { + /* no one interested and need ack? */ log::verbose("no one interested, ack now"); if (GATTC_SendHandleValueConfirm(conn_id, p_data->cid) != GATT_SUCCESS) { log::warn("Unable to send GATT client handle value confirmation conn_id:{} cid:{}", conn_id, diff --git a/system/bta/gatt/bta_gattc_main.cc b/system/bta/gatt/bta_gattc_main.cc index 2912879e77..b4afcd542a 100644 --- a/system/bta/gatt/bta_gattc_main.cc +++ b/system/bta/gatt/bta_gattc_main.cc @@ -126,7 +126,6 @@ static const uint8_t bta_gattc_st_idle[][BTA_GATTC_NUM_COLS] = { /* BTA_GATTC_DISCOVER_CMPL_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_IDLE_ST}, /* BTA_GATTC_OP_CMPL_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_IDLE_ST}, /* BTA_GATTC_INT_DISCONN_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_IDLE_ST}, - }; /* state table for wait for open state */ @@ -153,7 +152,6 @@ static const uint8_t bta_gattc_st_w4_conn[][BTA_GATTC_NUM_COLS] = { /* BTA_GATTC_DISCOVER_CMPL_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_W4_CONN_ST}, /* BTA_GATTC_OP_CMPL_EVT */ {BTA_GATTC_IGNORE, BTA_GATTC_W4_CONN_ST}, /* BTA_GATTC_INT_DISCONN_EVT */ {BTA_GATTC_OPEN_FAIL, BTA_GATTC_IDLE_ST}, - }; /* state table for open state */ @@ -181,7 +179,6 @@ static const uint8_t bta_gattc_st_connected[][BTA_GATTC_NUM_COLS] = { /* BTA_GATTC_OP_CMPL_EVT */ {BTA_GATTC_OP_CMPL, BTA_GATTC_CONN_ST}, /* BTA_GATTC_INT_DISCONN_EVT */ {BTA_GATTC_CLOSE, BTA_GATTC_IDLE_ST}, - }; /* state table for discover state */ @@ -209,7 +206,6 @@ static const uint8_t bta_gattc_st_discover[][BTA_GATTC_NUM_COLS] = { /* BTA_GATTC_OP_CMPL_EVT */ {BTA_GATTC_OP_CMPL_DURING_DISCOVERY, BTA_GATTC_DISCOVER_ST}, /* BTA_GATTC_INT_DISCONN_EVT */ {BTA_GATTC_CLOSE, BTA_GATTC_IDLE_ST}, - }; /* type for state table */ diff --git a/system/bta/has/has_client.cc b/system/bta/has/has_client.cc index 15f69ab76a..915472dd85 100644 --- a/system/bta/has/has_client.cc +++ b/system/bta/has/has_client.cc @@ -429,7 +429,7 @@ public: ClearDeviceInformationAndStartSearch(device); } else { log::error("Devices {}: Control point not usable. Disconnecting!", device->addr); - BTA_GATTC_Close(device->conn_id); + CleanAndDisconnectByConnId(conn_id); } } @@ -475,7 +475,7 @@ public: ClearDeviceInformationAndStartSearch(device); } else { log::error("Devices {}: Control point not usable. Disconnecting!", device->addr); - BTA_GATTC_Close(device->conn_id); + CleanAndDisconnectByConnId(conn_id); } } @@ -1137,7 +1137,7 @@ private: /* Both of these CCC are mandatory */ if (enabling_ntf && (status != GATT_SUCCESS)) { log::error("Failed to register for notifications on handle=0x{:x}", handle); - BTA_GATTC_Close(conn_id); + CleanAndDisconnectByConnId(conn_id); return; } } @@ -1189,20 +1189,22 @@ private: return; } + tCONN_ID conn_id = device->conn_id; + if (status != GATT_SUCCESS) { if (status == GATT_DATABASE_OUT_OF_SYNC) { log::info("Database out of sync for {}", device->addr); ClearDeviceInformationAndStartSearch(device); } else { log::error("Could not read characteristic at handle=0x{:04x}", handle); - BTA_GATTC_Close(device->conn_id); + CleanAndDisconnectByConnId(conn_id); } return; } if (len != 1) { log::error("Invalid features value length={} at handle=0x{:x}", len, handle); - BTA_GATTC_Close(device->conn_id); + CleanAndDisconnectByConnId(conn_id); return; } @@ -1565,9 +1567,11 @@ private: void OnHasCtpValueNotification(HasDevice* device, uint16_t len, const uint8_t* value) { auto ntf_opt = HasCtpNtf::FromCharacteristicValue(len, value); + tCONN_ID conn_id = device->conn_id; + if (!ntf_opt.has_value()) { log::error("Unhandled notification for device: {}", *device); - BTA_GATTC_Close(device->conn_id); + CleanAndDisconnectByConnId(conn_id); return; } @@ -1591,19 +1595,22 @@ private: return; } + tCONN_ID conn_id = device->conn_id; + if (status != GATT_SUCCESS) { if (status == GATT_DATABASE_OUT_OF_SYNC) { log::info("Database out of sync for {}", device->addr); ClearDeviceInformationAndStartSearch(device); } else { log::error("Could not read characteristic at handle=0x{:04x}", handle); - BTA_GATTC_Close(device->conn_id); + CleanAndDisconnectByConnId(conn_id); + return; } } if (len != 1) { log::error("Invalid preset value length={} at handle=0x{:x}", len, handle); - BTA_GATTC_Close(device->conn_id); + CleanAndDisconnectByConnId(conn_id); return; } @@ -1717,6 +1724,16 @@ private: device.ConnectionCleanUp(); } + void CleanAndDisconnectByConnId(tCONN_ID conn_id) { + auto device_iter = + std::find_if(devices_.begin(), devices_.end(), HasDevice::MatchConnId(conn_id)); + if (device_iter != devices_.end()) { + DoDisconnectCleanUp(*device_iter); + devices_.erase(device_iter); + } + BTA_GATTC_Close(conn_id); + } + /* These below are all GATT service discovery, validation, cache & storage */ bool CacheAttributeHandles(const gatt::Service& service, HasDevice* device) { log::debug("device={}", device->addr); diff --git a/system/bta/has/has_client_test.cc b/system/bta/has/has_client_test.cc index b0656e41b5..322c387153 100644 --- a/system/bta/has/has_client_test.cc +++ b/system/bta/has/has_client_test.cc @@ -1544,7 +1544,7 @@ TEST_F(HasClientTest, test_discovery_basic_has_no_opt_ntf) { /* Verify presets */ uint16_t conn_id = GetTestConnId(test_address); - ASSERT_NE(preset_details.size(), 0u); + ASSERT_NE(0u, preset_details.size()); ASSERT_EQ(current_peer_presets_.at(conn_id).size(), preset_details.size()); for (auto const& preset : current_peer_presets_.at(conn_id)) { @@ -1602,6 +1602,41 @@ TEST_F(HasClientTest, test_discovery_has_broken_no_active_preset_ntf) { TestConnect(test_address); } +TEST_F(HasClientTest, test_cp_not_usable_read_all_presets) { + osi_property_set_bool("persist.bluetooth.has.always_use_preset_cache", false); + + const RawAddress test_address = GetTestAddress(1); + std::set<HasPreset, HasPreset::ComparatorDesc> has_presets = {{ + HasPreset(1, HasPreset::kPropertyAvailable, "Universal"), + HasPreset(2, HasPreset::kPropertyAvailable | HasPreset::kPropertyWritable, "Preset2"), + }}; + + SetSampleDatabaseHasPresetsNtf(test_address, + bluetooth::has::kFeatureBitHearingAidTypeBanded | + bluetooth::has::kFeatureBitWritablePresets | + bluetooth::has::kFeatureBitDynamicPresets, + has_presets); + + ON_CALL(gatt_queue, ReadCharacteristic(_, HasDbBuilder::kActivePresetIndexValHdl, _, _)) + .WillByDefault(Invoke([&](uint16_t conn_id, uint16_t handle, GATT_READ_OP_CB cb, + void* cb_data) -> void { + std::vector<uint8_t> value; + + tGATT_STATUS status = GATT_ERROR; + if (cb) { + cb(conn_id, status, handle, value.size(), value.data(), cb_data); + } + })); + + EXPECT_CALL(*callbacks, + OnDeviceAvailable(test_address, bluetooth::has::kFeatureBitHearingAidTypeBanded | + bluetooth::has::kFeatureBitWritablePresets | + bluetooth::has::kFeatureBitDynamicPresets)); + EXPECT_CALL(gatt_queue, Clean(1)).Times(1); + + TestConnect(test_address); +} + TEST_F(HasClientTest, test_discovery_has_features_ntf) { const RawAddress test_address = GetTestAddress(1); auto test_conn_id = GetTestConnId(test_address); @@ -1736,7 +1771,7 @@ TEST_F(HasClientTest, test_duplicate_presets) { TestConnect(test_address); /* Verify presets - expect 1, no duplicates */ - ASSERT_EQ(preset_details.size(), 1u); + ASSERT_EQ(1u, preset_details.size()); auto preset = std::find_if(preset_details.begin(), preset_details.end(), [](auto const& preset_info) { return preset_info.preset_index == 5; }); ASSERT_TRUE(preset != preset_details.end()); @@ -1873,7 +1908,7 @@ TEST_F(HasClientTest, test_preset_group_set_name) { .Times(1); HasClient::Get()->SetPresetName(not_synced_group, 55, "new preset name"); - ASSERT_EQ(preset_details.size(), 1u); + ASSERT_EQ(1u, preset_details.size()); ASSERT_EQ(preset_details[0].preset_name, "new preset name"); ASSERT_EQ(preset_details[0].preset_index, 55); } @@ -2198,7 +2233,7 @@ TEST_F(HasClientTest, test_select_preset_valid) { EXPECT_CALL(*callbacks, OnActivePresetSelected(_, _)).WillOnce(SaveArg<1>(&active_preset_index)); TestConnect(test_address); - ASSERT_TRUE(preset_details.size() > 1); + ASSERT_GT(preset_details.size(), 1u); ASSERT_EQ(preset_details.front().preset_index, active_preset_index); uint8_t new_active_preset_index = 0; @@ -2268,7 +2303,7 @@ TEST_F(HasClientTest, test_select_preset_not_available) { EXPECT_CALL(*callbacks, OnActivePresetSelected(_, _)).WillOnce(SaveArg<1>(&active_preset_index)); TestConnect(test_address); - ASSERT_TRUE(preset_details.size() > 1); + ASSERT_GT(preset_details.size(), 1u); ASSERT_EQ(preset_details.front().preset_index, active_preset_index); EXPECT_CALL(*callbacks, OnActivePresetSelectError(std::variant<RawAddress, int>(test_address), @@ -2344,8 +2379,8 @@ TEST_F(HasClientTest, test_select_group_preset_not_available) { ON_CALL(mock_csis_client_module_, GetDeviceList(group_id)) .WillByDefault(Return(std::vector<RawAddress>({{test_address1, test_address2}}))); - ASSERT_TRUE(preset_details1.size() > 1); - ASSERT_TRUE(preset_details2.size() > 1); + ASSERT_GT(preset_details1.size(), 1u); + ASSERT_GT(preset_details2.size(), 1u); ASSERT_EQ(preset_details1.front().preset_index, active_preset_index1); ASSERT_EQ(preset_details2.front().preset_index, active_preset_index2); @@ -2430,8 +2465,8 @@ TEST_F(HasClientTest, test_select_group_preset_not_available_binaural) { ON_CALL(mock_csis_client_module_, GetDeviceList(group_id)) .WillByDefault(Return(std::vector<RawAddress>({{test_address1, test_address2}}))); - ASSERT_TRUE(preset_details1.size() > 1); - ASSERT_TRUE(preset_details2.size() > 1); + ASSERT_GT(preset_details1.size(), 1u); + ASSERT_GT(preset_details2.size(), 1u); ASSERT_EQ(preset_details1.front().preset_index, active_preset_index1); ASSERT_EQ(preset_details2.front().preset_index, active_preset_index2); @@ -2518,8 +2553,8 @@ TEST_F(HasClientTest, test_select_group_preset_not_available_binaural_independen ON_CALL(mock_csis_client_module_, GetDeviceList(group_id)) .WillByDefault(Return(std::vector<RawAddress>({{test_address1, test_address2}}))); - ASSERT_TRUE(preset_details1.size() > 1); - ASSERT_TRUE(preset_details2.size() > 1); + ASSERT_GT(preset_details1.size(), 1u); + ASSERT_GT(preset_details2.size(), 1u); ASSERT_EQ(preset_details1.front().preset_index, active_preset_index1); ASSERT_EQ(preset_details2.front().preset_index, active_preset_index2); @@ -2654,7 +2689,7 @@ TEST_F(HasClientTest, test_select_preset_invalid) { EXPECT_CALL(*callbacks, OnActivePresetSelected(_, _)).WillOnce(SaveArg<1>(&active_preset_index)); TestConnect(test_address); - ASSERT_TRUE(preset_details.size() > 1); + ASSERT_GT(preset_details.size(), 1u); ASSERT_EQ(preset_details.front().preset_index, active_preset_index); /* Inject preset deletion of index 2 */ @@ -2694,7 +2729,7 @@ TEST_F(HasClientTest, test_select_preset_next) { EXPECT_CALL(*callbacks, OnActivePresetSelected(_, _)).WillOnce(SaveArg<1>(&active_preset_index)); TestConnect(test_address); - ASSERT_TRUE(preset_details.size() > 1); + ASSERT_GT(preset_details.size(), 1u); ASSERT_EQ(1, active_preset_index); /* Verify active preset change */ @@ -2827,7 +2862,7 @@ TEST_F(HasClientTest, test_select_preset_prev) { TestConnect(test_address); HasClient::Get()->SelectActivePreset(test_address, 2); - ASSERT_TRUE(preset_details.size() > 1); + ASSERT_GT(preset_details.size(), 1u); ASSERT_EQ(2, active_preset_index); /* Verify active preset change */ diff --git a/system/bta/hf_client/bta_hf_client_act.cc b/system/bta/hf_client/bta_hf_client_act.cc index c660f7a413..31daf28b4e 100644 --- a/system/bta/hf_client/bta_hf_client_act.cc +++ b/system/bta/hf_client/bta_hf_client_act.cc @@ -300,9 +300,8 @@ void bta_hf_client_rfc_close(tBTA_HF_CLIENT_DATA* p_data) { bta_hf_client_sco_shutdown(client_cb); bta_sys_sco_unuse(BTA_ID_HS, 1, client_cb->peer_addr); - } - /* else close port and deallocate scb */ - else { + } else { + /* else close port and deallocate scb */ tBTA_HF_CLIENT evt; memset(&evt, 0, sizeof(evt)); evt.reg.bd_addr = client_cb->peer_addr; diff --git a/system/bta/hf_client/bta_hf_client_at.h b/system/bta/hf_client/bta_hf_client_at.h index e4d4b2342e..8ac789fdc5 100644 --- a/system/bta/hf_client/bta_hf_client_at.h +++ b/system/bta/hf_client/bta_hf_client_at.h @@ -59,5 +59,4 @@ typedef struct { so when their values come later, we know which value in sequence match certain indicator */ int indicator_lookup[BTA_HF_CLIENT_AT_INDICATOR_COUNT]; - } tBTA_HF_CLIENT_AT_CB; diff --git a/system/bta/hf_client/bta_hf_client_int.h b/system/bta/hf_client/bta_hf_client_int.h index f9314633e3..4f560e762e 100644 --- a/system/bta/hf_client/bta_hf_client_int.h +++ b/system/bta/hf_client/bta_hf_client_int.h @@ -149,7 +149,6 @@ typedef union { tBTA_HF_CLIENT_DISC_RESULT disc_result; tBTA_HF_CLIENT_RFC rfc; tBTA_HF_CLIENT_DATA_VAL val; - } tBTA_HF_CLIENT_DATA; /* First handle for the control block */ diff --git a/system/bta/hf_client/bta_hf_client_rfc.cc b/system/bta/hf_client/bta_hf_client_rfc.cc index 262d31d267..48c6d49c80 100644 --- a/system/bta/hf_client/bta_hf_client_rfc.cc +++ b/system/bta/hf_client/bta_hf_client_rfc.cc @@ -244,9 +244,8 @@ void bta_hf_client_rfc_do_open(tBTA_HF_CLIENT_DATA* p_data) { BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT) == PORT_SUCCESS) { bta_hf_client_setup_port(client_cb->conn_handle); log::verbose("bta_hf_client_rfc_do_open : conn_handle = {}", client_cb->conn_handle); - } - /* RFCOMM create connection failed; send ourselves RFCOMM close event */ - else { + } else { + /* RFCOMM create connection failed; send ourselves RFCOMM close event */ bta_hf_client_sm_execute(BTA_HF_CLIENT_RFC_CLOSE_EVT, p_data); } } diff --git a/system/bta/hf_client/bta_hf_client_sco.cc b/system/bta/hf_client/bta_hf_client_sco.cc index f22077a48c..aa3f47f453 100644 --- a/system/bta/hf_client/bta_hf_client_sco.cc +++ b/system/bta/hf_client/bta_hf_client_sco.cc @@ -64,9 +64,8 @@ static bool bta_hf_client_sco_remove(tBTA_HF_CLIENT_CB* client_cb) { if (status == tBTM_STATUS::BTM_CMD_STARTED) { removed_started = true; - } - /* If no connection reset the SCO handle */ - else if ((status == tBTM_STATUS::BTM_SUCCESS) || (status == tBTM_STATUS::BTM_UNKNOWN_ADDR)) { + } else if ((status == tBTM_STATUS::BTM_SUCCESS) || (status == tBTM_STATUS::BTM_UNKNOWN_ADDR)) { + /* If no connection reset the SCO handle */ client_cb->sco_idx = BTM_INVALID_SCO_INDEX; } } diff --git a/system/bta/hf_client/bta_hf_client_sdp.cc b/system/bta/hf_client/bta_hf_client_sdp.cc index 94ebd87917..d967b40ff6 100644 --- a/system/bta/hf_client/bta_hf_client_sdp.cc +++ b/system/bta/hf_client/bta_hf_client_sdp.cc @@ -335,9 +335,8 @@ void bta_hf_client_do_disc(tBTA_HF_CLIENT_CB* client_cb) { attr_list[3] = ATTR_ID_SUPPORTED_FEATURES; num_attr = 4; uuid_list[0] = Uuid::From16Bit(UUID_SERVCLASS_AG_HANDSFREE); - } - /* acceptor; get features */ - else { + } else { + /* acceptor; get features */ attr_list[0] = ATTR_ID_SERVICE_CLASS_ID_LIST; attr_list[1] = ATTR_ID_BT_PROFILE_DESC_LIST; attr_list[2] = ATTR_ID_SUPPORTED_FEATURES; diff --git a/system/bta/hh/bta_hh_act.cc b/system/bta/hh/bta_hh_act.cc index 118a4b72f4..e32500a4ed 100644 --- a/system/bta/hh/bta_hh_act.cc +++ b/system/bta/hh/bta_hh_act.cc @@ -978,6 +978,9 @@ void bta_hh_maint_dev_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) { /* remove from known device list in BTA */ bta_hh_clean_up_kdev(p_cb); + } else if (com::android::bluetooth::flags::remove_pending_hid_connection()) { + log::warn("Failed to remove device {}", dev_info.link_spec); + bta_hh_clean_up_kdev(p_cb); } } break; diff --git a/system/bta/hh/bta_hh_int.h b/system/bta/hh/bta_hh_int.h index c897c2105b..2f9f502ba9 100644 --- a/system/bta/hh/bta_hh_int.h +++ b/system/bta/hh/bta_hh_int.h @@ -71,7 +71,6 @@ enum { BTA_HH_W4_SEC, BTA_HH_INVALID_ST /* Used to check invalid states before executing SM function */ - }; typedef uint8_t tBTA_HH_STATE; diff --git a/system/bta/hh/bta_hh_le.cc b/system/bta/hh/bta_hh_le.cc index c1f4447dc9..37f1a63cb7 100644 --- a/system/bta/hh/bta_hh_le.cc +++ b/system/bta/hh/bta_hh_le.cc @@ -542,18 +542,16 @@ static void bta_hh_le_register_input_notif(tBTA_HH_DEV_CB* p_dev_cb, uint8_t pro if (register_ba && p_rpt->uuid == GATT_UUID_BATTERY_LEVEL) { BTA_GATTC_RegisterForNotifications(bta_hh_cb.gatt_if, p_dev_cb->link_spec.addrt.bda, p_rpt->char_inst_id); - } - /* boot mode, deregister report input notification */ - else if (proto_mode == BTA_HH_PROTO_BOOT_MODE) { + } else if (proto_mode == BTA_HH_PROTO_BOOT_MODE) { + /* boot mode, deregister report input notification */ if (p_rpt->uuid == GATT_UUID_HID_REPORT && p_rpt->client_cfg_value == GATT_CLT_CONFIG_NOTIFICATION) { log::verbose("---> Deregister Report ID:{}", p_rpt->rpt_id); BTA_GATTC_DeregisterForNotifications(bta_hh_cb.gatt_if, p_dev_cb->link_spec.addrt.bda, p_rpt->char_inst_id); - } - /* register boot reports notification */ - else if (p_rpt->uuid == GATT_UUID_HID_BT_KB_INPUT || - p_rpt->uuid == GATT_UUID_HID_BT_MOUSE_INPUT) { + } else if (p_rpt->uuid == GATT_UUID_HID_BT_KB_INPUT || + /* register boot reports notification */ + p_rpt->uuid == GATT_UUID_HID_BT_MOUSE_INPUT) { log::verbose("<--- Register Boot Report ID:{}", p_rpt->rpt_id); BTA_GATTC_RegisterForNotifications(bta_hh_cb.gatt_if, p_dev_cb->link_spec.addrt.bda, p_rpt->char_inst_id); @@ -1026,9 +1024,8 @@ void bta_hh_security_cmpl(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* /* p_buf */) if (!bta_hh_le_set_protocol_mode(p_cb, p_cb->mode)) { bta_hh_le_open_cmpl(p_cb); } - } - /* start primary service discovery for HID service */ - else { + } else { + /* start primary service discovery for HID service */ log::verbose("Starting service discovery"); bta_hh_le_pri_service_discovery(p_cb); } @@ -1103,9 +1100,8 @@ void bta_hh_start_security(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* /* p_buf */ log::debug("addr:{} already encrypted", p_cb->link_spec.addrt.bda); p_cb->status = BTA_HH_OK; bta_hh_sm_execute(p_cb, BTA_HH_ENC_CMPL_EVT, NULL); - } - /* if bonded and link not encrypted */ - else if (BTM_IsLinkKeyKnown(p_cb->link_spec.addrt.bda, BT_TRANSPORT_LE)) { + } else if (BTM_IsLinkKeyKnown(p_cb->link_spec.addrt.bda, BT_TRANSPORT_LE)) { + /* if bonded and link not encrypted */ log::debug("addr:{} bonded, not encrypted", p_cb->link_spec.addrt.bda); p_cb->status = BTA_HH_ERR_AUTH_FAILED; BTM_SetEncryption(p_cb->link_spec.addrt.bda, BT_TRANSPORT_LE, bta_hh_le_encrypt_cback, NULL, diff --git a/system/bta/include/bta_api.h b/system/bta/include/bta_api.h index 8772fe183c..fbdf277df4 100644 --- a/system/bta/include/bta_api.h +++ b/system/bta/include/bta_api.h @@ -129,7 +129,6 @@ inline std::string preferred_role_text(const tBTA_PREF_ROLES& role) { } enum { - BTA_DM_NO_SCATTERNET, /* Device doesn't support scatternet, it might support "role switch during connection" for an incoming connection, when it already has @@ -139,7 +138,6 @@ enum { Peripheral roles for short period of time */ BTA_DM_FULL_SCATTERNET /* Device can have simultaneous connection in central and peripheral roles */ - }; typedef struct { diff --git a/system/bta/include/bta_hh_api.h b/system/bta/include/bta_hh_api.h index 506cea6583..e59f80a8b7 100644 --- a/system/bta/include/bta_hh_api.h +++ b/system/bta/include/bta_hh_api.h @@ -318,7 +318,6 @@ typedef struct { BT_HDR* p_rpt_data; /* GET_RPT_EVT : report data */ uint8_t idle_rate; /* GET_IDLE_EVT : idle rate */ } rsp_data; - } tBTA_HH_HSDATA; /* union of data associated with HD callback */ diff --git a/system/bta/include/bta_jv_api.h b/system/bta/include/bta_jv_api.h index f43bb9ed75..1809bf94d4 100644 --- a/system/bta/include/bta_jv_api.h +++ b/system/bta/include/bta_jv_api.h @@ -32,7 +32,7 @@ #include "include/macros.h" #include "internal_include/bt_target.h" #include "stack/include/bt_hdr.h" -#include "stack/include/l2cap_interface.h" +#include "stack/include/l2cap_types.h" #include "stack/include/rfcdefs.h" #include "types/bluetooth/uuid.h" #include "types/raw_address.h" diff --git a/system/bta/include/bta_pan_api.h b/system/bta/include/bta_pan_api.h index ad7f116786..bd4a00cc50 100644 --- a/system/bta/include/bta_pan_api.h +++ b/system/bta/include/bta_pan_api.h @@ -68,7 +68,6 @@ typedef struct { typedef struct { RawAddress bd_addr; /* BD address of peer device. */ uint16_t handle; /* Handle associated with this connection. */ - } tBTA_PAN_OPENING; /* Event associated with BTA_PAN_OPEN_EVT */ @@ -78,7 +77,6 @@ typedef struct { tBTA_PAN_STATUS status; /* status of open event */ tBTA_PAN_ROLE local_role; /* Local device PAN role for the connection */ tBTA_PAN_ROLE peer_role; /* Peer device PAN role for the connection */ - } tBTA_PAN_OPEN; /* Event associated with BTA_PAN_CLOSE_EVT */ diff --git a/system/bta/include/bta_vc_api.h b/system/bta/include/bta_vc_api.h index 2eb33c2f59..4a4ae893b4 100644 --- a/system/bta/include/bta_vc_api.h +++ b/system/bta/include/bta_vc_api.h @@ -17,6 +17,7 @@ #pragma once +#include <aics/api.h> #include <hardware/bt_vc.h> #include <string> @@ -57,7 +58,8 @@ public: virtual void GetExtAudioOutDescription(const RawAddress& address, uint8_t ext_output_id) = 0; virtual void SetExtAudioOutDescription(const RawAddress& address, uint8_t ext_output_id, std::string descr) = 0; - /* Audio Input Service (AIS)*/ + + /* Audio Input Control Service (AICS) */ virtual void GetExtAudioInState(const RawAddress& address, uint8_t ext_input_id) = 0; virtual void GetExtAudioInStatus(const RawAddress& address, uint8_t ext_input_id) = 0; virtual void GetExtAudioInType(const RawAddress& address, uint8_t ext_input_id) = 0; @@ -67,9 +69,8 @@ public: std::string descr) = 0; virtual void SetExtAudioInGainSetting(const RawAddress& address, uint8_t ext_input_id, int8_t gain_setting) = 0; - /* Set Gain Mode as per AIS */ virtual void SetExtAudioInGainMode(const RawAddress& address, uint8_t ext_input_id, - bool auto_mode) = 0; - virtual void SetExtAudioInGainMute(const RawAddress& address, uint8_t ext_input_id, - bool mute) = 0; + bluetooth::aics::GainMode gain_mode) = 0; + virtual void SetExtAudioInMute(const RawAddress& address, uint8_t ext_input_id, + bluetooth::aics::Mute mute) = 0; }; diff --git a/system/bta/jv/bta_jv_act.cc b/system/bta/jv/bta_jv_act.cc index cb00b7b6f8..20e57bd478 100644 --- a/system/bta/jv/bta_jv_act.cc +++ b/system/bta/jv/bta_jv_act.cc @@ -1901,26 +1901,23 @@ void bta_jv_rfcomm_write(uint32_t handle, uint32_t req_id, tBTA_JV_RFC_CB* p_cb, /* Set or free power mode profile for a JV application */ void bta_jv_set_pm_profile(uint32_t handle, tBTA_JV_PM_ID app_id, tBTA_JV_CONN_STATE init_st) { - tBTA_JV_STATUS status; - tBTA_JV_PM_CB* p_cb; - log::verbose("handle=0x{:x}, app_id={}, init_st={}", handle, app_id, bta_jv_conn_state_text(init_st)); /* clear PM control block */ if (app_id == BTA_JV_PM_ID_CLEAR) { - status = bta_jv_free_set_pm_profile_cb(handle); - + tBTA_JV_STATUS status = bta_jv_free_set_pm_profile_cb(handle); if (status != tBTA_JV_STATUS::SUCCESS) { - log::warn("free pm cb failed: reason={}", bta_jv_status_text(status)); + log::warn("Unable to free a power mode profile handle:0x:{:x} app_id:{} state:{} status:{}", + handle, app_id, init_st, bta_jv_status_text(status)); } } else { /* set PM control block */ - p_cb = bta_jv_alloc_set_pm_profile_cb(handle, app_id); - - if (NULL != p_cb) { + tBTA_JV_PM_CB* p_cb = bta_jv_alloc_set_pm_profile_cb(handle, app_id); + if (p_cb) { bta_jv_pm_state_change(p_cb, init_st); } else { - log::warn("failed"); + log::warn("Unable to allocate a power mode profile handle:0x:{:x} app_id:{} state:{}", handle, + app_id, init_st); } } } diff --git a/system/bta/le_audio/broadcaster/broadcast_configuration_provider.cc b/system/bta/le_audio/broadcaster/broadcast_configuration_provider.cc index 3f6c2ae600..03e0e4ad4f 100644 --- a/system/bta/le_audio/broadcaster/broadcast_configuration_provider.cc +++ b/system/bta/le_audio/broadcaster/broadcast_configuration_provider.cc @@ -76,4 +76,4 @@ BroadcastConfiguration GetBroadcastConfig( return lc3_mono_16_2_2; } } // namespace broadcaster -} // namespace bluetooth::le_audio
\ No newline at end of file +} // namespace bluetooth::le_audio diff --git a/system/bta/le_audio/broadcaster/broadcaster.cc b/system/bta/le_audio/broadcaster/broadcaster.cc index 251091a8b4..782e5826f9 100644 --- a/system/bta/le_audio/broadcaster/broadcaster.cc +++ b/system/bta/le_audio/broadcaster/broadcaster.cc @@ -889,7 +889,6 @@ public: log::assert_that(broadcasts_.count(broadcast_id) != 0, "assert failed: broadcasts_.count(broadcast_id) != 0"); broadcasts_[broadcast_id]->HandleHciEvent(HCI_BLE_CREATE_BIG_CPL_EVT, evt); - } break; case bluetooth::hci::iso_manager::kIsoEventBigOnTerminateCmpl: { auto* evt = static_cast<big_terminate_cmpl_evt*>(data); diff --git a/system/bta/le_audio/codec_interface.cc b/system/bta/le_audio/codec_interface.cc index 637c77f5bf..0342e45c74 100644 --- a/system/bta/le_audio/codec_interface.cc +++ b/system/bta/le_audio/codec_interface.cc @@ -80,8 +80,14 @@ struct CodecInterface::Impl { (pcm_config_->bits_per_sample == 24) ? LC3_PCM_FORMAT_S24 : LC3_PCM_FORMAT_S16; // Prepare the decoded output buffer - output_channel_samples_ = + auto num_samples = lc3_frame_samples(bt_codec_config_.data_interval_us, pcm_config_->sample_rate); + if (num_samples == -1) { + log::error("Could not determine the sample count for data_interval: {}, sample_rate: {}", + bt_codec_config_.data_interval_us, pcm_config_->sample_rate); + return CodecInterface::Status::STATUS_ERR_CODEC_NOT_READY; + } + output_channel_samples_ = num_samples; adjustOutputBufferSizeIfNeeded(&output_channel_data_); // Prepare the decoder @@ -185,7 +191,14 @@ struct CodecInterface::Impl { } if (codec_id_.coding_format == types::kLeAudioCodingFormatLC3) { - return lc3_frame_samples(bt_codec_config_.data_interval_us, pcm_config_->sample_rate); + auto num_samples = + lc3_frame_samples(bt_codec_config_.data_interval_us, pcm_config_->sample_rate); + if (num_samples == -1) { + log::error("Could not determine the sample count for data_interval: {}, sample_rate: {}", + bt_codec_config_.data_interval_us, pcm_config_->sample_rate); + return 0; + } + return num_samples; } log::error("Invalid codec ID: [{}:{}:{}]", codec_id_.coding_format, codec_id_.vendor_company_id, @@ -206,6 +219,7 @@ struct CodecInterface::Impl { private: inline void adjustOutputBufferSizeIfNeeded(std::vector<int16_t>* out_buffer) { if (out_buffer->size() < output_channel_samples_) { + log::debug("Changing buffer size to {}", output_channel_samples_); out_buffer->resize(output_channel_samples_); } } diff --git a/system/bta/le_audio/devices.h b/system/bta/le_audio/devices.h index e7dcbee61a..a7a27bdb1a 100644 --- a/system/bta/le_audio/devices.h +++ b/system/bta/le_audio/devices.h @@ -27,7 +27,7 @@ #include "gmap_client.h" #include "le_audio_types.h" #include "osi/include/alarm.h" -#include "raw_address.h" +#include "types/raw_address.h" namespace bluetooth::le_audio { diff --git a/system/bta/le_audio/devices_test.cc b/system/bta/le_audio/devices_test.cc index 11480961b8..26dfc62eb4 100644 --- a/system/bta/le_audio/devices_test.cc +++ b/system/bta/le_audio/devices_test.cc @@ -1080,9 +1080,9 @@ protected: } if (success_expected) { - ASSERT_TRUE(num_of_matching_configurations > 0); + ASSERT_GT(num_of_matching_configurations, 0); } else { - ASSERT_TRUE(num_of_matching_configurations == 0); + ASSERT_EQ(0, num_of_matching_configurations); } } diff --git a/system/bta/le_audio/le_audio_client_test.cc b/system/bta/le_audio/le_audio_client_test.cc index 111f051099..c2398ffe06 100644 --- a/system/bta/le_audio/le_audio_client_test.cc +++ b/system/bta/le_audio/le_audio_client_test.cc @@ -9840,7 +9840,7 @@ TEST_F(UnicastTest, TwoEarbudsStreamingProfileDisconnectStreamStopTimeout) { ASSERT_NE(0lu, streaming_groups.count(group_id)); auto group = streaming_groups.at(group_id); ASSERT_TRUE(group != nullptr); - ASSERT_TRUE(group->NumOfConnected() > 0); + ASSERT_GT(group->NumOfConnected(), 0); state_machine_callbacks_->OnStateTransitionTimeout(group_id); SyncOnMainLoop(); @@ -12493,10 +12493,7 @@ TEST_F(UnicastTestHandoverMode, SetAllowedContextMask) { ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); - types::BidirectionalPair<types::AudioContexts> metadata = {.sink = types::AudioContexts(), - .source = types::AudioContexts()}; - EXPECT_CALL(mock_state_machine_, - StartStream(_, types::LeAudioContextType::SOUNDEFFECTS, metadata, _)) + EXPECT_CALL(mock_state_machine_, StartStream(_, types::LeAudioContextType::SOUNDEFFECTS, _, _)) .Times(0); LeAudioClient::Get()->GroupSetActive(group_id); diff --git a/system/bta/le_audio/le_audio_log_history.h b/system/bta/le_audio/le_audio_log_history.h index 5fa17350e2..1e85affc0a 100644 --- a/system/bta/le_audio/le_audio_log_history.h +++ b/system/bta/le_audio/le_audio_log_history.h @@ -75,4 +75,4 @@ public: const std::string& msg) = 0; virtual void AddLogHistory(const std::string& tag, int group_id, const RawAddress& addr, const std::string& msg, const std::string& extra) = 0; -};
\ No newline at end of file +}; diff --git a/system/bta/le_audio/le_audio_types.h b/system/bta/le_audio/le_audio_types.h index 2d9a46a30f..85bb1beed4 100644 --- a/system/bta/le_audio/le_audio_types.h +++ b/system/bta/le_audio/le_audio_types.h @@ -33,11 +33,11 @@ #include <variant> #include <vector> -#include "bluetooth/uuid.h" #include "bta/include/bta_le_audio_uuids.h" #include "osi/include/alarm.h" #include "stack/include/bt_types.h" #include "stack/include/btm_iso_api_types.h" +#include "types/bluetooth/uuid.h" namespace bluetooth::le_audio { diff --git a/system/bta/le_audio/le_audio_utils.cc b/system/bta/le_audio/le_audio_utils.cc index 719d017607..8a1bb6cbfc 100644 --- a/system/bta/le_audio/le_audio_utils.cc +++ b/system/bta/le_audio/le_audio_utils.cc @@ -64,7 +64,7 @@ LeAudioContextType AudioContentToLeAudioContext(audio_content_type_t content_typ return LeAudioContextType::RINGTONE; } - return LeAudioContextType::MEDIA; + return LeAudioContextType::SOUNDEFFECTS; case AUDIO_USAGE_GAME: return LeAudioContextType::GAME; case AUDIO_USAGE_NOTIFICATION: diff --git a/system/bta/le_audio/state_machine.cc b/system/bta/le_audio/state_machine.cc index dff39b1f39..b548a1fc2e 100644 --- a/system/bta/le_audio/state_machine.cc +++ b/system/bta/le_audio/state_machine.cc @@ -1687,7 +1687,6 @@ private: leAudioDevice->address_, BT_TRANSPORT_LE); conn_pairs.push_back({.cis_conn_handle = ase->cis_conn_hdl, .acl_conn_handle = acl_handle}); log::debug("cis handle: {} acl handle : 0x{:x}", ase->cis_conn_hdl, acl_handle); - } while ((ase = leAudioDevice->GetNextActiveAse(ase))); } while ((leAudioDevice = group->GetNextActiveDevice(leAudioDevice))); @@ -2416,7 +2415,6 @@ private: msg_stream << "ASE_ID " << +ase->id << ","; extra_stream << "meta: " << base::HexEncode(conf.metadata.data(), conf.metadata.size()) << ";;"; - } while ((ase = leAudioDevice->GetNextActiveAse(ase))); bluetooth::le_audio::client_parser::ascs::PrepareAseCtpEnable(confs, value); diff --git a/system/bta/le_audio/storage_helper.h b/system/bta/le_audio/storage_helper.h index 0f196024f7..85418457c9 100644 --- a/system/bta/le_audio/storage_helper.h +++ b/system/bta/le_audio/storage_helper.h @@ -31,4 +31,4 @@ bool SerializeAses(const LeAudioDevice* leAudioDevice, std::vector<uint8_t>& out bool DeserializeAses(LeAudioDevice* leAudioDevice, const std::vector<uint8_t>& in); bool SerializeHandles(const LeAudioDevice* leAudioDevice, std::vector<uint8_t>& out); bool DeserializeHandles(LeAudioDevice* leAudioDevice, const std::vector<uint8_t>& in); -} // namespace bluetooth::le_audio
\ No newline at end of file +} // namespace bluetooth::le_audio diff --git a/system/bta/le_audio/storage_helper_test.cc b/system/bta/le_audio/storage_helper_test.cc index 07dbb6859d..ef0a9ed172 100644 --- a/system/bta/le_audio/storage_helper_test.cc +++ b/system/bta/le_audio/storage_helper_test.cc @@ -37,61 +37,61 @@ TEST(StorageHelperTest, DeserializeSinkPacs) { const std::vector<uint8_t> validSinkPack = { 0x00, // Magic 0x01, // Num of PACs - 0x02,0x12, // handle - 0x03,0x12, // cc handle + 0x02, 0x12, // handle + 0x03, 0x12, // cc handle 0x02, // Number of records in PAC 0x1e, // PAC entry size - 0x06,0x00,0x00,0x00,0x00, // Codec Id + 0x06, 0x00, 0x00, 0x00, 0x00, // Codec Id 0x13, // Codec specific cap. size - 0x03,0x01,0x04,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x1e,0x00,0x1e,0x00,0x02,0x05,0x01, // Codec specific capa + 0x03, 0x01, 0x04, 0x00, 0x02, 0x02, 0x01, 0x02, 0x03, 0x01, 0x05, 0x04, 0x1e, 0x00, 0x1e, 0x00, 0x02, 0x05, 0x01, // Codec specific capa 0x04, // Metadata size - 0x03,0x01,0xff,0x0f, // Metadata + 0x03, 0x01, 0xff, 0x0f, // Metadata 0x1e, // - 0x06,0x00,0x00,0x00,0x00, // Codec ID + 0x06, 0x00, 0x00, 0x00, 0x00, // Codec ID 0x13, // Codec specific cap. size - 0x03,0x01,0x20,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x3c,0x00,0x3c,0x00,0x02,0x05,0x01, // Codec specific capa + 0x03, 0x01, 0x20, 0x00, 0x02, 0x02, 0x01, 0x02, 0x03, 0x01, 0x05, 0x04, 0x3c, 0x00, 0x3c, 0x00, 0x02, 0x05, 0x01, // Codec specific capa 0x04, // Codec specific capa - 0x03,0x01,0xff,0x0f, // Metadata + 0x03, 0x01, 0xff, 0x0f, // Metadata }; const std::vector<uint8_t> invalidSinkPackNumOfPacs = { 0x00, // Magic 0x05, // Num of PACs - 0x02,0x12, // handle - 0x03,0x12, // cc handle + 0x02, 0x12, // handle + 0x03, 0x12, // cc handle 0x01, // Number of records in PAC 0x1e, // PAC entry size - 0x06,0x00,0x00,0x00,0x00, // Codec Id + 0x06, 0x00, 0x00, 0x00, 0x00, // Codec Id 0x13, // Codec specific cap. size - 0x03,0x01,0x04,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x1e,0x00,0x1e,0x00,0x02,0x05,0x01, // Codec specific capa + 0x03, 0x01, 0x04, 0x00, 0x02, 0x02, 0x01, 0x02, 0x03, 0x01, 0x05, 0x04, 0x1e, 0x00, 0x1e, 0x00, 0x02, 0x05, 0x01, // Codec specific capa 0x04, // Metadata size - 0x03,0x01,0xff,0x0f, // Metadata + 0x03, 0x01, 0xff, 0x0f, // Metadata 0x1e, // - 0x06,0x00,0x00,0x00,0x00, // Codec ID + 0x06, 0x00, 0x00, 0x00, 0x00, // Codec ID 0x13, // Codec specific cap. size - 0x03,0x01,0x20,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x3c,0x00,0x3c,0x00,0x02,0x05,0x01, // Codec specific capa + 0x03, 0x01, 0x20, 0x00, 0x02, 0x02, 0x01, 0x02, 0x03, 0x01, 0x05, 0x04, 0x3c, 0x00, 0x3c, 0x00, 0x02, 0x05, 0x01, // Codec specific capa 0x04, // Codec specific capa - 0x03,0x01,0xff,0x0f, // Metadata + 0x03, 0x01, 0xff, 0x0f, // Metadata }; const std::vector<uint8_t> invalidSinkPackMagic = { 0x01, // Magic 0x01, // Num of PACs - 0x02,0x12, // handle - 0x03,0x12, // cc handle + 0x02, 0x12, // handle + 0x03, 0x12, // cc handle 0x02, // Number of records in PAC 0x1e, // PAC entry size - 0x06,0x00,0x00,0x00,0x00, // Codec Id + 0x06, 0x00, 0x00, 0x00, 0x00, // Codec Id 0x13, // Codec specific cap. size - 0x03,0x01,0x04,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x1e,0x00,0x1e,0x00,0x02,0x05,0x01, // Codec specific capa + 0x03, 0x01, 0x04, 0x00, 0x02, 0x02, 0x01, 0x02, 0x03, 0x01, 0x05, 0x04, 0x1e, 0x00, 0x1e, 0x00, 0x02, 0x05, 0x01, // Codec specific capa 0x04, // Metadata size - 0x03,0x01,0xff,0x0f, // Metadata + 0x03, 0x01, 0xff, 0x0f, // Metadata 0x1e, // - 0x06,0x00,0x00,0x00,0x00, // Codec ID + 0x06, 0x00, 0x00, 0x00, 0x00, // Codec ID 0x13, // Codec specific cap. size - 0x03,0x01,0x20,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x3c,0x00,0x3c,0x00,0x02,0x05,0x01, // Codec specific capa + 0x03, 0x01, 0x20, 0x00, 0x02, 0x02, 0x01, 0x02, 0x03, 0x01, 0x05, 0x04, 0x3c, 0x00, 0x3c, 0x00, 0x02, 0x05, 0x01, // Codec specific capa 0x04, // Codec specific capa - 0x03,0x01,0xff,0x0f, // Metadata + 0x03, 0x01, 0xff, 0x0f, // Metadata }; // clang-format on @@ -111,71 +111,71 @@ TEST(StorageHelperTest, DeserializeSourcePacs) { const std::vector<uint8_t> validSourcePack = { 0x00, // Magic 0x01, // Num of PACs - 0x08,0x12, // handle - 0x09,0x12, // cc handle + 0x08, 0x12, // handle + 0x09, 0x12, // cc handle 0x02, // Number of records in PAC 0x1e, // PAC entry size - 0x06,0x00,0x00,0x00,0x00, // Codec Id + 0x06, 0x00, 0x00, 0x00, 0x00, // Codec Id 0x13, // Codec specific cap. size - 0x03,0x01,0x04,0x00,0x02,0x02,0x01,0x02,0x03,0x01,0x05,0x04,0x1e,0x00,0x1e,0x00,0x02,0x05,0x01, + 0x03, 0x01, 0x04, 0x00, 0x02, 0x02, 0x01, 0x02, 0x03, 0x01, 0x05, 0x04, 0x1e, 0x00, 0x1e, 0x00, 0x02, 0x05, 0x01, 0x04, // Metadata size - 0x03,0x01,0x03,0x00, // Metadata + 0x03, 0x01, 0x03, 0x00, // Metadata 0x1e, // PAC entry size - 0x06,0x00,0x00,0x00,0x00, // Codec Id + 0x06, 0x00, 0x00, 0x00, 0x00, // Codec Id 0x13, // Codec specific cap. size - 0x03,0x01,0x20,0x00,0x02,0x02,0x01,0x02, // Codec specific capa - 0x03,0x01,0x05,0x04,0x3c,0x00,0x3c,0x00, // Codec specific capa - 0x02,0x05,0x01, // Codec specific capa + 0x03, 0x01, 0x20, 0x00, 0x02, 0x02, 0x01, 0x02, // Codec specific capa + 0x03, 0x01, 0x05, 0x04, 0x3c, 0x00, 0x3c, 0x00, // Codec specific capa + 0x02, 0x05, 0x01, // Codec specific capa 0x04, // Metadata size - 0x03,0x01,0x03,0x00 // Metadata + 0x03, 0x01, 0x03, 0x00 // Metadata }; const std::vector<uint8_t> invalidSourcePackNumOfPacs = { 0x00, // Magic 0x04, // Num of PACs - 0x08,0x12, // handle - 0x09,0x12, // cc handle + 0x08, 0x12, // handle + 0x09, 0x12, // cc handle 0x01, // Number of records in PAC 0x1e, // PAC entry size - 0x06,0x00,0x00,0x00,0x00, // Codec Id + 0x06, 0x00, 0x00, 0x00, 0x00, // Codec Id 0x13, // Codec specific cap. size - 0x03,0x01,0x04,0x00,0x02,0x02,0x01,0x02, // Codec specific capa - 0x03,0x01,0x05,0x04,0x1e,0x00,0x1e,0x00, // Codec specific capa - 0x02,0x05,0x01, // Codec specific capa + 0x03, 0x01, 0x04, 0x00, 0x02, 0x02, 0x01, 0x02, // Codec specific capa + 0x03, 0x01, 0x05, 0x04, 0x1e, 0x00, 0x1e, 0x00, // Codec specific capa + 0x02, 0x05, 0x01, // Codec specific capa 0x04, // Metadata size - 0x03,0x01,0x03,0x00, // Metadata + 0x03, 0x01, 0x03, 0x00, // Metadata 0x1e, // PAC entry size - 0x06,0x00,0x00,0x00,0x00, // Codec Id + 0x06, 0x00, 0x00, 0x00, 0x00, // Codec Id 0x13, // Codec specific cap. size - 0x03,0x01,0x20,0x00,0x02,0x02,0x01,0x02, // Codec specific capa - 0x03,0x01,0x05,0x04,0x3c,0x00,0x3c,0x00, // Codec specific capa - 0x02,0x05,0x01, // Codec specific capa + 0x03, 0x01, 0x20, 0x00, 0x02, 0x02, 0x01, 0x02, // Codec specific capa + 0x03, 0x01, 0x05, 0x04, 0x3c, 0x00, 0x3c, 0x00, // Codec specific capa + 0x02, 0x05, 0x01, // Codec specific capa 0x04, // Metadata size - 0x03,0x01,0x03,0x00 // Metadata + 0x03, 0x01, 0x03, 0x00 // Metadata }; const std::vector<uint8_t> invalidSourcePackMagic = { 0x01, // Magic 0x01, // Num of PACs - 0x08,0x12, // handle - 0x09,0x12, // cc handle + 0x08, 0x12, // handle + 0x09, 0x12, // cc handle 0x02, // Number of records in PAC 0x1e, // PAC entry size - 0x06,0x00,0x00,0x00,0x00, // Codec Id + 0x06, 0x00, 0x00, 0x00, 0x00, // Codec Id 0x13, // Codec specific cap. size - 0x03,0x01,0x04,0x00,0x02,0x02,0x01,0x02, // Codec specific capa - 0x03,0x01,0x05,0x04,0x1e,0x00,0x1e,0x00, // Codec specific capa - 0x02,0x05,0x01, // Codec specific capa + 0x03, 0x01, 0x04, 0x00, 0x02, 0x02, 0x01, 0x02, // Codec specific capa + 0x03, 0x01, 0x05, 0x04, 0x1e, 0x00, 0x1e, 0x00, // Codec specific capa + 0x02, 0x05, 0x01, // Codec specific capa 0x04, // Metadata size - 0x03,0x01,0x03,0x00, // Metadata + 0x03, 0x01, 0x03, 0x00, // Metadata 0x1e, // PAC entry size - 0x06,0x00,0x00,0x00,0x00, // Codec Id + 0x06, 0x00, 0x00, 0x00, 0x00, // Codec Id 0x13, // Codec specific cap. size - 0x03,0x01,0x20,0x00,0x02,0x02,0x01,0x02, // Codec specific capa - 0x03,0x01,0x05,0x04,0x3c,0x00,0x3c,0x00, // Codec specific capa - 0x02,0x05,0x01, // Codec specific capa + 0x03, 0x01, 0x20, 0x00, 0x02, 0x02, 0x01, 0x02, // Codec specific capa + 0x03, 0x01, 0x05, 0x04, 0x3c, 0x00, 0x3c, 0x00, // Codec specific capa + 0x02, 0x05, 0x01, // Codec specific capa 0x04, // Metadata size - 0x03,0x01,0x03,0x00 // Metadata + 0x03, 0x01, 0x03, 0x00 // Metadata }; // clang-format on @@ -206,7 +206,7 @@ TEST(StorageHelperTest, DeserializeAses) { 0x0b, 0x11, // handle 0x0c, 0x11, // ccc handle 0x03, // ASE id - 0x02 // direction + 0x02 // direction }; const std::vector<uint8_t> invalidAsesNumOfAses { 0x00, // Magic @@ -222,7 +222,7 @@ TEST(StorageHelperTest, DeserializeAses) { 0x0b, 0x11, // handle 0x0c, 0x11, // ccc handle 0x03, // ASE id - 0x02 // direction + 0x02 // direction }; const std::vector<uint8_t> invalidAsesMagic { 0x01, // Magic @@ -238,7 +238,7 @@ TEST(StorageHelperTest, DeserializeAses) { 0x0b, 0x11, // handle 0x0c, 0x11, // ccc handle 0x03, // ASE id - 0x02 // direction + 0x02 // direction }; // clang-format on RawAddress test_address0 = GetTestAddress(0); diff --git a/system/bta/pan/bta_pan_act.cc b/system/bta/pan/bta_pan_act.cc index fa24534bd9..2ecc793111 100644 --- a/system/bta/pan/bta_pan_act.cc +++ b/system/bta/pan/bta_pan_act.cc @@ -348,9 +348,8 @@ void bta_pan_set_role(tBTA_PAN_DATA* p_data) { } else { bta_sys_remove_uuid(UUID_SERVCLASS_PANU); } - } - /* if status is not success clear everything */ - else { + } else { + /* if status is not success clear everything */ PAN_SetRole(0, std::string(), std::string()); bta_sys_remove_uuid(UUID_SERVCLASS_NAP); bta_sys_remove_uuid(UUID_SERVCLASS_GN); @@ -547,9 +546,8 @@ void bta_pan_rx_path(tBTA_PAN_SCB* p_scb, tBTA_PAN_DATA* /* p_data */) { /* call application callout function for rx path */ bta_pan_co_rx_path(p_scb->handle, p_scb->app_id); } - } - /* else data path configured for rx push */ - else { + } else { + /* else data path configured for rx push */ } } diff --git a/system/bta/pan/bta_pan_int.h b/system/bta/pan/bta_pan_int.h index 09781f4269..dd9e154228 100644 --- a/system/bta/pan/bta_pan_int.h +++ b/system/bta/pan/bta_pan_int.h @@ -101,7 +101,6 @@ typedef struct { typedef struct { BT_HDR_RIGID hdr; /* Event header */ tPAN_RESULT result; - } tBTA_PAN_CONN; /* pan data param */ @@ -112,7 +111,6 @@ typedef struct { uint16_t protocol; bool ext; bool forward; - } tBTA_PAN_DATA_PARAMS; /* union of all data types */ @@ -139,7 +137,6 @@ typedef struct { tBTA_PAN_ROLE local_role; /* local role */ tBTA_PAN_ROLE peer_role; /* peer role */ uint8_t app_id; /* application id for the connection */ - } tBTA_PAN_SCB; /* main control block */ @@ -149,7 +146,6 @@ typedef struct { uint8_t app_id[3]; /* application id for PAN roles */ uint8_t flow_mask; /* Data flow mask */ uint8_t q_level; /* queue level set by application for TX data */ - } tBTA_PAN_CB; /***************************************************************************** diff --git a/system/bta/pan/bta_pan_main.cc b/system/bta/pan/bta_pan_main.cc index 91652e596a..249b3c01cb 100644 --- a/system/bta/pan/bta_pan_main.cc +++ b/system/bta/pan/bta_pan_main.cc @@ -56,7 +56,6 @@ typedef void (*tBTA_PAN_ACTION)(tBTA_PAN_SCB* p_scb, tBTA_PAN_DATA* p_data); const tBTA_PAN_ACTION bta_pan_action[] = { bta_pan_api_close, bta_pan_tx_path, bta_pan_rx_path, bta_pan_tx_flow, bta_pan_write_buf, bta_pan_conn_open, bta_pan_conn_close, bta_pan_free_buf, - }; /* state table information */ @@ -75,8 +74,7 @@ const uint8_t bta_pan_st_idle[][BTA_PAN_NUM_COLS] = { /* PAN_CONN_OPEN */ {BTA_PAN_CONN_OPEN, BTA_PAN_OPEN_ST}, /* PAN_CONN_CLOSE */ {BTA_PAN_CONN_OPEN, BTA_PAN_IDLE_ST}, /* FLOW_ENABLE */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST}, - /* BNEP_DATA */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST} - + /* BNEP_DATA */ {BTA_PAN_IGNORE, BTA_PAN_IDLE_ST}, }; /* state table for open state */ @@ -90,7 +88,8 @@ const uint8_t bta_pan_st_open[][BTA_PAN_NUM_COLS] = { /* PAN_CONN_OPEN */ {BTA_PAN_IGNORE, BTA_PAN_OPEN_ST}, /* PAN_CONN_CLOSE */ {BTA_PAN_CONN_CLOSE, BTA_PAN_IDLE_ST}, /* FLOW_ENABLE */ {BTA_PAN_RX_PATH, BTA_PAN_OPEN_ST}, - /* BNEP_DATA */ {BTA_PAN_TX_PATH, BTA_PAN_OPEN_ST}}; + /* BNEP_DATA */ {BTA_PAN_TX_PATH, BTA_PAN_OPEN_ST}, +}; /* state table for closing state */ const uint8_t bta_pan_st_closing[][BTA_PAN_NUM_COLS] = { @@ -103,7 +102,8 @@ const uint8_t bta_pan_st_closing[][BTA_PAN_NUM_COLS] = { /* PAN_CONN_OPEN */ {BTA_PAN_IGNORE, BTA_PAN_CLOSING_ST}, /* PAN_CONN_CLOSE */ {BTA_PAN_CONN_CLOSE, BTA_PAN_IDLE_ST}, /* FLOW_ENABLE */ {BTA_PAN_RX_PATH, BTA_PAN_CLOSING_ST}, - /* BNEP_DATA */ {BTA_PAN_TX_PATH, BTA_PAN_CLOSING_ST}}; + /* BNEP_DATA */ {BTA_PAN_TX_PATH, BTA_PAN_CLOSING_ST}, +}; /* type for state table */ typedef const uint8_t (*tBTA_PAN_ST_TBL)[BTA_PAN_NUM_COLS]; diff --git a/system/bta/pb/bta_pbs_int.h b/system/bta/pb/bta_pbs_int.h index 4a06199983..5807ac15f5 100644 --- a/system/bta/pb/bta_pbs_int.h +++ b/system/bta/pb/bta_pbs_int.h @@ -53,7 +53,6 @@ typedef struct { (Server only) */ uint8_t supported_features; /* Server supported features */ uint8_t supported_repositories; /* Server supported repositories */ - } tBTA_PBS_CFG; #endif /* BTA_PBS_INT_H */ diff --git a/system/bta/ras/ras_types.h b/system/bta/ras/ras_types.h index 95dda05aae..1db5c4f35e 100644 --- a/system/bta/ras/ras_types.h +++ b/system/bta/ras/ras_types.h @@ -16,7 +16,7 @@ #pragma once -#include "bluetooth/uuid.h" +#include "types/bluetooth/uuid.h" namespace ras { static const uint16_t kFeatureSize = 0x04; diff --git a/system/bta/sys/bta_sys_int.h b/system/bta/sys/bta_sys_int.h index 7f37764fc5..5d0b4755ae 100644 --- a/system/bta/sys/bta_sys_int.h +++ b/system/bta/sys/bta_sys_int.h @@ -61,7 +61,6 @@ typedef struct { tBTA_SYS_SSR_CFG_CBACK* p_ssr_cb; /* VS event handler */ tBTA_SYS_VS_EVT_HDLR* p_vs_evt_hdlr; - } tBTA_SYS_CB; /***************************************************************************** diff --git a/system/bta/sys/utl.cc b/system/bta/sys/utl.cc index aa421d76bb..2d625083c5 100644 --- a/system/bta/sys/utl.cc +++ b/system/bta/sys/utl.cc @@ -100,9 +100,8 @@ int utl_strucmp(const char* p_s, const char* p_t) { /* if p_t hit null first, no match */ if (*p_t == 0 && *p_s != 0) { return 1; - } - /* else p_s hit null first, count as match */ - else { + } else { + /* else p_s hit null first, count as match */ return 0; } } diff --git a/system/bta/test/gatt/database_test.cc b/system/bta/test/gatt/database_test.cc index e6f6075d10..3b50d860ae 100644 --- a/system/bta/test/gatt/database_test.cc +++ b/system/bta/test/gatt/database_test.cc @@ -539,5 +539,4 @@ TEST(GattDatabaseTest, serialized_hash_test) { EXPECT_EQ(db_from_disk.Hash(), db_from_serialized.Hash()); } - } // namespace gatt diff --git a/system/bta/vc/device.cc b/system/bta/vc/device.cc index 43f1e61d56..1510e99a51 100644 --- a/system/bta/vc/device.cc +++ b/system/bta/vc/device.cc @@ -610,12 +610,12 @@ void VolumeControlDevice::GetExtAudioInDescription(uint8_t ext_input_id, GATT_RE void VolumeControlDevice::SetExtAudioInDescription(uint8_t ext_input_id, const std::string& descr) { VolumeAudioInput* input = audio_inputs.FindById(ext_input_id); if (!input) { - log::error("{}, no such input={:#x}", address, ext_input_id); + log::error("{} no such input={:#x}", address, ext_input_id); return; } if (!input->description_writable) { - log::warn("not writable"); + log::warn("{} input={:#x} input description is not writable", address, ext_input_id); return; } @@ -624,13 +624,13 @@ void VolumeControlDevice::SetExtAudioInDescription(uint8_t ext_input_id, const s GATT_WRITE_NO_RSP, nullptr, nullptr); } -void VolumeControlDevice::ExtAudioInControlPointOperation(uint8_t ext_input_id, uint8_t opcode, +bool VolumeControlDevice::ExtAudioInControlPointOperation(uint8_t ext_input_id, uint8_t opcode, const std::vector<uint8_t>* arg, GATT_WRITE_OP_CB cb, void* cb_data) { VolumeAudioInput* input = audio_inputs.FindById(ext_input_id); if (!input) { log::error("{}, no such input={:#x}", address, ext_input_id); - return; + return false; } std::vector<uint8_t> set_value({opcode, input->change_counter}); @@ -640,6 +640,7 @@ void VolumeControlDevice::ExtAudioInControlPointOperation(uint8_t ext_input_id, BtaGattQueue::WriteCharacteristic(connection_id, input->control_point_handle, set_value, GATT_WRITE, cb, cb_data); + return true; } bool VolumeControlDevice::IsEncryptionEnabled() { diff --git a/system/bta/vc/devices.h b/system/bta/vc/devices.h index 8c0a5739c4..19f2bd5650 100644 --- a/system/bta/vc/devices.h +++ b/system/bta/vc/devices.h @@ -99,10 +99,12 @@ public: stream << " volume: " << +volume << "\n" << " mute: " << +mute << "\n" + << " change_counter: " << +change_counter << "\n" << " flags: " << +flags << "\n" - << " device read: " << device_ready << "\n" + << " device ready: " << device_ready << "\n" << " connecting_actively: " << connecting_actively << "\n" - << " change_counter: " << +change_counter << "\n"; + << " is encrypted: " << IsEncryptionEnabled() << "\n" + << " GATT operations pending: " << handles_pending.size() << "\n"; dprintf(fd, "%s", stream.str().c_str()); audio_offsets.Dump(fd); @@ -137,7 +139,7 @@ public: void GetExtAudioInGainProps(uint8_t ext_input_id, GATT_READ_OP_CB cb, void* cb_data); void GetExtAudioInDescription(uint8_t ext_input_id, GATT_READ_OP_CB cb, void* cb_data); void SetExtAudioInDescription(uint8_t ext_input_id, const std::string& descr); - void ExtAudioInControlPointOperation(uint8_t ext_input_id, uint8_t opcode, + bool ExtAudioInControlPointOperation(uint8_t ext_input_id, uint8_t opcode, const std::vector<uint8_t>* arg, GATT_WRITE_OP_CB cb, void* cb_data); bool IsEncryptionEnabled(); diff --git a/system/bta/vc/types.h b/system/bta/vc/types.h index 65d83550be..6c69bd7aa7 100644 --- a/system/bta/vc/types.h +++ b/system/bta/vc/types.h @@ -137,12 +137,12 @@ struct GainSettings { struct VolumeAudioInput { /* const */ uint8_t id; - Mute mute = bluetooth::aics::Mute::DISABLED; int8_t gain_setting = 0; + bluetooth::aics::Mute mute = bluetooth::aics::Mute::DISABLED; + bluetooth::aics::GainMode gain_mode = bluetooth::aics::GainMode::MANUAL_ONLY; VolumeInputStatus status = VolumeInputStatus::Inactive; VolumeInputType type = VolumeInputType::Unspecified; uint8_t change_counter = 0; - uint8_t mode = 0; std::string description = ""; /* const */ uint16_t service_handle; /* const */ uint16_t state_handle; diff --git a/system/bta/vc/vc.cc b/system/bta/vc/vc.cc index 9c89b9887e..e18d630a80 100644 --- a/system/bta/vc/vc.cc +++ b/system/bta/vc/vc.cc @@ -195,7 +195,7 @@ public: /* Make sure to remove device from background connect. * It will be added back if needed, when device got disconnected */ - BTA_GATTC_CancelOpen(gatt_if_, address, false); + BTA_GATTC_CancelOpen(gatt_if_, address, true); if (device->IsEncryptionEnabled()) { OnEncryptionComplete(address, tBTM_STATUS::BTM_SUCCESS); @@ -590,14 +590,19 @@ public: } input->mute = bluetooth::aics::parseMuteField(mute); - STREAM_TO_UINT8(input->mode, pp); + uint8_t gain_mode; + STREAM_TO_UINT8(gain_mode, pp); + if (!bluetooth::aics::isValidAudioInputGainModeValue(gain_mode)) { + bluetooth::log::error("{} Invalid GainMode value: {:#x}", device->address, gain_mode); + return; + } + input->gain_mode = bluetooth::aics::parseGainModeField(gain_mode); STREAM_TO_UINT8(input->change_counter, pp); bluetooth::log::verbose("{}, data:{}", device->address, base::HexEncode(value, len)); bluetooth::log::info( - "{} id={:#x}gain_setting {:#x}, mute: {:#x}, mode: {:#x}, " - "change_counter: {}", - device->address, input->id, input->gain_setting, mute, input->mode, + "{} id={:#x}gain_setting {:#x}, mute: {:#x}, mode: {:#x}, change_counter: {}", + device->address, input->id, input->gain_setting, input->mute, input->gain_mode, input->change_counter); if (!device->device_ready) { @@ -605,7 +610,7 @@ public: } callbacks_->OnExtAudioInStateChanged(device->address, input->id, input->gain_setting, - input->mute, input->mode); + input->mute, input->gain_mode); } void OnExtAudioInTypeChanged(VolumeControlDevice* device, VolumeAudioInput* input, uint16_t len, @@ -672,10 +677,12 @@ public: return; } - callbacks_->OnExtAudioInDescriptionChanged(device->address, input->id, input->description); + callbacks_->OnExtAudioInDescriptionChanged(device->address, input->id, input->description, + input->description_writable); } - void OnExtAudioInCPWrite(uint16_t connection_id, tGATT_STATUS status, uint16_t handle) { + void OnExtAudioInCPWrite(uint16_t connection_id, tGATT_STATUS status, uint16_t handle, + uint8_t opcode, uint8_t id) { VolumeControlDevice* device = volume_control_devices_.FindByConnId(connection_id); if (!device) { bluetooth::log::info("Skipping unknown device disconnect, connection_id={:#x}", @@ -685,6 +692,25 @@ public: bluetooth::log::info("{}, Input Control Point write response handle {:#x}, status {:#x}", device->address, handle, status); + if (status == GATT_SUCCESS) { + return; + } + + switch (opcode) { + case kVolumeInputControlPointOpcodeSetGain: + callbacks_->OnExtAudioInSetGainSettingFailed(device->address, id); + break; + case kVolumeInputControlPointOpcodeMute: + case kVolumeInputControlPointOpcodeUnmute: + callbacks_->OnExtAudioInSetMuteFailed(device->address, id); + break; + case kVolumeInputControlPointOpcodeSetAutoGainMode: + case kVolumeInputControlPointOpcodeSetManualGainMode: + callbacks_->OnExtAudioInSetGainModeFailed(device->address, id); + break; + default: + bluetooth::log::error("{} Not a valid opcode", opcode); + } } void OnExtAudioInGainSettingChanged(VolumeControlDevice* device, VolumeAudioInput* input, @@ -708,8 +734,9 @@ public: return; } - callbacks_->OnExtAudioInGainPropsChanged(device->address, input->id, input->gain_settings.unit, - input->gain_settings.min, input->gain_settings.max); + callbacks_->OnExtAudioInGainSettingPropertiesChanged( + device->address, input->id, input->gain_settings.unit, input->gain_settings.min, + input->gain_settings.max); } void OnExtAudioOutCPWrite(tCONN_ID connection_id, tGATT_STATUS status, uint16_t handle, @@ -810,14 +837,14 @@ public: bluetooth::log::info("{}", address); /* Removes all registrations for connection. */ - BTA_GATTC_CancelOpen(gatt_if_, address, false); + BTA_GATTC_CancelOpen(gatt_if_, address, true); Disconnect(address); volume_control_devices_.Remove(address); } void OnGattDisconnected(tCONN_ID connection_id, tGATT_IF /*client_if*/, RawAddress remote_bda, - tGATT_DISCONN_REASON reason) { + tGATT_DISCONN_REASON /*reason*/) { VolumeControlDevice* device = volume_control_devices_.FindByConnId(connection_id); if (!device) { bluetooth::log::error("Skipping unknown device disconnect, connection_id={:#x}", @@ -838,9 +865,7 @@ public: bool notify = device->IsReady() || device->connecting_actively; device_cleanup_helper(device, notify); - if (reason != GATT_CONN_TERMINATE_LOCAL_HOST && device->connecting_actively) { - StartOpportunisticConnect(remote_bda); - } + StartOpportunisticConnect(remote_bda); } void RemoveDeviceFromOperationList(const RawAddress& addr) { @@ -1295,23 +1320,87 @@ public: void SetExtAudioInGainSetting(const RawAddress& address, uint8_t ext_input_id, int8_t gain_setting) override { std::vector<uint8_t> arg({(uint8_t)gain_setting}); - ext_audio_in_control_point_helper(address, ext_input_id, kVolumeInputControlPointOpcodeSetGain, - &arg); + bluetooth::log::info("{}, input_id={:#x}", address, ext_input_id); + + VolumeControlDevice* device = volume_control_devices_.FindByAddress(address); + if (!device) { + bluetooth::log::error("{}, no such device!", address); + callbacks_->OnExtAudioInSetGainSettingFailed(address, ext_input_id); + return; + } + + if (!device->ExtAudioInControlPointOperation( + ext_input_id, kVolumeInputControlPointOpcodeSetGain, &arg, + [](uint16_t connection_id, tGATT_STATUS status, uint16_t handle, uint16_t /*len*/, + const uint8_t* /*value*/, void* data) { + if (instance) { + instance->OnExtAudioInCPWrite(connection_id, status, handle, + kVolumeInputControlPointOpcodeSetGain, + PTR_TO_INT(data)); + } + }, + INT_TO_PTR(ext_input_id))) { + callbacks_->OnExtAudioInSetGainSettingFailed(address, ext_input_id); + } } void SetExtAudioInGainMode(const RawAddress& address, uint8_t ext_input_id, - bool automatic) override { - ext_audio_in_control_point_helper(address, ext_input_id, - automatic ? kVolumeInputControlPointOpcodeSetAutoGainMode - : kVolumeInputControlPointOpcodeSetManualGainMode, - nullptr); + bluetooth::aics::GainMode gain_mode) override { + bluetooth::log::info("{}, input_id={:#x} gain_mode={:#x}", address, ext_input_id, gain_mode); + + VolumeControlDevice* device = volume_control_devices_.FindByAddress(address); + if (!device) { + bluetooth::log::error("{}, no such device!", address); + callbacks_->OnExtAudioInSetGainModeFailed(address, ext_input_id); + return; + } + + if (!device->ExtAudioInControlPointOperation( + ext_input_id, + gain_mode == bluetooth::aics::GainMode::AUTOMATIC + ? kVolumeInputControlPointOpcodeSetAutoGainMode + : kVolumeInputControlPointOpcodeSetManualGainMode, + nullptr, + [](uint16_t connection_id, tGATT_STATUS status, uint16_t handle, uint16_t /*len*/, + const uint8_t* /*value*/, void* data) { + if (instance) { + instance->OnExtAudioInCPWrite(connection_id, status, handle, + kVolumeInputControlPointOpcodeSetAutoGainMode, + PTR_TO_INT(data)); + } + }, + INT_TO_PTR(ext_input_id))) { + callbacks_->OnExtAudioInSetGainModeFailed(address, ext_input_id); + } } - void SetExtAudioInGainMute(const RawAddress& address, uint8_t ext_input_id, bool mute) override { - ext_audio_in_control_point_helper( - address, ext_input_id, - mute ? kVolumeInputControlPointOpcodeMute : kVolumeInputControlPointOpcodeUnmute, - nullptr); + void SetExtAudioInMute(const RawAddress& address, uint8_t ext_input_id, + bluetooth::aics::Mute mute) override { + bluetooth::log::info("{}, input_id={:#x}, mute={:#x}", address, ext_input_id, mute); + + VolumeControlDevice* device = volume_control_devices_.FindByAddress(address); + if (!device) { + bluetooth::log::error("{}, no such device!", address); + callbacks_->OnExtAudioInSetMuteFailed(address, ext_input_id); + return; + } + + if (!device->ExtAudioInControlPointOperation( + ext_input_id, + mute == bluetooth::aics::Mute::MUTED ? kVolumeInputControlPointOpcodeMute + : kVolumeInputControlPointOpcodeUnmute, + nullptr, + [](uint16_t connection_id, tGATT_STATUS status, uint16_t handle, uint16_t /*len*/, + const uint8_t* /*value*/, void* data) { + if (instance) { + instance->OnExtAudioInCPWrite(connection_id, status, handle, + kVolumeInputControlPointOpcodeMute, + PTR_TO_INT(data)); + } + }, + INT_TO_PTR(ext_input_id))) { + callbacks_->OnExtAudioInSetMuteFailed(address, ext_input_id); + } } void CleanUp() { @@ -1380,27 +1469,6 @@ private: INT_TO_PTR(operation_id)); } - void ext_audio_in_control_point_helper(const RawAddress& address, uint8_t ext_input_id, - uint8_t opcode, const std::vector<uint8_t>* arg) { - bluetooth::log::info("{}, input_id={:#x}, opcode {:#x}", address, ext_input_id, opcode); - - VolumeControlDevice* device = volume_control_devices_.FindByAddress(address); - if (!device) { - bluetooth::log::error("{}, no such device!", address); - return; - } - - device->ExtAudioInControlPointOperation( - ext_input_id, opcode, arg, - [](uint16_t connection_id, tGATT_STATUS status, uint16_t handle, uint16_t /*len*/, - const uint8_t* /*value*/, void* /*data*/) { - if (instance) { - instance->OnExtAudioInCPWrite(connection_id, status, handle); - } - }, - nullptr); - } - void ext_audio_out_control_point_helper(const RawAddress& address, uint8_t ext_output_id, uint8_t opcode, const std::vector<uint8_t>* arg) { bluetooth::log::info("{} id={:#x} op={:#x}", address, ext_output_id, opcode); diff --git a/system/bta/vc/vc_test.cc b/system/bta/vc/vc_test.cc index 8b69fb3c86..c9c6adc425 100644 --- a/system/bta/vc/vc_test.cc +++ b/system/bta/vc/vc_test.cc @@ -59,6 +59,7 @@ namespace { using base::Bind; using base::Unretained; +using bluetooth::aics::GainMode; using bluetooth::aics::Mute; using bluetooth::vc::ConnectionState; using bluetooth::vc::VolumeControlCallbacks; @@ -106,19 +107,27 @@ public: (const RawAddress& address, uint8_t ext_output_id, std::string descr), (override)); MOCK_METHOD((void), OnExtAudioInStateChanged, (const RawAddress& address, uint8_t ext_input_id, int8_t gain_setting, Mute mute, - uint8_t gain_mode_auto), + GainMode gain_mode), (override)); + MOCK_METHOD((void), OnExtAudioInSetGainSettingFailed, + (const RawAddress& address, uint8_t ext_input_id), (override)); + MOCK_METHOD((void), OnExtAudioInSetMuteFailed, (const RawAddress& address, uint8_t ext_input_id), + (override)); + MOCK_METHOD((void), OnExtAudioInSetGainModeFailed, + (const RawAddress& address, uint8_t ext_input_id), (override)); MOCK_METHOD((void), OnExtAudioInStatusChanged, (const RawAddress& address, uint8_t ext_input_id, VolumeInputStatus status), (override)); MOCK_METHOD((void), OnExtAudioInTypeChanged, (const RawAddress& address, uint8_t ext_input_id, VolumeInputType type), (override)); - MOCK_METHOD((void), OnExtAudioInGainPropsChanged, + MOCK_METHOD((void), OnExtAudioInGainSettingPropertiesChanged, (const RawAddress& address, uint8_t ext_input_id, uint8_t unit, int8_t min, int8_t max), (override)); MOCK_METHOD((void), OnExtAudioInDescriptionChanged, - (const RawAddress& address, uint8_t ext_input_id, std::string descr), (override)); + (const RawAddress& address, uint8_t ext_input_id, std::string description, + bool is_writable), + (override)); }; class VolumeControlTest : public ::testing::Test { @@ -572,7 +581,7 @@ protected: } void TestRemove(const RawAddress& address, uint16_t conn_id) { - EXPECT_CALL(gatt_interface, CancelOpen(gatt_if, address, false)); + EXPECT_CALL(gatt_interface, CancelOpen(gatt_if, address, true)); if (conn_id) { EXPECT_CALL(gatt_interface, Close(conn_id)); } else { @@ -899,7 +908,7 @@ TEST_F(VolumeControlTest, test_reconnect_after_timeout) { // Disconnect not connected device - upper layer times out and needs a // disconnection event to leave the transient Connecting state EXPECT_CALL(callbacks, OnConnectionState(ConnectionState::DISCONNECTED, address)); - EXPECT_CALL(gatt_interface, CancelOpen(gatt_if, address, false)).Times(0); + EXPECT_CALL(gatt_interface, CancelOpen(gatt_if, address, _)).Times(0); TestDisconnect(address, 0); // Above the device was not connected and we got Disconnect request from the @@ -984,6 +993,7 @@ TEST_F(VolumeControlTest, test_disconnected_while_autoconnect) { TestAppRegister(); TestAddFromStorage(test_address); GetConnectedEvent(test_address, 1); + Mock::VerifyAndClearExpectations(&gatt_interface); // autoconnect - don't indicate disconnection EXPECT_CALL(callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)).Times(0); GetDisconnectedEvent(test_address, 1); @@ -1337,20 +1347,29 @@ TEST_F(VolumeControlCallbackTest, test_volume_state_changed_malformed) { TEST_F(VolumeControlCallbackTest, audio_input_state_changed__invalid_mute__is_rejected) { uint8_t invalid_mute = 0x03; - std::vector<uint8_t> value({0x03, invalid_mute, 0x02, 0x04}); + std::vector<uint8_t> value({0x03, invalid_mute, (uint8_t)GainMode::MANUAL, 0x04}); + EXPECT_CALL(callbacks, OnExtAudioInStateChanged(_, _, _, _, _)).Times(0); + GetNotificationEvent(0x0032, value); +} + +TEST_F(VolumeControlCallbackTest, audio_input_state_changed__invalid_gain_mode__is_rejected) { + uint8_t invalid_gain_mode = 0x06; + std::vector<uint8_t> value({0x03, (uint8_t)Mute::MUTED, invalid_gain_mode, 0x04}); EXPECT_CALL(callbacks, OnExtAudioInStateChanged(_, _, _, _, _)).Times(0); GetNotificationEvent(0x0032, value); } TEST_F(VolumeControlCallbackTest, test_audio_input_state_changed__muted) { - std::vector<uint8_t> value({0x03, (uint8_t)Mute::MUTED, 0x02, 0x04}); - EXPECT_CALL(callbacks, OnExtAudioInStateChanged(test_address, _, 0x03, Mute::MUTED, 0x02)); + std::vector<uint8_t> value({0x03, (uint8_t)Mute::MUTED, (uint8_t)GainMode::MANUAL, 0x04}); + EXPECT_CALL(callbacks, + OnExtAudioInStateChanged(test_address, _, 0x03, Mute::MUTED, GainMode::MANUAL)); GetNotificationEvent(0x0032, value); } TEST_F(VolumeControlCallbackTest, test_audio_input_state_changed__disabled) { - std::vector<uint8_t> value({0x03, (uint8_t)Mute::DISABLED, 0x02, 0x04}); - EXPECT_CALL(callbacks, OnExtAudioInStateChanged(test_address, _, 0x03, Mute::DISABLED, 0x02)); + std::vector<uint8_t> value({0x03, (uint8_t)Mute::DISABLED, (uint8_t)GainMode::MANUAL, 0x04}); + EXPECT_CALL(callbacks, + OnExtAudioInStateChanged(test_address, _, 0x03, Mute::DISABLED, GainMode::MANUAL)); GetNotificationEvent(0x0032, value); } @@ -1364,12 +1383,14 @@ TEST_F(VolumeControlCallbackTest, test_audio_input_state_changed_malformed) { TEST_F(VolumeControlCallbackTest, test_audio_gain_props_changed) { std::vector<uint8_t> value({0x03, 0x01, 0x02}); - EXPECT_CALL(callbacks, OnExtAudioInGainPropsChanged(test_address, _, 0x03, 0x01, 0x02)); + EXPECT_CALL(callbacks, + OnExtAudioInGainSettingPropertiesChanged(test_address, _, 0x03, 0x01, 0x02)); GetNotificationEvent(0x0055, value); } TEST_F(VolumeControlCallbackTest, test_audio_gain_props_changed_malformed) { - EXPECT_CALL(callbacks, OnExtAudioInGainPropsChanged(test_address, _, _, _, _)).Times(0); + EXPECT_CALL(callbacks, OnExtAudioInGainSettingPropertiesChanged(test_address, _, _, _, _)) + .Times(0); std::vector<uint8_t> too_short({0x03, 0x01}); GetNotificationEvent(0x0055, too_short); std::vector<uint8_t> too_long({0x03, 0x01, 0x02, 0x03}); @@ -1392,9 +1413,9 @@ TEST_F(VolumeControlCallbackTest, test_audio_input_status_changed_malformed) { } TEST_F(VolumeControlCallbackTest, test_audio_input_description_changed) { - std::string descr = "SPDIF"; - std::vector<uint8_t> value(descr.begin(), descr.end()); - EXPECT_CALL(callbacks, OnExtAudioInDescriptionChanged(test_address, _, descr)); + std::string description = "SPDIF"; + std::vector<uint8_t> value(description.begin(), description.end()); + EXPECT_CALL(callbacks, OnExtAudioInDescriptionChanged(test_address, _, description, _)); GetNotificationEvent(0x005e, value); } @@ -1489,8 +1510,9 @@ TEST_F(VolumeControlValueGetTest, test_get_ext_audio_out_description) { TEST_F(VolumeControlValueGetTest, test_get_ext_audio_in_state) { VolumeControl::Get()->GetExtAudioInState(test_address, 1); EXPECT_TRUE(cb); - std::vector<uint8_t> value({0x01, (uint8_t)Mute::NOT_MUTED, 0x02, 0x03}); - EXPECT_CALL(callbacks, OnExtAudioInStateChanged(test_address, 1, 0x01, Mute::NOT_MUTED, 0x02)); + std::vector<uint8_t> value({0x01, (uint8_t)Mute::NOT_MUTED, (uint8_t)GainMode::MANUAL, 0x03}); + EXPECT_CALL(callbacks, + OnExtAudioInStateChanged(test_address, 1, 0x01, Mute::NOT_MUTED, GainMode::MANUAL)); cb(conn_id, GATT_SUCCESS, handle, (uint16_t)value.size(), value.data(), cb_data); } @@ -1507,16 +1529,17 @@ TEST_F(VolumeControlValueGetTest, test_get_ext_audio_in_gain_props) { VolumeControl::Get()->GetExtAudioInGainProps(test_address, 0); EXPECT_TRUE(cb); std::vector<uint8_t> value({0x01, 0x02, 0x03}); - EXPECT_CALL(callbacks, OnExtAudioInGainPropsChanged(test_address, 0, 0x01, 0x02, 0x03)); + EXPECT_CALL(callbacks, + OnExtAudioInGainSettingPropertiesChanged(test_address, 0, 0x01, 0x02, 0x03)); cb(conn_id, GATT_SUCCESS, handle, (uint16_t)value.size(), value.data(), cb_data); } TEST_F(VolumeControlValueGetTest, test_get_ext_audio_in_description) { VolumeControl::Get()->GetExtAudioInDescription(test_address, 1); EXPECT_TRUE(cb); - std::string descr = "AUX-IN"; - std::vector<uint8_t> value(descr.begin(), descr.end()); - EXPECT_CALL(callbacks, OnExtAudioInDescriptionChanged(test_address, 1, descr)); + std::string description = "AUX-IN"; + std::vector<uint8_t> value(description.begin(), description.end()); + EXPECT_CALL(callbacks, OnExtAudioInDescriptionChanged(test_address, 1, description, _)); cb(conn_id, GATT_SUCCESS, handle, (uint16_t)value.size(), value.data(), cb_data); } @@ -1868,21 +1891,21 @@ TEST_F(VolumeControlValueSetTest, test_set_ext_audio_in_gain_setting) { } TEST_F(VolumeControlValueSetTest, test_set_ext_audio_in_gain_mode) { - std::vector<uint8_t> mode_manual({0x04, 0x00}); + std::vector<uint8_t> mode_manual({0x04, 0x00}); // 0x04 is the opcode for Manual EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x005c, mode_manual, GATT_WRITE, _, _)); - VolumeControl::Get()->SetExtAudioInGainMode(test_address, 1, false); - std::vector<uint8_t> mode_automatic({0x05, 0x00}); + VolumeControl::Get()->SetExtAudioInGainMode(test_address, 1, GainMode::MANUAL); + std::vector<uint8_t> mode_automatic({0x05, 0x00}); // 0x05 is the opcode for Automatic EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x005c, mode_automatic, GATT_WRITE, _, _)); - VolumeControl::Get()->SetExtAudioInGainMode(test_address, 1, true); + VolumeControl::Get()->SetExtAudioInGainMode(test_address, 1, GainMode::AUTOMATIC); } TEST_F(VolumeControlValueSetTest, test_set_ext_audio_in_gain_mute) { - std::vector<uint8_t> mute({0x03, 0x00}); + std::vector<uint8_t> mute({0x03, 0x00}); // 0x03 is the opcode for Mute EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x005c, mute, GATT_WRITE, _, _)); - VolumeControl::Get()->SetExtAudioInGainMute(test_address, 1, true); - std::vector<uint8_t> unmute({0x02, 0x00}); + VolumeControl::Get()->SetExtAudioInMute(test_address, 1, Mute::MUTED); + std::vector<uint8_t> unmute({0x02, 0x00}); // 0x02 is the opcode for UnMute EXPECT_CALL(gatt_queue, WriteCharacteristic(conn_id, 0x005c, unmute, GATT_WRITE, _, _)); - VolumeControl::Get()->SetExtAudioInGainMute(test_address, 1, false); + VolumeControl::Get()->SetExtAudioInMute(test_address, 1, Mute::NOT_MUTED); } class VolumeControlCsis : public VolumeControlTest { diff --git a/system/btcore/Android.bp b/system/btcore/Android.bp index 96da5abf57..dc6df095ad 100644 --- a/system/btcore/Android.bp +++ b/system/btcore/Android.bp @@ -110,6 +110,7 @@ cc_test { "libbluetooth_log", "libbtcore", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libosi", ], host_supported: true, diff --git a/system/btcore/fuzzer/Android.bp b/system/btcore/fuzzer/Android.bp index 746a3b31b5..c930086694 100644 --- a/system/btcore/fuzzer/Android.bp +++ b/system/btcore/fuzzer/Android.bp @@ -38,6 +38,7 @@ cc_defaults { "libbt-common", "libbtcore", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "liblog", "libmodpb64", diff --git a/system/btcore/include/property.h b/system/btcore/include/property.h index 17d2973b53..f8e06150ad 100644 --- a/system/btcore/include/property.h +++ b/system/btcore/include/property.h @@ -18,12 +18,12 @@ #pragma once -#include <bluetooth/uuid.h> #include <hardware/bluetooth.h> #include <stdint.h> #include <stdlib.h> #include "btcore/include/device_class.h" +#include "types/bluetooth/uuid.h" #include "types/raw_address.h" // Copies an array of consecutive properties of |count| to a newly diff --git a/system/btif/Android.bp b/system/btif/Android.bp index fd27f850ba..ad98a7dcc4 100644 --- a/system/btif/Android.bp +++ b/system/btif/Android.bp @@ -55,7 +55,6 @@ cc_library_static { "packages/modules/Bluetooth/system/gd", "packages/modules/Bluetooth/system/include", "packages/modules/Bluetooth/system/stack/include", - "packages/modules/Bluetooth/system/types", ], srcs: ["src/btif_jni_task.cc"], static_libs: [ @@ -403,6 +402,7 @@ cc_test { "libbluetooth_gd", "libbluetooth_log", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libosi", ], shared_libs: [ @@ -437,6 +437,7 @@ cc_test { "libbluetooth-types", "libbluetooth_log", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libosi", ], shared_libs: [ diff --git a/system/btif/BUILD.gn b/system/btif/BUILD.gn index 167ac3bcfb..519237997a 100644 --- a/system/btif/BUILD.gn +++ b/system/btif/BUILD.gn @@ -97,7 +97,6 @@ static_library("btif") { "//bt/system/bta/aics/include", "//bt/system/bta/include", "//bt/system/bta/sys", - "//bt/system/device/include", "//bt/system/embdrv/sbc/encoder/include", "//bt/system/embdrv/sbc/decoder/include", "//bt/system/gd", diff --git a/system/btif/avrcp/avrcp_service.h b/system/btif/avrcp/avrcp_service.h index 5c4974ac97..581852194e 100644 --- a/system/btif/avrcp/avrcp_service.h +++ b/system/btif/avrcp/avrcp_service.h @@ -24,7 +24,7 @@ #include "osi/include/properties.h" #include "profile/avrcp/avrcp_sdp_service.h" #include "profile/avrcp/connection_handler.h" -#include "raw_address.h" +#include "types/raw_address.h" namespace bluetooth { namespace avrcp { diff --git a/system/btif/co/bta_pan_co.cc b/system/btif/co/bta_pan_co.cc index 0bdcae371e..558149239d 100644 --- a/system/btif/co/bta_pan_co.cc +++ b/system/btif/co/bta_pan_co.cc @@ -139,7 +139,6 @@ void bta_pan_co_tx_path(uint16_t handle, uint8_t app_id) { p_buf->len, ext, forward); osi_free(p_buf); } - } while (p_buf != NULL); } diff --git a/system/btif/include/btif_bqr.h b/system/btif/include/btif_bqr.h index 909335b411..38bfa8badc 100644 --- a/system/btif/include/btif_bqr.h +++ b/system/btif/include/btif_bqr.h @@ -200,8 +200,10 @@ enum BqrQualityReportId : uint8_t { QUALITY_REPORT_ID_A2DP_AUDIO_CHOPPY = 0x03, QUALITY_REPORT_ID_SCO_VOICE_CHOPPY = 0x04, QUALITY_REPORT_ID_ROOT_INFLAMMATION = 0x05, + QUALITY_REPORT_ID_ENERGY_MONITOR = 0x06, QUALITY_REPORT_ID_LE_AUDIO_CHOPPY = 0x07, QUALITY_REPORT_ID_CONNECT_FAIL = 0x08, + QUALITY_REPORT_ID_RF_STATS = 0x09, QUALITY_REPORT_ID_VENDOR_SPECIFIC_QUALITY = 0x10, QUALITY_REPORT_ID_LMP_LL_MESSAGE_TRACE = 0x11, QUALITY_REPORT_ID_BT_SCHEDULING_TRACE = 0x12, @@ -330,6 +332,112 @@ typedef struct { const uint8_t* vendor_specific_parameter; } BqrLinkQualityEvent; +// Energy Monitor BQR event +typedef struct { + // Quality report ID. + uint8_t quality_report_id; + // Average current consumption of all activities consumed by the controller (mA) + uint16_t avg_current_consume; + // Total time in the idle (low power states, sleep) state. (ms) + uint32_t idle_total_time; + // Indicates how many times the controller enters the idle state. + uint32_t idle_state_enter_count; + // Total time in the active (inquiring, paging, ACL/SCO/eSCO/BIS/CIS traffic, processing any task) + // state. (ms) + uint32_t active_total_time; + // Indicates how many times the controller enters the active states. + uint32_t active_state_enter_count; + // Total time in the BR/EDR specific Tx(Transmitting for ACL/SCO/eSCO traffic)state (ms) + uint32_t bredr_tx_total_time; + // Indicates how many times the controller enters the BR/EDR specific Tx state. + uint32_t bredr_tx_state_enter_count; + // Average Tx power level of all the BR/EDR link(s) (dBm) + uint8_t bredr_tx_avg_power_lv; + // Total time in the BR/EDR specific Rx (Receiving from ACL/SCO/eSCO traffic) state. (ms) + uint32_t bredr_rx_total_time; + // Indicates how many times the controller enters the BR/EDR specific Rx state. (ms) + uint32_t bredr_rx_state_enter_count; + // Total time in the LE specific Tx (Transmitting for either ACL/BIS/CIS or LE advertising + // traffic) state (ms) + uint32_t le_tx_total_time; + // Indicates how many times the controller enters theLE specific Tx state. + uint32_t le_tx_state_enter_count; + // Average Tx power level of all the LE link(s) (dBm) + uint8_t le_tx_avg_power_lv; + // Total time in the LE specific Rx (Receiving from either ACL/BIS/CIS or LE scanning traffic) + // state. (ms) + uint32_t le_rx_total_time; + // Indicates how many times the controller enters the LE specific Rx state + uint32_t le_rx_state_enter_count; + // The total time duration to collect power related information (ms) + uint32_t tm_period; + // The time duration of RX active in one chain + uint32_t rx_active_one_chain_time; + // The time duration of RX active in two chain + uint32_t rx_active_two_chain_time; + // The time duration of internal TX active in one chain + uint32_t tx_ipa_active_one_chain_time; + // The time duration of internal TX active in two chain + uint32_t tx_ipa_active_two_chain_time; + // The time duration of external TX active in one chain + uint32_t tx_epa_active_one_chain_time; + // The time duration of external TX active in two chain + uint32_t tx_epa_active_two_chain_time; +} __attribute__((__packed__)) BqrEnergyMonitorEvent; + +static constexpr uint8_t kEnergyMonitorParamTotalLen = sizeof(BqrEnergyMonitorEvent); + +// RF Stats BQR event +typedef struct { + // Quality report ID. + uint8_t quality_report_id; + // Extension for Further usage = 0x01 for BQRv6 + uint8_t ext_info; + // time period (ms) + uint32_t tm_period; + // Packet counter of iPA BF + uint32_t tx_pw_ipa_bf; + // Packet counter of ePA BF + uint32_t tx_pw_epa_bf; + // Packet counter of iPA Div + uint32_t tx_pw_ipa_div; + // Packet counter of ePA Div + uint32_t tx_pw_epa_div; + // Packet counter of RSSI chain > -50 dBm + uint32_t rssi_ch_50; + // Packet counter of RSSI chain between -50 dBm ~ >-55 dBm + uint32_t rssi_ch_50_55; + // Packet counter of RSSI chain between -55 dBm ~ >-60 dBm + uint32_t rssi_ch_55_60; + // Packet counter of RSSI chain between -60 dBm ~ >-65 dBm + uint32_t rssi_ch_60_65; + // Packet counter of RSSI chain between -65 dBm ~ >-70 dBm + uint32_t rssi_ch_65_70; + // Packet counter of RSSI chain between -70 dBm ~ >-75 dBm + uint32_t rssi_ch_70_75; + // Packet counter of RSSI chain between -75 dBm ~ >-80 dBm + uint32_t rssi_ch_75_80; + // Packet counter of RSSI chain between -80 dBm ~ >-85 dBm + uint32_t rssi_ch_80_85; + // Packet counter of RSSI chain between -85 dBm ~ >-90 dBm + uint32_t rssi_ch_85_90; + // Packet counter of RSSI chain < -90 dBm + uint32_t rssi_ch_90; + // Packet counter of RSSI delta < 2 dBm + uint32_t rssi_delta_2_down; + // Packet counter of RSSI delta between 2 dBm ~ 5 dBm + uint32_t rssi_delta_2_5; + // Packet counter of RSSI delta between 5 dBm ~ 8 dB + uint32_t rssi_delta_5_8; + // Packet counter of RSSI delta between 8 dBm ~ 11 dBm + uint32_t rssi_delta_8_11; + // Packet counter of RSSI delta > 11 dBm + uint32_t rssi_delta_11_up; +} __attribute__((__packed__)) BqrRFStatsEvent; + +// Total length of all parameters of the RF Stats event +static constexpr uint8_t kRFStatsParamTotalLen = sizeof(BqrRFStatsEvent); + // Log dump related BQR event typedef struct { // Quality report ID. @@ -348,6 +456,20 @@ public: // @param length Total length of all parameters contained in the sub-event. // @param p_param_buf A pointer to the parameters contained in the sub-event. void ParseBqrLinkQualityEvt(uint8_t length, const uint8_t* p_param_buf); + // Parse the Energy Monitor BQR event. + // + // @param length Total length of all parameters contained in the sub-event. + // @param p_param_buf A pointer to the parameters contained in the sub-event. + // + // @return true if the event was parsed successfully, false otherwise. + bool ParseBqrEnergyMonitorEvt(uint8_t length, const uint8_t* p_param_buf); + // Parse the RF Stats BQR event. + // + // @param length Total length of all parameters contained in the sub-event. + // @param p_param_buf A pointer to the parameters contained in the sub-event. + // + // @return true if the event was parsed successfully, false otherwise. + bool ParseBqrRFStatsEvt(uint8_t length, const uint8_t* p_param_buf); // Write the LMP/LL message trace to the log file. // // @param fd The File Descriptor of the log file. @@ -372,6 +494,10 @@ public: virtual ~BqrVseSubEvt() = default; // Link Quality related BQR event BqrLinkQualityEvent bqr_link_quality_event_ = {}; + // Energy Monitor BQR event + BqrEnergyMonitorEvent bqr_energy_monitor_event_ = {}; + // RF Stats BQR event + BqrRFStatsEvent bqr_rf_stats_event_ = {}; // Log Dump related BQR event BqrLogDumpEvent bqr_log_dump_event_ = {}; // Local wall clock timestamp of receiving BQR VSE sub-event diff --git a/system/btif/include/btif_keystore.h b/system/btif/include/btif_keystore.h index 460f3b8a4a..83133a6eb8 100644 --- a/system/btif/include/btif_keystore.h +++ b/system/btif/include/btif_keystore.h @@ -22,4 +22,4 @@ namespace bluetooth_keystore { BluetoothKeystoreInterface* getBluetoothKeystoreInterface(); } // namespace bluetooth_keystore -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/btif/include/btif_metrics_logging.h b/system/btif/include/btif_metrics_logging.h index 00e3a33772..d68eddce5e 100644 --- a/system/btif/include/btif_metrics_logging.h +++ b/system/btif/include/btif_metrics_logging.h @@ -66,4 +66,4 @@ int save_metric_id_from_metric_id_allocator(const RawAddress&); void forget_device_from_metric_id_allocator(const RawAddress&); -bool is_valid_id_from_metric_id_allocator(const int id);
\ No newline at end of file +bool is_valid_id_from_metric_id_allocator(const int id); diff --git a/system/btif/include/btif_profile_storage.h b/system/btif/include/btif_profile_storage.h index 1aaddd2c24..6459c45b99 100644 --- a/system/btif/include/btif_profile_storage.h +++ b/system/btif/include/btif_profile_storage.h @@ -18,12 +18,12 @@ #pragma once -#include <bluetooth/uuid.h> #include <hardware/bluetooth.h> #include <vector> #include "types/ble_address_with_type.h" +#include "types/bluetooth/uuid.h" #include "types/raw_address.h" /******************************************************************************* diff --git a/system/btif/include/btif_sock_sdp.h b/system/btif/include/btif_sock_sdp.h index 44d765e417..b849828f98 100644 --- a/system/btif/include/btif_sock_sdp.h +++ b/system/btif/include/btif_sock_sdp.h @@ -19,11 +19,12 @@ #ifndef BTIF_SOCK_SDP_H #define BTIF_SOCK_SDP_H -#include <bluetooth/uuid.h> #include <stdbool.h> #include <stdint.h> #include <string.h> +#include "types/bluetooth/uuid.h" + static const bluetooth::Uuid UUID_OBEX_OBJECT_PUSH = bluetooth::Uuid::From16Bit(0x1105); static const bluetooth::Uuid UUID_PBAP_PCE = bluetooth::Uuid::From16Bit(0x112E); static const bluetooth::Uuid UUID_PBAP_PSE = bluetooth::Uuid::From16Bit(0x112F); diff --git a/system/btif/include/btif_storage.h b/system/btif/include/btif_storage.h index 9e4277a3cf..067e828781 100644 --- a/system/btif/include/btif_storage.h +++ b/system/btif/include/btif_storage.h @@ -19,7 +19,6 @@ #ifndef SYSTEM_BTIF_INCLUDE_BTIF_STORAGE_H_ #define SYSTEM_BTIF_INCLUDE_BTIF_STORAGE_H_ -#include <bluetooth/uuid.h> #include <hardware/bluetooth.h> #include <string> @@ -29,6 +28,7 @@ #include "stack/include/bt_octets.h" #include "stack/include/btm_sec_api_types.h" #include "types/ble_address_with_type.h" +#include "types/bluetooth/uuid.h" #include "types/raw_address.h" /******************************************************************************* diff --git a/system/btif/src/btif_a2dp_source.cc b/system/btif/src/btif_a2dp_source.cc index 3f3bc5a479..7ebe304fec 100644 --- a/system/btif/src/btif_a2dp_source.cc +++ b/system/btif/src/btif_a2dp_source.cc @@ -40,7 +40,6 @@ #include "a2dp_codec_api.h" #include "audio_hal_interface/a2dp_encoding.h" #include "avdt_api.h" -#include "bt_transport.h" #include "bta_av_api.h" #include "bta_av_ci.h" #include "btif_av.h" @@ -64,6 +63,7 @@ #include "stack/include/btm_client_interface.h" #include "stack/include/btm_status.h" #include "stack/include/main_thread.h" +#include "types/bt_transport.h" #include "types/raw_address.h" #ifdef __ANDROID__ @@ -364,6 +364,7 @@ class A2dpAudioPort : public bluetooth::audio::a2dp::BluetoothAudioPort { // Check if the stream has already been started. if (btif_av_stream_started_ready(A2dpType::kSource)) { + log::verbose("stream is already started"); return BluetoothAudioStatus::SUCCESS; } @@ -386,6 +387,7 @@ class A2dpAudioPort : public bluetooth::audio::a2dp::BluetoothAudioPort { // Check if the stream is already suspended. if (!btif_av_stream_started_ready(A2dpType::kSource)) { btif_av_clear_remote_suspend_flag(A2dpType::kSource); + log::verbose("stream is already suspended"); return BluetoothAudioStatus::SUCCESS; } @@ -395,6 +397,20 @@ class A2dpAudioPort : public bluetooth::audio::a2dp::BluetoothAudioPort { return BluetoothAudioStatus::PENDING; } + BluetoothAudioStatus StopStream() const override { + // Check if the stream is already suspended. + if (!btif_av_stream_started_ready(A2dpType::kSource)) { + btif_av_clear_remote_suspend_flag(A2dpType::kSource); + log::verbose("stream is already stopped"); + return BluetoothAudioStatus::SUCCESS; + } + + // Post stop event. The stop request is pending, but completion is not + // notified to the HAL. + btif_av_stream_stop(RawAddress::kEmpty); + return BluetoothAudioStatus::PENDING; + } + BluetoothAudioStatus SetLatencyMode(bool low_latency) const override { btif_av_set_low_latency(low_latency); return BluetoothAudioStatus::SUCCESS; diff --git a/system/btif/src/btif_av.cc b/system/btif/src/btif_av.cc index 8fa008acdd..ce8d74fb8b 100644 --- a/system/btif/src/btif_av.cc +++ b/system/btif/src/btif_av.cc @@ -2407,6 +2407,14 @@ bool BtifAvStateMachine::StateOpened::ProcessEvent(uint32_t event, void* p_data) peer_.PeerAddress()); std::promise<void> peer_ready_promise; std::future<void> peer_ready_future = peer_ready_promise.get_future(); + + if (com::android::bluetooth::flags::a2dp_clear_pending_start_on_session_restart()) { + // The stream may not be restarted without an explicit request from the + // Bluetooth Audio HAL. Any start request that was pending before the + // reconfiguration is invalidated when the session is ended. + peer_.ClearFlags(BtifAvPeer::kFlagPendingStart); + } + btif_a2dp_source_start_session(peer_.PeerAddress(), std::move(peer_ready_promise)); } if (peer_.CheckFlags(BtifAvPeer::kFlagPendingStart)) { diff --git a/system/btif/src/btif_bqr.cc b/system/btif/src/btif_bqr.cc index 765e7a7384..37ce06a935 100644 --- a/system/btif/src/btif_bqr.cc +++ b/system/btif/src/btif_bqr.cc @@ -15,6 +15,7 @@ */ #include <bluetooth/log.h> +#include <com_android_bluetooth_flags.h> #include <fcntl.h> #ifdef __ANDROID__ #include <statslog_bt.h> @@ -69,7 +70,8 @@ class BluetoothQualityReportInterfaceImpl; std::unique_ptr<BluetoothQualityReportInterface> bluetoothQualityReportInstance; namespace { -common::PostableContext* to_bind_ = nullptr; +static std::recursive_mutex life_cycle_guard_; +static common::PostableContext* to_bind_ = nullptr; } void BqrVseSubEvt::ParseBqrLinkQualityEvt(uint8_t length, const uint8_t* p_param_buf) { @@ -154,6 +156,79 @@ void BqrVseSubEvt::ParseBqrLinkQualityEvt(uint8_t length, const uint8_t* p_param localtime_r(&now, &tm_timestamp_); } +bool BqrVseSubEvt::ParseBqrEnergyMonitorEvt(uint8_t length, const uint8_t* p_param_buf) { + if (length < kEnergyMonitorParamTotalLen) { + log::fatal( + "Parameter total length: {} is abnormal. It shall be not shorter than: " + "{}", + length, kEnergyMonitorParamTotalLen); + return false; + } + + STREAM_TO_UINT8(bqr_energy_monitor_event_.quality_report_id, p_param_buf); + bqr_link_quality_event_.quality_report_id = bqr_energy_monitor_event_.quality_report_id; + STREAM_TO_UINT16(bqr_energy_monitor_event_.avg_current_consume, p_param_buf); + STREAM_TO_UINT32(bqr_energy_monitor_event_.idle_total_time, p_param_buf); + STREAM_TO_UINT32(bqr_energy_monitor_event_.idle_state_enter_count, p_param_buf); + STREAM_TO_UINT32(bqr_energy_monitor_event_.active_total_time, p_param_buf); + STREAM_TO_UINT32(bqr_energy_monitor_event_.active_state_enter_count, p_param_buf); + STREAM_TO_UINT32(bqr_energy_monitor_event_.bredr_tx_total_time, p_param_buf); + STREAM_TO_UINT32(bqr_energy_monitor_event_.bredr_tx_state_enter_count, p_param_buf); + STREAM_TO_UINT8(bqr_energy_monitor_event_.bredr_tx_avg_power_lv, p_param_buf); + STREAM_TO_UINT32(bqr_energy_monitor_event_.bredr_rx_total_time, p_param_buf); + STREAM_TO_UINT32(bqr_energy_monitor_event_.bredr_rx_state_enter_count, p_param_buf); + STREAM_TO_UINT32(bqr_energy_monitor_event_.le_tx_total_time, p_param_buf); + STREAM_TO_UINT32(bqr_energy_monitor_event_.le_tx_state_enter_count, p_param_buf); + STREAM_TO_UINT8(bqr_energy_monitor_event_.le_tx_avg_power_lv, p_param_buf); + STREAM_TO_UINT32(bqr_energy_monitor_event_.le_rx_total_time, p_param_buf); + STREAM_TO_UINT32(bqr_energy_monitor_event_.le_rx_state_enter_count, p_param_buf); + STREAM_TO_UINT32(bqr_energy_monitor_event_.tm_period, p_param_buf); + STREAM_TO_UINT32(bqr_energy_monitor_event_.rx_active_one_chain_time, p_param_buf); + STREAM_TO_UINT32(bqr_energy_monitor_event_.rx_active_two_chain_time, p_param_buf); + STREAM_TO_UINT32(bqr_energy_monitor_event_.tx_ipa_active_one_chain_time, p_param_buf); + STREAM_TO_UINT32(bqr_energy_monitor_event_.tx_ipa_active_two_chain_time, p_param_buf); + STREAM_TO_UINT32(bqr_energy_monitor_event_.tx_epa_active_one_chain_time, p_param_buf); + STREAM_TO_UINT32(bqr_energy_monitor_event_.tx_epa_active_two_chain_time, p_param_buf); + return true; +} + +bool BqrVseSubEvt::ParseBqrRFStatsEvt(uint8_t length, const uint8_t* p_param_buf) { + if (length < kRFStatsParamTotalLen) { + log::fatal( + "Parameter total length: {} is abnormal. It shall be not shorter than: " + "{}", + length, kRFStatsParamTotalLen); + return false; + } + + STREAM_TO_UINT8(bqr_rf_stats_event_.quality_report_id, p_param_buf); + bqr_link_quality_event_.quality_report_id = bqr_rf_stats_event_.quality_report_id; + STREAM_TO_UINT8(bqr_rf_stats_event_.ext_info, p_param_buf); + STREAM_TO_UINT32(bqr_rf_stats_event_.tm_period, p_param_buf); + STREAM_TO_UINT32(bqr_rf_stats_event_.tx_pw_ipa_bf, p_param_buf); + STREAM_TO_UINT32(bqr_rf_stats_event_.tx_pw_epa_bf, p_param_buf); + STREAM_TO_UINT32(bqr_rf_stats_event_.tx_pw_ipa_div, p_param_buf); + STREAM_TO_UINT32(bqr_rf_stats_event_.tx_pw_epa_div, p_param_buf); + + STREAM_TO_UINT32(bqr_rf_stats_event_.rssi_ch_50, p_param_buf); + STREAM_TO_UINT32(bqr_rf_stats_event_.rssi_ch_50_55, p_param_buf); + STREAM_TO_UINT32(bqr_rf_stats_event_.rssi_ch_55_60, p_param_buf); + STREAM_TO_UINT32(bqr_rf_stats_event_.rssi_ch_60_65, p_param_buf); + STREAM_TO_UINT32(bqr_rf_stats_event_.rssi_ch_65_70, p_param_buf); + STREAM_TO_UINT32(bqr_rf_stats_event_.rssi_ch_70_75, p_param_buf); + STREAM_TO_UINT32(bqr_rf_stats_event_.rssi_ch_75_80, p_param_buf); + STREAM_TO_UINT32(bqr_rf_stats_event_.rssi_ch_80_85, p_param_buf); + STREAM_TO_UINT32(bqr_rf_stats_event_.rssi_ch_85_90, p_param_buf); + STREAM_TO_UINT32(bqr_rf_stats_event_.rssi_ch_90, p_param_buf); + + STREAM_TO_UINT32(bqr_rf_stats_event_.rssi_delta_2_down, p_param_buf); + STREAM_TO_UINT32(bqr_rf_stats_event_.rssi_delta_2_5, p_param_buf); + STREAM_TO_UINT32(bqr_rf_stats_event_.rssi_delta_5_8, p_param_buf); + STREAM_TO_UINT32(bqr_rf_stats_event_.rssi_delta_8_11, p_param_buf); + STREAM_TO_UINT32(bqr_rf_stats_event_.rssi_delta_11_up, p_param_buf); + return true; +} + void BqrVseSubEvt::WriteLmpLlTraceLogFile(int fd, uint8_t length, const uint8_t* p_param_buf) { const auto now = system_clock::to_time_t(system_clock::now()); localtime_r(&now, &tm_timestamp_); @@ -225,7 +300,19 @@ std::string BqrVseSubEvt::ToString() const { << ", CRCError: " << std::to_string(bqr_link_quality_event_.crc_error_packets) << ", RxDuplicate: " << std::to_string(bqr_link_quality_event_.rx_duplicate_packets); } - + if (QUALITY_REPORT_ID_ENERGY_MONITOR == bqr_link_quality_event_.quality_report_id) { + ss << ", TotalTime: " << std::to_string(bqr_energy_monitor_event_.tm_period) + << ", ActiveTime: " << std::to_string(bqr_energy_monitor_event_.active_total_time) + << ", IdleTime: " << std::to_string(bqr_energy_monitor_event_.idle_total_time) + << ", AvgCurrent: " << std::to_string(bqr_energy_monitor_event_.avg_current_consume); + } + if (QUALITY_REPORT_ID_RF_STATS == bqr_link_quality_event_.quality_report_id) { + ss << ", TotalTime: " << std::to_string(bqr_rf_stats_event_.tm_period) + << ", TxiPABF: " << std::to_string(bqr_rf_stats_event_.tx_pw_ipa_bf) + << ", TxePABF: " << std::to_string(bqr_rf_stats_event_.tx_pw_epa_bf) + << ", TxiPADiv: " << std::to_string(bqr_rf_stats_event_.tx_pw_ipa_div) + << ", TxePADiv: " << std::to_string(bqr_rf_stats_event_.tx_pw_epa_div); + } return ss.str(); } @@ -247,6 +334,10 @@ static std::string QualityReportIdToString(uint8_t quality_report_id) { return "LE Audio Choppy"; case QUALITY_REPORT_ID_CONNECT_FAIL: return "Connect Fail"; + case QUALITY_REPORT_ID_ENERGY_MONITOR: + return "Energy Monitor"; + case QUALITY_REPORT_ID_RF_STATS: + return "RF Stats"; default: return "Invalid"; } @@ -385,6 +476,7 @@ void EnableBtQualityReport(common::PostableContext* to_bind) { void DisableBtQualityReport() { log::info(""); + std::unique_lock<std::recursive_mutex> lock(life_cycle_guard_); if (to_bind_ == nullptr) { log::warn("Skipping second call (Lifecycle issue)."); return; @@ -480,6 +572,16 @@ static void BqrVscCompleteCallback(hci::CommandCompleteView complete) { return; } + { + // `DisableBtQualityReport()` set `to_bind_` at nullptr, after sending the command that clear + // reporting. When disabled, we don't want to continue and use nulled `to_bind_` (b/365653608). + std::unique_lock<std::recursive_mutex> lock(life_cycle_guard_); + if (to_bind_ == nullptr) { + log::info("Disabled"); + return; + } + } + if (vendor_cap_supported_version >= kBqrVndLogVersion) { command_complete_param_len = 13; } @@ -577,6 +679,9 @@ static void ConfigureBqrCmpl(uint32_t current_evt_mask) { } static void AddLinkQualityEventToQueue(uint8_t length, const uint8_t* p_link_quality_event); +static void AddEnergyMonitorEventToQueue(uint8_t length, const uint8_t* p_link_quality_event); +static void AddRFStatsEventToQueue(uint8_t length, const uint8_t* p_link_quality_event); +static void AddLinkQualityEventToQueue(uint8_t length, const uint8_t* p_link_quality_event); // Categorize the incoming Bluetooth Quality Report. // // @param length Lengths of the quality report sent from the Bluetooth @@ -619,6 +724,34 @@ static void CategorizeBqrEvent(uint8_t length, const uint8_t* p_bqr_event) { log::warn("Unexpected ID: 0x{:x}", quality_report_id); break; + case QUALITY_REPORT_ID_ENERGY_MONITOR: + if (length < kEnergyMonitorParamTotalLen) { + log::fatal( + "Parameter total length: {} is abnormal. It shall be not shorter " + "than: {}", + length, kEnergyMonitorParamTotalLen); + return; + } + + if (com::android::bluetooth::flags::support_bluetooth_quality_report_v6()) { + AddEnergyMonitorEventToQueue(length, p_bqr_event); + } + break; + + case QUALITY_REPORT_ID_RF_STATS: + if (length < kRFStatsParamTotalLen) { + log::fatal( + "Parameter total length: {} is abnormal. It shall be not shorter " + "than: {}", + length, kRFStatsParamTotalLen); + return; + } + + if (com::android::bluetooth::flags::support_bluetooth_quality_report_v6()) { + AddRFStatsEventToQueue(length, p_bqr_event); + } + break; + default: log::warn("Unknown ID: 0x{:x}", quality_report_id); break; @@ -693,6 +826,42 @@ static void AddLinkQualityEventToQueue(uint8_t length, const uint8_t* p_link_qua kpBqrEventQueue.Enqueue(p_bqr_event.release()); } +static void AddEnergyMonitorEventToQueue(uint8_t length, const uint8_t* p_energy_monitor_event) { + std::unique_ptr<BqrVseSubEvt> p_bqr_event = std::make_unique<BqrVseSubEvt>(); + + if (!p_bqr_event->ParseBqrEnergyMonitorEvt(length, p_energy_monitor_event)) { + log::warn("failed to parse BQR energy monitor event"); + return; + } + + BluetoothQualityReportInterface* bqrItf = getBluetoothQualityReportInterface(); + + if (bqrItf == NULL) { + log::warn("failed to deliver BQR, bqrItf is NULL"); + return; + } + + bqrItf->bqr_delivery_event(RawAddress::kAny, p_energy_monitor_event, length); +} + +static void AddRFStatsEventToQueue(uint8_t length, const uint8_t* p_rf_stats_event) { + std::unique_ptr<BqrVseSubEvt> p_bqr_event = std::make_unique<BqrVseSubEvt>(); + + if (!p_bqr_event->ParseBqrRFStatsEvt(length, p_rf_stats_event)) { + log::warn("failed to parse BQR RF stats event"); + return; + } + + BluetoothQualityReportInterface* bqrItf = getBluetoothQualityReportInterface(); + + if (bqrItf == NULL) { + log::warn("failed to deliver BQR, bqrItf is NULL"); + return; + } + + bqrItf->bqr_delivery_event(RawAddress::kAny, p_rf_stats_event, length); +} + static int OpenLmpLlTraceLogFile(); // Dump the LMP/LL message handshaking with the remote device to a log file. diff --git a/system/btif/src/btif_config.cc b/system/btif/src/btif_config.cc index c21bd33efb..f17548cf63 100644 --- a/system/btif/src/btif_config.cc +++ b/system/btif/src/btif_config.cc @@ -37,8 +37,8 @@ #include "common/metric_id_allocator.h" #include "main/shim/config.h" #include "main/shim/shim.h" -#include "raw_address.h" #include "storage/config_keys.h" +#include "types/raw_address.h" #define TEMPORARY_SECTION_CAPACITY 10000 diff --git a/system/btif/src/btif_csis_client.cc b/system/btif/src/btif_csis_client.cc index 65811c6abe..434368864b 100644 --- a/system/btif/src/btif_csis_client.cc +++ b/system/btif/src/btif_csis_client.cc @@ -24,12 +24,12 @@ #include <memory> #include "bind_helpers.h" -#include "bluetooth/uuid.h" #include "bta_csis_api.h" #include "btif_common.h" #include "btif_profile_storage.h" -#include "raw_address.h" #include "stack/include/main_thread.h" +#include "types/bluetooth/uuid.h" +#include "types/raw_address.h" // TODO(b/369381361) Enfore -Wmissing-prototypes #pragma GCC diagnostic ignored "-Wmissing-prototypes" diff --git a/system/btif/src/btif_dm.cc b/system/btif/src/btif_dm.cc index a8a2e17091..70762b7c64 100644 --- a/system/btif/src/btif_dm.cc +++ b/system/btif/src/btif_dm.cc @@ -33,7 +33,6 @@ #include <base/functional/bind.h> #include <base/strings/stringprintf.h> #include <bluetooth/log.h> -#include <bluetooth/uuid.h> #include <com_android_bluetooth_flags.h> #include <hardware/bluetooth.h> #include <hardware/bt_csis.h> @@ -99,6 +98,7 @@ #include "stack/include/smp_api.h" #include "stack/include/srvc_api.h" // tDIS_VALUE #include "storage/config_keys.h" +#include "types/bluetooth/uuid.h" #include "types/raw_address.h" #ifdef __ANDROID__ @@ -196,7 +196,6 @@ typedef struct { Octet16 er; bool is_id_keys_rcvd; btif_dm_local_key_id_t id_keys; /* ID kyes */ - } btif_dm_local_key_cb_t; /* this structure holds optional OOB data for remote device */ @@ -564,18 +563,7 @@ static void bond_state_changed(bt_status_t status, const RawAddress& bd_addr, if (pairing_cb.bond_type == BOND_TYPE_TEMPORARY) { state = BT_BOND_STATE_NONE; - } else { - if (state == BT_BOND_STATE_NONE) { - bluetooth::os::LogMetricBluetoothEvent(ToGdAddress(bd_addr), - android::bluetooth::EventType::BOND, - android::bluetooth::State::STATE_NONE); - } else if (state == BT_BOND_STATE_BONDED) { - bluetooth::os::LogMetricBluetoothEvent(ToGdAddress(bd_addr), - android::bluetooth::EventType::BOND, - android::bluetooth::State::STATE_BONDED); - } } - log::info( "Bond state changed to state={}[0:none, 1:bonding, " "2:bonded],prev_state={}, sdp_attempts={}", diff --git a/system/btif/src/btif_has_client.cc b/system/btif/src/btif_has_client.cc index c44485d70b..ff9769c525 100644 --- a/system/btif/src/btif_has_client.cc +++ b/system/btif/src/btif_has_client.cc @@ -29,8 +29,8 @@ #include "bta_has_api.h" #include "btif_common.h" #include "btif_profile_storage.h" -#include "raw_address.h" #include "stack/include/main_thread.h" +#include "types/raw_address.h" // TODO(b/369381361) Enfore -Wmissing-prototypes #pragma GCC diagnostic ignored "-Wmissing-prototypes" diff --git a/system/btif/src/btif_hh.cc b/system/btif/src/btif_hh.cc index e1a42df19e..1a9855ef31 100644 --- a/system/btif/src/btif_hh.cc +++ b/system/btif/src/btif_hh.cc @@ -40,10 +40,7 @@ #include <cstdint> #include <cstring> -#include "ble_address_with_type.h" -#include "bluetooth/uuid.h" #include "bt_device_type.h" -#include "bt_transport.h" #include "bta_api.h" #include "bta_hh_api.h" #include "bta_hh_co.h" @@ -65,6 +62,9 @@ #include "stack/include/bt_uuid16.h" #include "stack/include/btm_client_interface.h" #include "stack/include/hidh_api.h" +#include "types/ble_address_with_type.h" +#include "types/bluetooth/uuid.h" +#include "types/bt_transport.h" #include "types/raw_address.h" #define COD_HID_KEYBOARD 0x0540 @@ -977,6 +977,11 @@ void btif_hh_remove_device(const tAclLinkSpec& link_spec) { } else { log::warn("device_num = 0"); } + + if (com::android::bluetooth::flags::remove_pending_hid_connection()) { + BTA_HhRemoveDev(p_dev->dev_handle); // Remove the connection, in case it was pending + } + bta_hh_co_close(p_dev); p_dev->dev_status = BTHH_CONN_STATE_UNKNOWN; p_dev->dev_handle = BTA_HH_INVALID_HANDLE; diff --git a/system/btif/src/btif_iot_config.cc b/system/btif/src/btif_iot_config.cc index 9db2159ad7..ee857ef620 100644 --- a/system/btif/src/btif_iot_config.cc +++ b/system/btif/src/btif_iot_config.cc @@ -27,9 +27,9 @@ #include "device/include/device_iot_conf_defs.h" #include "device/include/device_iot_config.h" #include "hardware/bluetooth.h" -#include "raw_address.h" #include "stack/include/btm_ble_api.h" #include "stack/include/btm_client_interface.h" +#include "types/raw_address.h" // TODO(b/369381361) Enfore -Wmissing-prototypes #pragma GCC diagnostic ignored "-Wmissing-prototypes" diff --git a/system/btif/src/btif_le_audio.cc b/system/btif/src/btif_le_audio.cc index 8498dab876..0e6d377698 100644 --- a/system/btif/src/btif_le_audio.cc +++ b/system/btif/src/btif_le_audio.cc @@ -26,8 +26,8 @@ #include "bta_le_audio_api.h" #include "btif_common.h" #include "btif_profile_storage.h" -#include "raw_address.h" #include "stack/include/main_thread.h" +#include "types/raw_address.h" // TODO(b/369381361) Enfore -Wmissing-prototypes #pragma GCC diagnostic ignored "-Wmissing-prototypes" diff --git a/system/btif/src/btif_profile_storage.cc b/system/btif/src/btif_profile_storage.cc index 230101906a..f4ac16352c 100644 --- a/system/btif/src/btif_profile_storage.cc +++ b/system/btif/src/btif_profile_storage.cc @@ -32,8 +32,6 @@ #include <utility> #include <vector> -#include "ble_address_with_type.h" -#include "bt_transport.h" #include "bta_csis_api.h" #include "bta_groups.h" #include "bta_has_api.h" @@ -51,7 +49,9 @@ #include "stack/include/bt_uuid16.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" #include "types/raw_address.h" // TODO(b/369381361) Enfore -Wmissing-prototypes diff --git a/system/btif/src/btif_sock_l2cap.cc b/system/btif/src/btif_sock_l2cap.cc index f864dda287..3aa7162b78 100644 --- a/system/btif/src/btif_sock_l2cap.cc +++ b/system/btif/src/btif_sock_l2cap.cc @@ -320,9 +320,11 @@ static l2cap_socket* btsock_l2cap_alloc_l(const char* name, const RawAddress* ad security |= BTM_SEC_IN_MIN_16_DIGIT_PIN; } - // For Floss, set socket as SOCK_STREAM - // TODO(b:271828292): Set SOCK_STREAM for everyone after verification tests #if TARGET_FLOSS + //Changed socket type to SOCK_STREAM to address a platform issue on FLOSS. + //This is a workaround and not the recommended approach. + //SOCK_SEQPACKET is preferred for L2CAP LE CoC channels because it preserves L2CAP + //packet boundaries, ensuring message integrity. sock_type = SOCK_STREAM; #endif if (socketpair(AF_LOCAL, sock_type, 0, fds)) { @@ -607,12 +609,11 @@ static void on_cl_l2cap_psm_connect_l(tBTA_JV_L2CAP_OPEN* p_open, l2cap_socket* } static void on_l2cap_connect(tBTA_JV* p_data, uint32_t id) { - l2cap_socket* sock; tBTA_JV_L2CAP_OPEN* psm_open = &p_data->l2c_open; tBTA_JV_L2CAP_LE_OPEN* le_open = &p_data->l2c_le_open; std::unique_lock<std::mutex> lock(state_lock); - sock = btsock_l2cap_find_by_id_l(id); + l2cap_socket* sock = btsock_l2cap_find_by_id_l(id); if (!sock) { log::error("Unable to find l2cap socket with socket_id:{}", id); return; diff --git a/system/btif/src/btif_sock_rfc.cc b/system/btif/src/btif_sock_rfc.cc index a7fb56dd5e..3b50ca528b 100644 --- a/system/btif/src/btif_sock_rfc.cc +++ b/system/btif/src/btif_sock_rfc.cc @@ -158,7 +158,7 @@ static rfc_slot_t* find_free_slot(void) { } static rfc_slot_t* find_rfc_slot_by_id(uint32_t id) { - CHECK(id != 0); + CHECK_NE(0u, id); for (size_t i = 0; i < ARRAY_SIZE(rfc_slots); ++i) { if (rfc_slots[i].id == id) { diff --git a/system/btif/src/btif_vc.cc b/system/btif/src/btif_vc.cc index 22b5091be7..99fad72810 100644 --- a/system/btif/src/btif_vc.cc +++ b/system/btif/src/btif_vc.cc @@ -41,6 +41,7 @@ using base::Bind; using base::Unretained; +using bluetooth::aics::GainMode; using bluetooth::aics::Mute; using bluetooth::vc::ConnectionState; using bluetooth::vc::VolumeControlCallbacks; @@ -111,11 +112,25 @@ class VolumeControlInterfaceImpl : public VolumeControlInterface, public VolumeC /* Callbacks for Audio Input Stream (AIS) - Extended Audio Inputs */ void OnExtAudioInStateChanged(const RawAddress& address, uint8_t ext_input_id, - int8_t gain_setting, ::Mute mute, uint8_t gain_mode) override { + int8_t gain_setting, ::Mute mute, ::GainMode gain_mode) override { do_in_jni_thread(Bind(&VolumeControlCallbacks::OnExtAudioInStateChanged, Unretained(callbacks_), address, ext_input_id, gain_setting, mute, gain_mode)); } + void OnExtAudioInSetGainSettingFailed(const RawAddress& address, uint8_t ext_input_id) override { + do_in_jni_thread(Bind(&VolumeControlCallbacks::OnExtAudioInSetGainSettingFailed, + Unretained(callbacks_), address, ext_input_id)); + } + + void OnExtAudioInSetMuteFailed(const RawAddress& address, uint8_t ext_input_id) override { + do_in_jni_thread(Bind(&VolumeControlCallbacks::OnExtAudioInSetMuteFailed, + Unretained(callbacks_), address, ext_input_id)); + } + void OnExtAudioInSetGainModeFailed(const RawAddress& address, uint8_t ext_input_id) override { + do_in_jni_thread(Bind(&VolumeControlCallbacks::OnExtAudioInSetGainModeFailed, + Unretained(callbacks_), address, ext_input_id)); + } + void OnExtAudioInStatusChanged(const RawAddress& address, uint8_t ext_input_id, bluetooth::vc::VolumeInputStatus status) override { do_in_jni_thread(Bind(&VolumeControlCallbacks::OnExtAudioInStatusChanged, @@ -128,16 +143,16 @@ class VolumeControlInterfaceImpl : public VolumeControlInterface, public VolumeC address, ext_input_id, type)); } - void OnExtAudioInGainPropsChanged(const RawAddress& address, uint8_t ext_input_id, uint8_t unit, - int8_t min, int8_t max) override { - do_in_jni_thread(Bind(&VolumeControlCallbacks::OnExtAudioInGainPropsChanged, + void OnExtAudioInGainSettingPropertiesChanged(const RawAddress& address, uint8_t ext_input_id, + uint8_t unit, int8_t min, int8_t max) override { + do_in_jni_thread(Bind(&VolumeControlCallbacks::OnExtAudioInGainSettingPropertiesChanged, Unretained(callbacks_), address, ext_input_id, unit, min, max)); } void OnExtAudioInDescriptionChanged(const RawAddress& address, uint8_t ext_input_id, - std::string descr) override { + std::string description, bool is_writable) override { do_in_jni_thread(Bind(&VolumeControlCallbacks::OnExtAudioInDescriptionChanged, - Unretained(callbacks_), address, ext_input_id, descr)); + Unretained(callbacks_), address, ext_input_id, description, is_writable)); } void Connect(const RawAddress& address) override { @@ -346,55 +361,56 @@ class VolumeControlInterfaceImpl : public VolumeControlInterface, public VolumeC Unretained(VolumeControl::Get()), address, ext_input_id)); } - void SetExtAudioInDescription(const RawAddress& address, uint8_t ext_input_id, + bool SetExtAudioInDescription(const RawAddress& address, uint8_t ext_input_id, std::string descr) override { if (!initialized || !VolumeControl::IsVolumeControlRunning()) { bluetooth::log::verbose( "call ignored, due to already started cleanup procedure or service " "being not read"); - return; + return false; } do_in_main_thread(Bind(&VolumeControl::SetExtAudioInDescription, Unretained(VolumeControl::Get()), address, ext_input_id, descr)); + return true; } - void SetExtAudioInGainSetting(const RawAddress& address, uint8_t ext_input_id, + bool SetExtAudioInGainSetting(const RawAddress& address, uint8_t ext_input_id, int8_t gain_setting) override { if (!initialized || !VolumeControl::IsVolumeControlRunning()) { bluetooth::log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); - return; + "call ignored, due to already started cleanup procedure or service being not read"); + return false; } do_in_main_thread(Bind(&VolumeControl::SetExtAudioInGainSetting, Unretained(VolumeControl::Get()), address, ext_input_id, gain_setting)); + return true; } - void SetExtAudioInGainMode(const RawAddress& address, uint8_t ext_input_id, - bool automatic) override { + bool SetExtAudioInGainMode(const RawAddress& address, uint8_t ext_input_id, + ::GainMode gain_mode) override { if (!initialized || !VolumeControl::IsVolumeControlRunning()) { bluetooth::log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); - return; + "call ignored, due to already started cleanup procedure or service being not read"); + return false; } do_in_main_thread(Bind(&VolumeControl::SetExtAudioInGainMode, Unretained(VolumeControl::Get()), - address, ext_input_id, automatic)); + address, ext_input_id, gain_mode)); + return true; } - void SetExtAudioInGainMute(const RawAddress& address, uint8_t ext_input_id, bool mute) override { + bool SetExtAudioInMute(const RawAddress& address, uint8_t ext_input_id, ::Mute mute) override { if (!initialized || !VolumeControl::IsVolumeControlRunning()) { bluetooth::log::verbose( - "call ignored, due to already started cleanup procedure or service " - "being not read"); - return; + "call ignored, due to already started cleanup procedure or service being not read"); + return false; } - do_in_main_thread(Bind(&VolumeControl::SetExtAudioInGainMute, Unretained(VolumeControl::Get()), + do_in_main_thread(Bind(&VolumeControl::SetExtAudioInMute, Unretained(VolumeControl::Get()), address, ext_input_id, mute)); + return true; } void Cleanup(void) override { diff --git a/system/btif/test/btif_storage_test.cc b/system/btif/test/btif_storage_test.cc index 49fd74352a..d9a0345c59 100644 --- a/system/btif/test/btif_storage_test.cc +++ b/system/btif/test/btif_storage_test.cc @@ -37,8 +37,8 @@ TEST(BtifStorageTest, test_uuid_split_multiple) { Uuid uuids[2]; size_t num_uuids = btif_split_uuids_string(s1, uuids, 2); EXPECT_EQ(num_uuids, 2u); - EXPECT_TRUE(memcmp(uuids[0].To128BitBE().data(), u1, sizeof(u1)) == 0); - EXPECT_TRUE(memcmp(uuids[1].To128BitBE().data(), u2, sizeof(u2)) == 0); + EXPECT_EQ(0, memcmp(uuids[0].To128BitBE().data(), u1, sizeof(u1))); + EXPECT_EQ(0, memcmp(uuids[1].To128BitBE().data(), u2, sizeof(u2))); } TEST(BtifStorageTest, test_uuid_split_partial) { diff --git a/system/common/Android.bp b/system/common/Android.bp index 3009c77ec0..4bc0bebf2d 100644 --- a/system/common/Android.bp +++ b/system/common/Android.bp @@ -140,6 +140,7 @@ cc_test { "libbluetooth_log", "libbt-common", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "libgmock", "libosi", @@ -168,6 +169,7 @@ cc_benchmark { "libbluetooth_log", "libbt-common", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "libosi", ], diff --git a/system/common/address_obfuscator.h b/system/common/address_obfuscator.h index 3caff715ca..146fece28b 100644 --- a/system/common/address_obfuscator.h +++ b/system/common/address_obfuscator.h @@ -22,7 +22,7 @@ #include <string> #include "hci/octets.h" -#include "raw_address.h" +#include "types/raw_address.h" namespace bluetooth { namespace common { @@ -73,4 +73,4 @@ private: }; } // namespace common -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/common/base_bind_unittest.cc b/system/common/base_bind_unittest.cc index b4f35f53e4..7a7530bdc3 100644 --- a/system/common/base_bind_unittest.cc +++ b/system/common/base_bind_unittest.cc @@ -36,7 +36,6 @@ struct Vars { int c{0}; bool operator==(const Vars& rhs) const { return a == rhs.a && b == rhs.b && c == rhs.c; } - } g_vars; void func() {} diff --git a/system/common/id_generator.h b/system/common/id_generator.h index e404ff4585..7c6425aeef 100644 --- a/system/common/id_generator.h +++ b/system/common/id_generator.h @@ -45,4 +45,4 @@ private: }; template <std::size_t N> -int IdGenerator<N>::ALL_USED = -1;
\ No newline at end of file +int IdGenerator<N>::ALL_USED = -1; diff --git a/system/common/id_generator_unittest.cc b/system/common/id_generator_unittest.cc index d56ee1971f..7b090cf365 100644 --- a/system/common/id_generator_unittest.cc +++ b/system/common/id_generator_unittest.cc @@ -34,4 +34,4 @@ TEST(IdGeneratorTest, sanity_test) { generator.Release(2); ASSERT_EQ(0, generator.GetNext()); ASSERT_EQ(2, generator.GetNext()); -}
\ No newline at end of file +} diff --git a/system/common/metric_id_allocator.h b/system/common/metric_id_allocator.h index a89f03ab7f..adc70bb073 100644 --- a/system/common/metric_id_allocator.h +++ b/system/common/metric_id_allocator.h @@ -24,7 +24,7 @@ #include <unordered_set> #include "lru.h" -#include "raw_address.h" +#include "types/raw_address.h" namespace bluetooth { diff --git a/system/device/Android.bp b/system/device/Android.bp index 4753441a66..1a5d72ae45 100644 --- a/system/device/Android.bp +++ b/system/device/Android.bp @@ -68,6 +68,7 @@ cc_test { "libbtcore", "libbtdevice", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libosi", ], header_libs: ["libbluetooth_headers"], diff --git a/system/device/fuzzer/Android.bp b/system/device/fuzzer/Android.bp index 0b5e6c1296..d1b7357de9 100644 --- a/system/device/fuzzer/Android.bp +++ b/system/device/fuzzer/Android.bp @@ -52,12 +52,12 @@ cc_fuzz { "libbtcore", "libbtdevice", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libgmock", "libosi", ], include_dirs: [ "packages/modules/Bluetooth/system", - "packages/modules/Bluetooth/system/device/include", "packages/modules/Bluetooth/system/gd", ], fuzz_config: { diff --git a/system/device/fuzzer/btdevice_esco_fuzzer.cpp b/system/device/fuzzer/btdevice_esco_fuzzer.cpp index aa06d1fec9..99b3f78cd8 100644 --- a/system/device/fuzzer/btdevice_esco_fuzzer.cpp +++ b/system/device/fuzzer/btdevice_esco_fuzzer.cpp @@ -19,9 +19,9 @@ #include <string> #include "btcore/include/module.h" -#include "esco_parameters.h" -#include "interop.h" -#include "interop_config.h" +#include "device/include/esco_parameters.h" +#include "device/include/interop.h" +#include "device/include/interop_config.h" // TODO(b/369381361) Enfore -Wmissing-prototypes #pragma GCC diagnostic ignored "-Wmissing-prototypes" diff --git a/system/device/include/device_iot_conf_defs.h b/system/device/include/device_iot_conf_defs.h index 4132deab54..09c576d9ae 100644 --- a/system/device/include/device_iot_conf_defs.h +++ b/system/device/include/device_iot_conf_defs.h @@ -104,4 +104,4 @@ #define IOT_CONF_BYTE_NUM_1 1 #define IOT_CONF_BYTE_NUM_2 2 #define IOT_CONF_BYTE_NUM_3 3 -#define IOT_CONF_BYTE_NUM_4 4
\ No newline at end of file +#define IOT_CONF_BYTE_NUM_4 4 diff --git a/system/device/include/interop.h b/system/device/include/interop.h index 1d520b0c08..f54ef0d715 100644 --- a/system/device/include/interop.h +++ b/system/device/include/interop.h @@ -23,7 +23,7 @@ #include "include/hardware/bluetooth.h" #include "osi/include/list.h" -#include "raw_address.h" +#include "types/raw_address.h" static const char INTEROP_MODULE[] = "interop_module"; @@ -31,7 +31,6 @@ static const char INTEROP_MODULE[] = "interop_module"; // Only add values at the end of this enum and before END_OF_INTEROP_LIST // do NOT delete values as they may be used in dynamic device configuration. typedef enum { - BEGINNING_OF_INTEROP_LIST = 0, // Disable secure connections // This is for pre BT 4.1/2 devices that do not handle secure mode diff --git a/system/device/include/interop_database.h b/system/device/include/interop_database.h index b6c0ae1994..e4056fbebe 100644 --- a/system/device/include/interop_database.h +++ b/system/device/include/interop_database.h @@ -19,7 +19,7 @@ #pragma once #include "device/include/interop.h" -#include "raw_address.h" +#include "types/raw_address.h" typedef struct { RawAddress addr; @@ -48,4 +48,4 @@ typedef struct { uint16_t vendor_id; uint16_t product_id; interop_feature_t feature; -} interop_hid_multitouch_t;
\ No newline at end of file +} interop_hid_multitouch_t; diff --git a/system/device/src/interop.cc b/system/device/src/interop.cc index c45031a7b0..344198f2ea 100644 --- a/system/device/src/interop.cc +++ b/system/device/src/interop.cc @@ -179,7 +179,6 @@ typedef struct { interop_lmp_version_t lmp_version_entry; interop_addr_range_entry_t addr_range_entry; } entry_type; - } interop_db_entry_t; namespace fmt { diff --git a/system/device/test/device_iot_config_test.cc b/system/device/test/device_iot_config_test.cc index 58bc3a3425..4693c741d5 100644 --- a/system/device/test/device_iot_config_test.cc +++ b/system/device/test/device_iot_config_test.cc @@ -161,12 +161,12 @@ TEST_F_WITH_FLAGS(DeviceIotConfigModuleTest, test_device_iot_config_module_init_ int backup_fd = -1; file_fd = open(IOT_CONFIG_FILE_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); - EXPECT_TRUE(file_fd > 0); + EXPECT_GT(file_fd, 0); EXPECT_EQ(errno, 0); backup_fd = open(IOT_CONFIG_BACKUP_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); - EXPECT_TRUE(backup_fd > 0); + EXPECT_GT(backup_fd, 0); EXPECT_EQ(errno, 0); EXPECT_EQ(access(IOT_CONFIG_FILE_PATH, F_OK), 0); @@ -459,13 +459,13 @@ TEST_F_WITH_FLAGS(DeviceIotConfigModuleTest, errno = 0; file_fd = open(IOT_CONFIG_FILE_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); - EXPECT_TRUE(file_fd > 0); + EXPECT_GT(file_fd, 0); EXPECT_EQ(errno, 0); errno = 0; backup_fd = open(IOT_CONFIG_BACKUP_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); - EXPECT_TRUE(backup_fd > 0); + EXPECT_GT(backup_fd, 0); EXPECT_EQ(errno, 0); EXPECT_EQ(access(IOT_CONFIG_FILE_PATH, F_OK), 0); @@ -536,13 +536,13 @@ TEST_F_WITH_FLAGS(DeviceIotConfigModuleTest, errno = 0; file_fd = open(IOT_CONFIG_FILE_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); - EXPECT_TRUE(file_fd > 0); + EXPECT_GT(file_fd, 0); EXPECT_EQ(errno, 0); errno = 0; backup_fd = open(IOT_CONFIG_BACKUP_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); - EXPECT_TRUE(backup_fd > 0); + EXPECT_GT(backup_fd, 0); EXPECT_EQ(errno, 0); EXPECT_EQ(access(IOT_CONFIG_FILE_PATH, F_OK), 0); @@ -908,7 +908,6 @@ TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_sections_sort_by_e .key = "a", }, }}, - }; device_iot_config_sections_sort_by_entry_key(conf, [](const entry_t& first, const entry_t& second) { @@ -2253,7 +2252,7 @@ TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_iot_config_get_str, EXPECT_EQ(actual_section, expected_section); EXPECT_EQ(actual_key, expected_key); EXPECT_EQ(size_bytes, (int)actual_value_str.length() + 1); - EXPECT_TRUE(strncmp(get_value_str, actual_value_str.c_str(), size_bytes) == 0); + EXPECT_EQ(0, strncmp(get_value_str, actual_value_str.c_str(), size_bytes)); EXPECT_EQ(get_func_call_count("config_get_string"), 1); } @@ -3132,7 +3131,7 @@ TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_debug_iot_config_dump, char buf[BUF_SIZE] = {0}; fd = open(IOT_CONFIG_FILE_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); - EXPECT_TRUE(fd > 0); + EXPECT_GT(fd, 0); EXPECT_EQ(errno, 0); lseek(fd, 0, SEEK_SET); @@ -3145,7 +3144,7 @@ TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_debug_iot_config_dump, lseek(fd, 0, SEEK_SET); bytes_read = read(fd, buf, BUF_SIZE); - EXPECT_TRUE(bytes_read > 0); + EXPECT_GT(bytes_read, 0); EXPECT_EQ(errno, 0); lseek(fd, 0, SEEK_SET); @@ -3178,12 +3177,12 @@ TEST_F_WITH_FLAGS(DeviceIotConfigTest, test_device_debug_iot_config_delete_files int backup_fd = -1; file_fd = open(IOT_CONFIG_FILE_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); - EXPECT_TRUE(file_fd > 0); + EXPECT_GT(file_fd, 0); EXPECT_EQ(errno, 0); backup_fd = open(IOT_CONFIG_BACKUP_PATH, O_CREAT | O_RDWR | O_TRUNC | O_CLOEXEC, S_IRUSR | S_IWUSR); - EXPECT_TRUE(backup_fd > 0); + EXPECT_GT(backup_fd, 0); EXPECT_EQ(errno, 0); EXPECT_EQ(access(IOT_CONFIG_FILE_PATH, F_OK), 0); diff --git a/system/device/test/interop_test.cc b/system/device/test/interop_test.cc index c27801f208..88ff853ca5 100644 --- a/system/device/test/interop_test.cc +++ b/system/device/test/interop_test.cc @@ -543,7 +543,7 @@ TEST_F(InteropTest, test_ssr_max_latency_hit) { EXPECT_TRUE(interop_database_match_addr_get_max_lat(INTEROP_UPDATE_HID_SSR_MAX_LAT, &test_address, &max_lat)); - EXPECT_TRUE(max_lat == 0x0012); + EXPECT_EQ(0x0012, max_lat); module_clean_up(&interop_module); } @@ -624,7 +624,7 @@ TEST_F(InteropTest, test_dynamic_addr_get_ssr_max_lat) { interop_database_add_addr_max_lat(INTEROP_UPDATE_HID_SSR_MAX_LAT, &test_address, 0x0012); interop_database_match_addr_get_max_lat(INTEROP_UPDATE_HID_SSR_MAX_LAT, &test_address, &max_lat); - EXPECT_TRUE(max_lat == 0x0012); + EXPECT_EQ(0x0012, max_lat); interop_database_remove_addr_max_lat(INTEROP_UPDATE_HID_SSR_MAX_LAT, &test_address, 0x0012); @@ -632,7 +632,7 @@ TEST_F(InteropTest, test_dynamic_addr_get_ssr_max_lat) { EXPECT_FALSE(interop_database_match_addr_get_max_lat(INTEROP_UPDATE_HID_SSR_MAX_LAT, &test_address, &max_lat)); - EXPECT_FALSE(max_lat == 0x0012); + EXPECT_NE(0x0012, max_lat); module_clean_up(&interop_module); } diff --git a/system/embdrv/encoder_for_aptx/src/CBStruct.h b/system/embdrv/encoder_for_aptx/src/CBStruct.h index eb968d6650..7be8943979 100644 --- a/system/embdrv/encoder_for_aptx/src/CBStruct.h +++ b/system/embdrv/encoder_for_aptx/src/CBStruct.h @@ -37,4 +37,4 @@ typedef struct circularBuffer_t { #ifdef _GCC #pragma GCC visibility pop #endif -#endif // CBSTRUCT_H
\ No newline at end of file +#endif // CBSTRUCT_H diff --git a/system/embdrv/sbc/decoder/include/oi_bt_spec.h b/system/embdrv/sbc/decoder/include/oi_bt_spec.h index c0091cbe73..26c8d18aef 100644 --- a/system/embdrv/sbc/decoder/include/oi_bt_spec.h +++ b/system/embdrv/sbc/decoder/include/oi_bt_spec.h @@ -140,7 +140,6 @@ typedef enum { OI_LINK_KEY_TYPE_UNAUTHENTICATED = 4, /* Unauthenticated */ OI_LINK_KEY_TYPE_AUTHENTICATED = 5, /* Authenticated */ OI_LINK_KEY_TYPE_CHANGED_COMBO = 6 /* Changed */ - } OI_BT_LINK_KEY_TYPE; /* Number of bytes allocated for a PIN (personal indentification number) */ diff --git a/system/embdrv/sbc/decoder/include/oi_status.h b/system/embdrv/sbc/decoder/include/oi_status.h index 28d9f04f0a..b91809f564 100644 --- a/system/embdrv/sbc/decoder/include/oi_status.h +++ b/system/embdrv/sbc/decoder/include/oi_status.h @@ -684,7 +684,6 @@ typedef enum { status. (Only to be used for special cases involving OI_SLOG_ERROR() and OI_SLOG_WARNING().) */ - } OI_STATUS; /* Remember to update the #define below when new reserved blocks are added to diff --git a/system/embdrv/sbc/decoder/include/oi_stddefs.h b/system/embdrv/sbc/decoder/include/oi_stddefs.h index 1cf03b7bbe..9eec86abeb 100644 --- a/system/embdrv/sbc/decoder/include/oi_stddefs.h +++ b/system/embdrv/sbc/decoder/include/oi_stddefs.h @@ -39,27 +39,21 @@ extern "C" { #endif #ifndef FALSE -#define FALSE 0 /**< This define statement sets FALSE as a preprocessor alias for 0. */ +#define FALSE 0 /* This define statement sets FALSE as a preprocessor alias for 0. */ #endif #ifndef TRUE -#define TRUE \ - (!FALSE) /**< This define statement sets TRUE as a preprocessor alias for \ - !FALSE. */ +#define TRUE (!FALSE) /* This define statement sets TRUE as a preprocessor alias for !FALSE. */ #endif #ifdef HEW_TOOLCHAIN #ifdef NULL -#undef NULL /**< Override HEW toolchain NULL definition */ +#undef NULL /* Override HEW toolchain NULL definition */ #endif -#define NULL \ - 0 /**< HEW toolchain does not allow us to compare (void*) type to function \ - pointer */ +#define NULL 0 /* HEW toolchain does not allow us to compare (void*) type to function pointer */ #else #ifndef NULL -#define NULL \ - ((void*)0) /**< This define statement sets NULL as a preprocessor alias \ - for (void*)0 */ +#define NULL ((void*)0) /* This define statement sets NULL as a preprocessor alias for (void*)0 */ #endif #endif @@ -67,22 +61,18 @@ extern "C" { * @name Maximum and minimum values for basic types * @{ */ -#define OI_INT8_MIN ((int8_t)0x80) /**< decimal value: -128 */ -#define OI_INT8_MAX ((int8_t)0x7F) /**< decimal value: 127 */ -#define OI_INT16_MIN ((int16_t)0x8000) /**< decimal value: -32768 */ -#define OI_INT16_MAX ((int16_t)0x7FFF) /**< decimal value: 32767 */ -#define OI_INT32_MIN \ - ((int32_t)0x80000000) /**< decimal value: -2,147,483,648 \ - */ -#define OI_INT32_MAX \ - ((int32_t)0x7FFFFFFF) /**< decimal value: 2,147,483,647 \ - */ -#define OI_UINT8_MIN ((uint8_t)0) /**< decimal value: 0 */ -#define OI_UINT8_MAX ((uint8_t)0xFF) /**< decimal value: 255 */ -#define OI_UINT16_MIN ((uint16_t)0) /**< decimal value: 0 */ -#define OI_UINT16_MAX ((uint16_t)0xFFFF) /**< decimal value: 65535 */ -#define OI_UINT32_MIN ((uint32_t)0) /**< decimal value: 0 */ -#define OI_UINT32_MAX ((uint32_t)0xFFFFFFFF) /**< decimal value: 4,294,967,295 */ +#define OI_INT8_MIN ((int8_t)0x80) /* decimal value: -128 */ +#define OI_INT8_MAX ((int8_t)0x7F) /* decimal value: 127 */ +#define OI_INT16_MIN ((int16_t)0x8000) /* decimal value: -32768 */ +#define OI_INT16_MAX ((int16_t)0x7FFF) /* decimal value: 32767 */ +#define OI_INT32_MIN ((int32_t)0x80000000) /* decimal value: -2 147 483 648 */ +#define OI_INT32_MAX ((int32_t)0x7FFFFFFF) /* decimal value: 2 147 483 647 */ +#define OI_UINT8_MIN ((uint8_t)0) /* decimal value: 0 */ +#define OI_UINT8_MAX ((uint8_t)0xFF) /* decimal value: 255 */ +#define OI_UINT16_MIN ((uint16_t)0) /* decimal value: 0 */ +#define OI_UINT16_MAX ((uint16_t)0xFFFF) /* decimal value: 65535 */ +#define OI_UINT32_MIN ((uint32_t)0) /* decimal value: 0 */ +#define OI_UINT32_MAX ((uint32_t)0xFFFFFFFF) /* decimal value: 4 294 967 295 */ /** * @} @@ -95,8 +85,8 @@ extern "C" { /** unsigned 64-bit integer as a structure of two unsigned 32-bit integers */ typedef struct { - uint32_t I1; /**< most significant 32 bits */ - uint32_t I2; /**< least significant 32 bits */ + uint32_t I1; /* most significant 32 bits */ + uint32_t I2; /* least significant 32 bits */ } OI_UINT64; #define OI_UINT64_MIN \ @@ -108,8 +98,8 @@ typedef struct { * signed 32-bit integer */ typedef struct { - int32_t I1; /**< most significant 32 bits as a signed integer */ - uint32_t I2; /**< least significant 32 bits as an unsigned integer */ + int32_t I1; /* most significant 32 bits as a signed integer */ + uint32_t I2; /* least significant 32 bits as an unsigned integer */ } OI_INT64; #define OI_INT64_MIN \ @@ -119,10 +109,10 @@ typedef struct { /** unsigned 128-bit integer as a structure of four unsigned 32-bit integers */ typedef struct { - uint32_t I1; /**< most significant 32 bits */ - uint32_t I2; /**< second-most significant 32 bits */ - uint32_t I3; /**< third-most significant 32 bits */ - uint32_t I4; /**< least significant 32 bits */ + uint32_t I1; /* most significant 32 bits */ + uint32_t I2; /* second-most significant 32 bits */ + uint32_t I3; /* third-most significant 32 bits */ + uint32_t I4; /* least significant 32 bits */ } OI_UINT128; #define OI_UINT128_MIN \ @@ -133,10 +123,10 @@ typedef struct { /* signed 128-bit integer as a structure of three unsigned 32-bit integers and * one signed 32-bit integer */ typedef struct { - int32_t I1; /**< most significant 32 bits as a signed integer */ - uint32_t I2; /**< second-most significant 32 bits as an unsigned integer */ - uint32_t I3; /**< third-most significant 32 bits as an unsigned integer */ - uint32_t I4; /**< least significant 32 bits as an unsigned integer */ + int32_t I1; /* most significant 32 bits as a signed integer */ + uint32_t I2; /* second-most significant 32 bits as an unsigned integer */ + uint32_t I3; /* third-most significant 32 bits as an unsigned integer */ + uint32_t I4; /* least significant 32 bits as an unsigned integer */ } OI_INT128; #define OI_INT128_MIN \ diff --git a/system/embdrv/sbc/encoder/include/sbc_dct.h b/system/embdrv/sbc/encoder/include/sbc_dct.h index 42e1d4fb0d..fc817576e5 100644 --- a/system/embdrv/sbc/encoder/include/sbc_dct.h +++ b/system/embdrv/sbc/encoder/include/sbc_dct.h @@ -30,8 +30,7 @@ #if (SBC_ARM_ASM_OPT == TRUE) #define SBC_MULT_32_16_SIMPLIFIED(s16In2, s32In1, s32OutLow) \ { \ - __asm { \ - MUL s32OutLow,(int32_t)s16In2, (s32In1>>15) } \ + __asm { MUL s32OutLow, (int32_t)s16In2, (s32In1>>15) } \ } #else #if (SBC_DSP_OPT == TRUE) diff --git a/system/embdrv/sbc/encoder/include/sbc_encoder.h b/system/embdrv/sbc/encoder/include/sbc_encoder.h index 4c8d2c6fb4..d225b5d19e 100644 --- a/system/embdrv/sbc/encoder/include/sbc_encoder.h +++ b/system/embdrv/sbc/encoder/include/sbc_encoder.h @@ -186,7 +186,6 @@ typedef struct SBC_ENC_PARAMS_TAG { uint16_t FrameHeader; uint8_t Format; /* Default to be SBC_FORMAT_GENERAL for SBC if not assigned. Assigning to SBC_FORMAT_MSBC for mSBC */ - } SBC_ENC_PARAMS; #ifdef __cplusplus diff --git a/system/gd/Android.bp b/system/gd/Android.bp index ff26e0b539..fbef6533c2 100644 --- a/system/gd/Android.bp +++ b/system/gd/Android.bp @@ -170,7 +170,6 @@ cc_defaults { include_dirs: [ "packages/modules/Bluetooth/system/include", "packages/modules/Bluetooth/system/stack/include", - "packages/modules/Bluetooth/system/types", ], } @@ -251,7 +250,6 @@ cc_binary { include_dirs: [ "packages/modules/Bluetooth/system", "packages/modules/Bluetooth/system/include", - "packages/modules/Bluetooth/system/types", ], host_supported: true, srcs: [ @@ -342,7 +340,6 @@ cc_test { include_dirs: [ "packages/modules/Bluetooth/system", "packages/modules/Bluetooth/system/include", - "packages/modules/Bluetooth/system/types", ], host_supported: true, target: { @@ -387,7 +384,6 @@ cc_test { include_dirs: [ "packages/modules/Bluetooth/system", "packages/modules/Bluetooth/system/include", - "packages/modules/Bluetooth/system/types", ], host_supported: true, // TODO(b/231993739): Reenable isolated:true by deleting the explicit disable below diff --git a/system/gd/common/audit_log.h b/system/gd/common/audit_log.h index 7ce403e931..b129bc7411 100644 --- a/system/gd/common/audit_log.h +++ b/system/gd/common/audit_log.h @@ -25,4 +25,4 @@ void LogConnectionAdminAuditEvent(const char* action, const hci::Address& addres hci::ErrorCode status); } // namespace common -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/common/byte_array.h b/system/gd/common/byte_array.h index 29c58d8d8d..b7183c4d2d 100644 --- a/system/gd/common/byte_array.h +++ b/system/gd/common/byte_array.h @@ -74,4 +74,4 @@ public: }; } // namespace common -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/common/list_map.h b/system/gd/common/list_map.h index 802602bde7..1b63302806 100644 --- a/system/gd/common/list_map.h +++ b/system/gd/common/list_map.h @@ -200,4 +200,4 @@ private: }; } // namespace common -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/common/numbers.h b/system/gd/common/numbers.h index 826615a71f..e31bebbee3 100644 --- a/system/gd/common/numbers.h +++ b/system/gd/common/numbers.h @@ -44,4 +44,4 @@ bool IsNumberInNumericLimits(InputType input) { } } // namespace common -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/common/numbers_test.cc b/system/gd/common/numbers_test.cc index ee1b92a87b..bf4159f934 100644 --- a/system/gd/common/numbers_test.cc +++ b/system/gd/common/numbers_test.cc @@ -34,4 +34,4 @@ TEST(NumbersTest, test_is_number_in_numeric_limits) { ASSERT_FALSE(IsNumberInNumericLimits<int8_t>(int32_t(-129))); } -} // namespace testing
\ No newline at end of file +} // namespace testing diff --git a/system/gd/common/type_helper.h b/system/gd/common/type_helper.h index 74991fbade..2f4a9d74fe 100644 --- a/system/gd/common/type_helper.h +++ b/system/gd/common/type_helper.h @@ -28,4 +28,4 @@ template <template <typename...> class TemplateType, typename... Args> struct is_specialization_of<TemplateType<Args...>, TemplateType> : std::true_type {}; } // namespace common -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/crypto_toolbox/crypto_toolbox_test.cc b/system/gd/crypto_toolbox/crypto_toolbox_test.cc index c3d081e709..35ab082d89 100644 --- a/system/gd/crypto_toolbox/crypto_toolbox_test.cc +++ b/system/gd/crypto_toolbox/crypto_toolbox_test.cc @@ -46,7 +46,7 @@ TEST(CryptoToolboxTest, bt_spec_test_d_1_test) { aes_set_key(k, sizeof(k), &ctx); aes_encrypt(m, output, &ctx); /* outputs in byte 48 to byte 63 */ - EXPECT_TRUE(memcmp(output, aes_cmac_k_m, kOctet16Length) == 0); + EXPECT_EQ(0, memcmp(output, aes_cmac_k_m, kOctet16Length)); // useful for debugging // log::info("k {}", base::HexEncode(k, OCTET16_LEN)); diff --git a/system/gd/dumpsys/filter_test.cc b/system/gd/dumpsys/filter_test.cc index 139279f6de..a1678ec373 100644 --- a/system/gd/dumpsys/filter_test.cc +++ b/system/gd/dumpsys/filter_test.cc @@ -92,15 +92,15 @@ TEST_F(DumpsysFilterTest, filter_as_developer) { const testing::DumpsysTestDataRoot* data_root = GetDumpsysTestDataRoot(dumpsys_data.data()); - ASSERT_TRUE(data_root->string_private()->str() == "String private"); - ASSERT_TRUE(data_root->string_opaque()->str() == "String opaque"); - ASSERT_TRUE(data_root->string_anonymized()->str() == "String anonymized"); - ASSERT_TRUE(data_root->string_any()->str() == "String any"); - - ASSERT_TRUE(data_root->int_private() == 123); - ASSERT_TRUE(data_root->int_opaque() == 456); - ASSERT_TRUE(data_root->int_anonymized() == 789); - ASSERT_TRUE(data_root->int_any() == 0xabc); + ASSERT_EQ("String private", data_root->string_private()->str()); + ASSERT_EQ("String opaque", data_root->string_opaque()->str()); + ASSERT_EQ("String anonymized", data_root->string_anonymized()->str()); + ASSERT_EQ("String any", data_root->string_any()->str()); + + ASSERT_EQ(123, data_root->int_private()); + ASSERT_EQ(456, data_root->int_opaque()); + ASSERT_EQ(789, data_root->int_anonymized()); + ASSERT_EQ(0xabc, data_root->int_any()); ASSERT_EQ(nullptr, data_root->bar_module_data()); diff --git a/system/gd/dumpsys/reflection_schema_test.cc b/system/gd/dumpsys/reflection_schema_test.cc index 727dd41ccf..83e433eddd 100644 --- a/system/gd/dumpsys/reflection_schema_test.cc +++ b/system/gd/dumpsys/reflection_schema_test.cc @@ -41,7 +41,7 @@ protected: TEST_F(ReflectionSchemaTest, verify_test_content) { dumpsys::ReflectionSchema reflection_schema(testing::GetBundledSchemaData()); - ASSERT_TRUE(reflection_schema.GetNumberOfBundledSchemas() == 5); + ASSERT_EQ(5, reflection_schema.GetNumberOfBundledSchemas()); ASSERT_TRUE(reflection_schema.FindInReflectionSchema("testing.DumpsysTestDataRoot") != nullptr); ASSERT_TRUE(reflection_schema.FindInReflectionSchema("testing.BarTestSchema") != nullptr); ASSERT_TRUE(reflection_schema.FindInReflectionSchema("testing.BazTestSchema") != nullptr); diff --git a/system/gd/hal/snoop_logger_socket_thread_test.cc b/system/gd/hal/snoop_logger_socket_thread_test.cc index f5a30b7298..a967a8d2a2 100644 --- a/system/gd/hal/snoop_logger_socket_thread_test.cc +++ b/system/gd/hal/snoop_logger_socket_thread_test.cc @@ -107,7 +107,7 @@ TEST_F(SnoopLoggerSocketThreadModuleTest, socket_connect_test) { // Connect to snoop logger socket RUN_NO_INTR(ret = connect(socket_fd, (struct sockaddr*)&addr, sizeof(addr))); - ASSERT_TRUE(ret == 0); + ASSERT_EQ(0, ret); sls.Stop(); @@ -134,11 +134,11 @@ TEST_F(SnoopLoggerSocketThreadModuleTest, socket_connect_disconnect_test) { // Connect to snoop logger socket RUN_NO_INTR(ret = connect(socket_fd, (struct sockaddr*)&addr, sizeof(addr))); - ASSERT_TRUE(ret == 0); + ASSERT_EQ(0, ret); // Close snoop logger socket RUN_NO_INTR(ret = close(socket_fd)); - ASSERT_TRUE(ret == 0); + ASSERT_EQ(0, ret); sls.Stop(); @@ -180,7 +180,7 @@ TEST_F(SnoopLoggerSocketThreadModuleTest, socket_send_before_connect_test) { // Connect to snoop logger socket RUN_NO_INTR(ret = connect(socket_fd, (struct sockaddr*)&addr, sizeof(addr))); - ASSERT_TRUE(ret == 0); + ASSERT_EQ(0, ret); char recv_buf1[sizeof(SnoopLoggerCommon::FileHeaderType)]; char recv_buf2[sizeof(test_data)]; @@ -217,7 +217,7 @@ TEST_F(SnoopLoggerSocketThreadModuleTest, socket_recv_file_header_test) { // Connect to snoop logger socket RUN_NO_INTR(ret = connect(socket_fd, (struct sockaddr*)&addr, sizeof(addr))); - ASSERT_TRUE(ret == 0); + ASSERT_EQ(0, ret); char recv_buf[sizeof(SnoopLoggerCommon::FileHeaderType)]; int bytes_read = -1; @@ -232,7 +232,7 @@ TEST_F(SnoopLoggerSocketThreadModuleTest, socket_recv_file_header_test) { bytes_read = a.get(); ASSERT_EQ(bytes_read, static_cast<int>(sizeof(SnoopLoggerCommon::FileHeaderType))); - ASSERT_TRUE(std::memcmp(recv_buf, &SnoopLoggerCommon::kBtSnoopFileHeader, bytes_read) == 0); + ASSERT_EQ(0, std::memcmp(recv_buf, &SnoopLoggerCommon::kBtSnoopFileHeader, bytes_read)); close(socket_fd); } @@ -255,7 +255,7 @@ TEST_F(SnoopLoggerSocketThreadModuleTest, socket_send_recv_test) { // Connect to snoop logger socket RUN_NO_INTR(ret = connect(socket_fd, (struct sockaddr*)&addr, sizeof(addr))); - ASSERT_TRUE(ret == 0); + ASSERT_EQ(0, ret); char test_data[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0f}; @@ -275,11 +275,10 @@ TEST_F(SnoopLoggerSocketThreadModuleTest, socket_send_recv_test) { a.wait(); bytes_read = a.get(); - ASSERT_TRUE(std::memcmp(recv_buf1, &SnoopLoggerCommon::kBtSnoopFileHeader, sizeof(recv_buf1)) == - 0); + ASSERT_EQ(0, std::memcmp(recv_buf1, &SnoopLoggerCommon::kBtSnoopFileHeader, sizeof(recv_buf1))); ASSERT_EQ(bytes_read, static_cast<int>(sizeof(test_data))); - ASSERT_TRUE(std::memcmp(recv_buf2, test_data, bytes_read) == 0); + ASSERT_EQ(0, std::memcmp(recv_buf2, test_data, bytes_read)); close(socket_fd); } diff --git a/system/gd/hal/snoop_logger_test.cc b/system/gd/hal/snoop_logger_test.cc index ac32603f94..595e2ad839 100644 --- a/system/gd/hal/snoop_logger_test.cc +++ b/system/gd/hal/snoop_logger_test.cc @@ -699,7 +699,7 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_sabme_ua_test) { auto filter_rfcomm_property = bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty); ASSERT_TRUE(filter_rfcomm_property); - ASSERT_TRUE(filter_rfcomm_property.value() == "true"); + ASSERT_EQ("true", filter_rfcomm_property.value()); auto* snoop_logger = new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, @@ -753,7 +753,7 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_acceptlisted_dlci_test) { auto filter_rfcomm_property = bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty); ASSERT_TRUE(filter_rfcomm_property); - ASSERT_TRUE(filter_rfcomm_property.value() == "true"); + ASSERT_EQ("true", filter_rfcomm_property.value()); auto* snoop_logger = new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, @@ -804,7 +804,7 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_not_acceptlisted_dlci_test auto filter_rfcomm_property = bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty); ASSERT_TRUE(filter_rfcomm_property); - ASSERT_TRUE(filter_rfcomm_property.value() == "true"); + ASSERT_EQ("true", filter_rfcomm_property.value()); auto* snoop_logger = new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, @@ -853,7 +853,7 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_not_acceptlisted_l2cap_cha auto filter_rfcomm_property = bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty); ASSERT_TRUE(filter_rfcomm_property); - ASSERT_TRUE(filter_rfcomm_property.value() == "true"); + ASSERT_EQ("true", filter_rfcomm_property.value()); auto* snoop_logger = new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, @@ -899,7 +899,7 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_acceptlisted_l2cap_channel auto filter_rfcomm_property = bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty); ASSERT_TRUE(filter_rfcomm_property); - ASSERT_TRUE(filter_rfcomm_property.value() == "true"); + ASSERT_EQ("true", filter_rfcomm_property.value()); auto* snoop_logger = new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10, @@ -1237,7 +1237,7 @@ TEST_F(SnoopLoggerModuleTest, socket_disabled_connect_fail_test) { // Connect to snoop logger socket RUN_NO_INTR(ret = connect(socket_fd, (struct sockaddr*)&addr, sizeof(addr))); - ASSERT_TRUE(ret != 0); + ASSERT_NE(0, ret); test_registry->StopAll(); close(socket_fd); @@ -1260,7 +1260,7 @@ TEST_F(SnoopLoggerModuleTest, default_socket_enabled_capture_recv_test) { // Connect to snoop logger socket RUN_NO_INTR(ret = connect(socket_fd, (struct sockaddr*)&addr, sizeof(addr))); - ASSERT_TRUE(ret == 0); + ASSERT_EQ(0, ret); char recv_buf1[sizeof(SnoopLoggerCommon::FileHeaderType)]; char recv_buf2[sizeof(SnoopLogger::PacketHeaderType)]; @@ -1281,10 +1281,9 @@ TEST_F(SnoopLoggerModuleTest, default_socket_enabled_capture_recv_test) { a.wait(); bytes_read = a.get(); - ASSERT_TRUE(std::memcmp(recv_buf1, &SnoopLoggerCommon::kBtSnoopFileHeader, sizeof(recv_buf1)) == - 0); + ASSERT_EQ(0, std::memcmp(recv_buf1, &SnoopLoggerCommon::kBtSnoopFileHeader, sizeof(recv_buf1))); ASSERT_EQ(bytes_read, static_cast<int>(kHfpAtNrec0.size())); - ASSERT_TRUE(std::memcmp(recv_buf3, kHfpAtNrec0.data(), kHfpAtNrec0.size()) == 0); + ASSERT_EQ(0, std::memcmp(recv_buf3, kHfpAtNrec0.data(), kHfpAtNrec0.size())); test_registry->StopAll(); close(socket_fd); @@ -1318,7 +1317,7 @@ TEST_F(SnoopLoggerModuleTest, custom_socket_register_enabled_capture_recv_test) int ret = 0; // Connect to snoop logger socket RUN_NO_INTR(ret = connect(socket_fd, (struct sockaddr*)&addr, sizeof(addr))); - ASSERT_TRUE(ret == 0); + ASSERT_EQ(0, ret); char recv_buf1[sizeof(SnoopLoggerCommon::FileHeaderType)]; char recv_buf2[sizeof(SnoopLogger::PacketHeaderType)]; @@ -1339,10 +1338,9 @@ TEST_F(SnoopLoggerModuleTest, custom_socket_register_enabled_capture_recv_test) a.wait(); bytes_read = a.get(); - ASSERT_TRUE(std::memcmp(recv_buf1, &SnoopLoggerCommon::kBtSnoopFileHeader, sizeof(recv_buf1)) == - 0); + ASSERT_EQ(0, std::memcmp(recv_buf1, &SnoopLoggerCommon::kBtSnoopFileHeader, sizeof(recv_buf1))); ASSERT_EQ(bytes_read, static_cast<int>(kHfpAtNrec0.size())); - ASSERT_TRUE(std::memcmp(recv_buf3, kHfpAtNrec0.data(), kHfpAtNrec0.size()) == 0); + ASSERT_EQ(0, std::memcmp(recv_buf3, kHfpAtNrec0.data(), kHfpAtNrec0.size())); test_registry->StopAll(); close(socket_fd); @@ -1469,7 +1467,7 @@ TEST_F(SnoopLoggerModuleTest, custom_socket_profiles_filtered_hfp_hf_test) { int ret = 0; // Connect to snoop logger socket RUN_NO_INTR(ret = connect(socket_fd, (struct sockaddr*)&addr, sizeof(addr))); - ASSERT_TRUE(ret == 0); + ASSERT_EQ(0, ret); char recv_buf1[sizeof(SnoopLoggerCommon::FileHeaderType)]; char recv_buf2[sizeof(SnoopLogger::PacketHeaderType)]; @@ -1492,10 +1490,9 @@ TEST_F(SnoopLoggerModuleTest, custom_socket_profiles_filtered_hfp_hf_test) { a.wait(); bytes_read = a.get(); - ASSERT_TRUE(std::memcmp(recv_buf1, &SnoopLoggerCommon::kBtSnoopFileHeader, sizeof(recv_buf1)) == - 0); + ASSERT_EQ(0, std::memcmp(recv_buf1, &SnoopLoggerCommon::kBtSnoopFileHeader, sizeof(recv_buf1))); ASSERT_EQ(bytes_read, static_cast<int>(expected_data_size)); - ASSERT_TRUE(std::memcmp(recv_buf3, kExpectedPhoneNumber.data(), expected_data_size) == 0); + ASSERT_EQ(0, std::memcmp(recv_buf3, kExpectedPhoneNumber.data(), expected_data_size)); ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty, SnoopLogger::kBtSnoopLogFilterProfileModeDisabled)); diff --git a/system/gd/hci/acl_manager/le_impl.h b/system/gd/hci/acl_manager/le_impl.h index 8020dfc47e..a8936a95d2 100644 --- a/system/gd/hci/acl_manager/le_impl.h +++ b/system/gd/hci/acl_manager/le_impl.h @@ -298,7 +298,6 @@ private: } return false; } - } connections; public: diff --git a/system/gd/hci/controller_test.cc b/system/gd/hci/controller_test.cc index 0662469200..cd0374cba7 100644 --- a/system/gd/hci/controller_test.cc +++ b/system/gd/hci/controller_test.cc @@ -393,21 +393,21 @@ TEST_F(ControllerTest, read_controller_info) { test_hci_layer_->total_num_synchronous_data_packets); ASSERT_EQ(controller_->GetMacAddress(), Address::kAny); LocalVersionInformation local_version_information = controller_->GetLocalVersionInformation(); - ASSERT_EQ(local_version_information.hci_version_, HciVersion::V_5_0); - ASSERT_EQ(local_version_information.hci_revision_, 0x1234); - ASSERT_EQ(local_version_information.lmp_version_, LmpVersion::V_4_2); - ASSERT_EQ(local_version_information.manufacturer_name_, 0xBAD); - ASSERT_EQ(local_version_information.lmp_subversion_, 0x5678); - ASSERT_EQ(controller_->GetLeBufferSize().le_data_packet_length_, 0x16); - ASSERT_EQ(controller_->GetLeBufferSize().total_num_le_packets_, 0x08); - ASSERT_EQ(controller_->GetLeSupportedStates(), 0x001f123456789abeUL); - ASSERT_EQ(controller_->GetLeMaximumDataLength().supported_max_tx_octets_, 0x12); - ASSERT_EQ(controller_->GetLeMaximumDataLength().supported_max_tx_time_, 0x34); - ASSERT_EQ(controller_->GetLeMaximumDataLength().supported_max_rx_octets_, 0x56); - ASSERT_EQ(controller_->GetLeMaximumDataLength().supported_max_rx_time_, 0x78); - ASSERT_EQ(controller_->GetLeMaximumAdvertisingDataLength(), 0x0672); - ASSERT_EQ(controller_->GetLeNumberOfSupportedAdverisingSets(), 0xF0); - ASSERT_TRUE(controller_->GetLocalSupportedBrEdrCodecIds().size() > 0); + ASSERT_EQ(HciVersion::V_5_0, local_version_information.hci_version_); + ASSERT_EQ(0x1234, local_version_information.hci_revision_); + ASSERT_EQ(LmpVersion::V_4_2, local_version_information.lmp_version_); + ASSERT_EQ(0xBAD, local_version_information.manufacturer_name_); + ASSERT_EQ(0x5678, local_version_information.lmp_subversion_); + ASSERT_EQ(0x16, controller_->GetLeBufferSize().le_data_packet_length_); + ASSERT_EQ(0x08, controller_->GetLeBufferSize().total_num_le_packets_); + ASSERT_EQ(0x001f123456789abeUL, controller_->GetLeSupportedStates()); + ASSERT_EQ(0x12, controller_->GetLeMaximumDataLength().supported_max_tx_octets_); + ASSERT_EQ(0x34, controller_->GetLeMaximumDataLength().supported_max_tx_time_); + ASSERT_EQ(0x56, controller_->GetLeMaximumDataLength().supported_max_rx_octets_); + ASSERT_EQ(0x78, controller_->GetLeMaximumDataLength().supported_max_rx_time_); + ASSERT_EQ(0x0672, controller_->GetLeMaximumAdvertisingDataLength()); + ASSERT_EQ(0xF0, controller_->GetLeNumberOfSupportedAdverisingSets()); + ASSERT_GT(controller_->GetLocalSupportedBrEdrCodecIds().size(), 0u); } TEST_F(ControllerTest, read_write_local_name) { diff --git a/system/gd/hci/distance_measurement_manager.cc b/system/gd/hci/distance_measurement_manager.cc index fc93fa9232..0140cf806d 100644 --- a/system/gd/hci/distance_measurement_manager.cc +++ b/system/gd/hci/distance_measurement_manager.cc @@ -27,6 +27,7 @@ #include "common/strings.h" #include "hal/ranging_hal.h" #include "hci/acl_manager.h" +#include "hci/controller.h" #include "hci/distance_measurement_interface.h" #include "hci/event_checkers.h" #include "hci/hci_layer.h" @@ -253,9 +254,10 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { } ~impl() {} - void start(os::Handler* handler, hal::RangingHal* ranging_hal, hci::HciLayer* hci_layer, - hci::AclManager* acl_manager) { + void start(os::Handler* handler, hci::Controller* controller, hal::RangingHal* ranging_hal, + hci::HciLayer* hci_layer, hci::AclManager* acl_manager) { handler_ = handler; + controller_ = controller; ranging_hal_ = ranging_hal; hci_layer_ = hci_layer; acl_manager_ = acl_manager; @@ -265,6 +267,10 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { log::info("IS_FLAG_ENABLED channel_sounding_in_stack: false"); return; } + if (!controller_->SupportsBleChannelSounding()) { + log::info("The controller doesn't support Channel Sounding feature."); + return; + } distance_measurement_interface_ = hci_layer_->GetDistanceMeasurementInterface( handler_->BindOn(this, &DistanceMeasurementManager::impl::handle_event)); distance_measurement_interface_->EnqueueCommand( @@ -2137,6 +2143,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { os::Handler* handler_; hal::RangingHal* ranging_hal_; + hci::Controller* controller_; hci::HciLayer* hci_layer_; hci::AclManager* acl_manager_; hci::DistanceMeasurementInterface* distance_measurement_interface_; @@ -2167,13 +2174,14 @@ DistanceMeasurementManager::~DistanceMeasurementManager() = default; void DistanceMeasurementManager::ListDependencies(ModuleList* list) const { list->add<hal::RangingHal>(); + list->add<hci::Controller>(); list->add<hci::HciLayer>(); list->add<hci::AclManager>(); } void DistanceMeasurementManager::Start() { - pimpl_->start(GetHandler(), GetDependency<hal::RangingHal>(), GetDependency<hci::HciLayer>(), - GetDependency<AclManager>()); + pimpl_->start(GetHandler(), GetDependency<hci::Controller>(), GetDependency<hal::RangingHal>(), + GetDependency<hci::HciLayer>(), GetDependency<AclManager>()); } void DistanceMeasurementManager::Stop() { pimpl_->stop(); } diff --git a/system/gd/hci/enum_helper.h b/system/gd/hci/enum_helper.h index b9b307d726..43ac2f92a1 100644 --- a/system/gd/hci/enum_helper.h +++ b/system/gd/hci/enum_helper.h @@ -93,4 +93,4 @@ std::optional<hci::LegacyScanMode> FromLegacyConfigString(const std::string& str return static_cast<hci::LegacyScanMode>(*raw_value); } -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/hci/hci_layer.cc b/system/gd/hci/hci_layer.cc index 87061483d9..1311815633 100644 --- a/system/gd/hci/hci_layer.cc +++ b/system/gd/hci/hci_layer.cc @@ -60,6 +60,9 @@ using os::Alarm; using os::Handler; using std::unique_ptr; +static std::recursive_mutex life_cycle_guard; +static bool life_cycle_stopped = true; + static std::chrono::milliseconds getHciTimeoutMs() { static auto sHciTimeoutMs = std::chrono::milliseconds(bluetooth::os::GetSystemPropertyUint32Base( "bluetooth.hci.timeout_milliseconds", HciLayer::kHciTimeoutMs.count())); @@ -573,6 +576,10 @@ struct HciLayer::hal_callbacks : public hal::HciHalCallbacks { explicit hal_callbacks(HciLayer& module) : module_(module) {} void hciEventReceived(hal::HciPacket event_bytes) override { + std::unique_lock<std::recursive_mutex> lock(life_cycle_guard); + if (life_cycle_stopped) { + return; + } auto packet = packet::PacketView<packet::kLittleEndian>( std::make_shared<std::vector<uint8_t>>(event_bytes)); EventView event = EventView::Create(packet); @@ -580,6 +587,10 @@ struct HciLayer::hal_callbacks : public hal::HciHalCallbacks { } void aclDataReceived(hal::HciPacket data_bytes) override { + std::unique_lock<std::recursive_mutex> lock(life_cycle_guard); + if (life_cycle_stopped) { + return; + } auto packet = packet::PacketView<packet::kLittleEndian>( std::make_shared<std::vector<uint8_t>>(std::move(data_bytes))); auto acl = std::make_unique<AclView>(AclView::Create(packet)); @@ -587,6 +598,10 @@ struct HciLayer::hal_callbacks : public hal::HciHalCallbacks { } void scoDataReceived(hal::HciPacket data_bytes) override { + std::unique_lock<std::recursive_mutex> lock(life_cycle_guard); + if (life_cycle_stopped) { + return; + } auto packet = packet::PacketView<packet::kLittleEndian>( std::make_shared<std::vector<uint8_t>>(std::move(data_bytes))); auto sco = std::make_unique<ScoView>(ScoView::Create(packet)); @@ -594,6 +609,10 @@ struct HciLayer::hal_callbacks : public hal::HciHalCallbacks { } void isoDataReceived(hal::HciPacket data_bytes) override { + std::unique_lock<std::recursive_mutex> lock(life_cycle_guard); + if (life_cycle_stopped) { + return; + } auto packet = packet::PacketView<packet::kLittleEndian>( std::make_shared<std::vector<uint8_t>>(std::move(data_bytes))); auto iso = std::make_unique<IsoView>(IsoView::Create(packet)); @@ -621,12 +640,20 @@ common::BidiQueueEnd<IsoBuilder, IsoView>* HciLayer::GetIsoQueueEnd() { void HciLayer::EnqueueCommand(unique_ptr<CommandBuilder> command, ContextualOnceCallback<void(CommandCompleteView)> on_complete) { + std::unique_lock<std::recursive_mutex> lock(life_cycle_guard); + if (life_cycle_stopped) { + return; + } CallOn(impl_, &impl::enqueue_command<CommandCompleteView>, std::move(command), std::move(on_complete)); } void HciLayer::EnqueueCommand(unique_ptr<CommandBuilder> command, ContextualOnceCallback<void(CommandStatusView)> on_status) { + std::unique_lock<std::recursive_mutex> lock(life_cycle_guard); + if (life_cycle_stopped) { + return; + } CallOn(impl_, &impl::enqueue_command<CommandStatusView>, std::move(command), std::move(on_status)); } @@ -639,28 +666,52 @@ void HciLayer::EnqueueCommand( } void HciLayer::RegisterEventHandler(EventCode event, ContextualCallback<void(EventView)> handler) { + std::unique_lock<std::recursive_mutex> lock(life_cycle_guard); + if (life_cycle_stopped) { + return; + } CallOn(impl_, &impl::register_event, event, handler); } void HciLayer::UnregisterEventHandler(EventCode event) { + std::unique_lock<std::recursive_mutex> lock(life_cycle_guard); + if (life_cycle_stopped) { + return; + } CallOn(impl_, &impl::unregister_event, event); } void HciLayer::RegisterLeEventHandler(SubeventCode event, ContextualCallback<void(LeMetaEventView)> handler) { + std::unique_lock<std::recursive_mutex> lock(life_cycle_guard); + if (life_cycle_stopped) { + return; + } CallOn(impl_, &impl::register_le_event, event, handler); } void HciLayer::UnregisterLeEventHandler(SubeventCode event) { + std::unique_lock<std::recursive_mutex> lock(life_cycle_guard); + if (life_cycle_stopped) { + return; + } CallOn(impl_, &impl::unregister_le_event, event); } void HciLayer::RegisterVendorSpecificEventHandler( VseSubeventCode event, ContextualCallback<void(VendorSpecificEventView)> handler) { + std::unique_lock<std::recursive_mutex> lock(life_cycle_guard); + if (life_cycle_stopped) { + return; + } CallOn(impl_, &impl::register_vs_event, event, handler); } void HciLayer::UnregisterVendorSpecificEventHandler(VseSubeventCode event) { + std::unique_lock<std::recursive_mutex> lock(life_cycle_guard); + if (life_cycle_stopped) { + return; + } CallOn(impl_, &impl::unregister_vs_event, event); } @@ -877,9 +928,11 @@ void HciLayer::ListDependencies(ModuleList* list) const { } void HciLayer::Start() { + std::unique_lock<std::recursive_mutex> lock(life_cycle_guard); auto hal = GetDependency<hal::HciHal>(); impl_ = new impl(hal, *this); hal_callbacks_ = new hal_callbacks(*this); + life_cycle_stopped = false; Handler* handler = GetHandler(); impl_->acl_queue_.GetDownEnd()->RegisterDequeue(handler, @@ -907,6 +960,7 @@ void HciLayer::StartWithNoHalDependencies(Handler* handler) { } void HciLayer::Stop() { + std::unique_lock<std::recursive_mutex> lock(life_cycle_guard); auto hal = GetDependency<hal::HciHal>(); hal->unregisterIncomingPacketCallback(); delete hal_callbacks_; @@ -915,6 +969,8 @@ void HciLayer::Stop() { impl_->sco_queue_.GetDownEnd()->UnregisterDequeue(); impl_->iso_queue_.GetDownEnd()->UnregisterDequeue(); delete impl_; + + life_cycle_stopped = true; } } // namespace hci diff --git a/system/gd/hci/hci_metrics_logging.h b/system/gd/hci/hci_metrics_logging.h index ffa07fda50..4e1d9b72f4 100644 --- a/system/gd/hci/hci_metrics_logging.h +++ b/system/gd/hci/hci_metrics_logging.h @@ -44,4 +44,4 @@ void log_remote_device_information(const Address& address, uint32_t connection_handle, ErrorCode status, storage::StorageModule* storage_module); } // namespace hci -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/hci/hci_packets_test.cc b/system/gd/hci/hci_packets_test.cc index 01121c7922..017a5dab98 100644 --- a/system/gd/hci/hci_packets_test.cc +++ b/system/gd/hci/hci_packets_test.cc @@ -442,7 +442,7 @@ TEST(HciPacketsTest, testLeMultiAdvSetAdvertisingDataBuilderLength) { ASSERT_TRUE(command_view.IsValid()); auto view = LeMultiAdvtSetDataView::Create(command_view); ASSERT_TRUE(view.IsValid()); - ASSERT_TRUE(view.GetAdvertisingData().size() > 0ul); + ASSERT_GT(view.GetAdvertisingData().size(), 0ul); ASSERT_EQ(view.GetAdvertisingData()[0].data_, gap_data.data_); ASSERT_EQ(view.GetAdvertisingInstance(), 3); } diff --git a/system/gd/hci/link_key.cc b/system/gd/hci/link_key.cc index 2a9204f690..78ea1a48ea 100644 --- a/system/gd/hci/link_key.cc +++ b/system/gd/hci/link_key.cc @@ -22,4 +22,4 @@ namespace hci { const LinkKey kExampleLinkKey{{0x4C, 0x68, 0x38, 0x41, 0x39, 0xf5, 0x74, 0xd8, 0x36, 0xbc, 0xf3, 0x4e, 0x9d, 0xfb, 0x01, 0xbf}}; } -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/hci/link_key.h b/system/gd/hci/link_key.h index ed873e6e77..fc55c0cacc 100644 --- a/system/gd/hci/link_key.h +++ b/system/gd/hci/link_key.h @@ -27,4 +27,4 @@ using LinkKey = common::ByteArray<16>; extern const LinkKey kExampleLinkKey; } // namespace hci -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/hci/remote_name_request.h b/system/gd/hci/remote_name_request.h index d8018d2841..c8553c7c2f 100644 --- a/system/gd/hci/remote_name_request.h +++ b/system/gd/hci/remote_name_request.h @@ -73,4 +73,4 @@ public: }; } // namespace hci -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/hci/uuid_unittest.cc b/system/gd/hci/uuid_unittest.cc index 36abbba0f7..3656a13ffd 100644 --- a/system/gd/hci/uuid_unittest.cc +++ b/system/gd/hci/uuid_unittest.cc @@ -45,9 +45,9 @@ TEST(UuidTest, IsEmpty) { } TEST(UuidTest, GetShortestRepresentationSize) { - ASSERT_TRUE(Uuid::kNumBytes16 == kBase.GetShortestRepresentationSize()); - ASSERT_TRUE(Uuid::kNumBytes32 == Uuid::From32Bit(0x01234567).GetShortestRepresentationSize()); - ASSERT_TRUE(Uuid::kNumBytes128 == Uuid::kEmpty.GetShortestRepresentationSize()); + ASSERT_EQ(Uuid::kNumBytes16, kBase.GetShortestRepresentationSize()); + ASSERT_EQ(Uuid::kNumBytes32, Uuid::From32Bit(0x01234567).GetShortestRepresentationSize()); + ASSERT_EQ(Uuid::kNumBytes128, Uuid::kEmpty.GetShortestRepresentationSize()); } TEST(UuidTest, As16Bit) { @@ -80,17 +80,17 @@ TEST(UuidTest, From16Bit) { const uint8_t u2[] = {0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; Uuid uuid = Uuid::From16Bit(0x0001); - ASSERT_TRUE(memcmp(uuid.data(), u2, sizeof(u2)) == 0); + ASSERT_EQ(0, memcmp(uuid.data(), u2, sizeof(u2))); const uint8_t u3[] = {0x00, 0x00, 0x55, 0x3e, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; uuid = Uuid::From16Bit(0x553e); - ASSERT_TRUE(memcmp(uuid.data(), u3, sizeof(u3)) == 0); + ASSERT_EQ(0, memcmp(uuid.data(), u3, sizeof(u3))); const uint8_t u4[] = {0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; uuid = Uuid::From16Bit(0xffff); - ASSERT_TRUE(memcmp(uuid.data(), u4, sizeof(u4)) == 0); + ASSERT_EQ(0, memcmp(uuid.data(), u4, sizeof(u4))); } TEST(UuidTest, From32Bit) { @@ -99,17 +99,17 @@ TEST(UuidTest, From32Bit) { const uint8_t u2[] = {0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; Uuid uuid = Uuid::From32Bit(0x00000001); - ASSERT_TRUE(memcmp(uuid.data(), u2, sizeof(u2)) == 0); + ASSERT_EQ(0, memcmp(uuid.data(), u2, sizeof(u2))); const uint8_t u3[] = {0x33, 0x44, 0x55, 0x3e, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; uuid = Uuid::From32Bit(0x3344553e); - ASSERT_TRUE(memcmp(uuid.data(), u3, sizeof(u3)) == 0); + ASSERT_EQ(0, memcmp(uuid.data(), u3, sizeof(u3))); const uint8_t u4[] = {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; uuid = Uuid::From32Bit(0xffffffff); - ASSERT_TRUE(memcmp(uuid.data(), u4, sizeof(u4)) == 0); + ASSERT_EQ(0, memcmp(uuid.data(), u4, sizeof(u4))); } TEST(UuidTest, ToString) { @@ -132,19 +132,19 @@ TEST(UuidTest, test_string_to_uuid) { 0x9d, 0xb0, 0x35, 0xfb, 0xd9, 0xae, 0xbf, 0x22}; auto uuid = Uuid::FromString("e39c6285-867f-4b1d-9db0-35fbd9aebf22"); ASSERT_TRUE(uuid); - ASSERT_TRUE(memcmp(uuid->data(), u1, sizeof(u1)) == 0); + ASSERT_EQ(0, memcmp(uuid->data(), u1, sizeof(u1))); const uint8_t u2[] = {0x00, 0x00, 0x1a, 0xe8, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; uuid = Uuid::FromString("1Ae8"); ASSERT_TRUE(uuid); - ASSERT_TRUE(memcmp(uuid->data(), u2, sizeof(u2)) == 0); + ASSERT_EQ(0, memcmp(uuid->data(), u2, sizeof(u2))); const uint8_t u3[] = {0x12, 0x34, 0x11, 0x28, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; uuid = Uuid::FromString("12341128"); ASSERT_TRUE(uuid); - ASSERT_TRUE(memcmp(uuid->data(), u3, sizeof(u3)) == 0); + ASSERT_EQ(0, memcmp(uuid->data(), u3, sizeof(u3))); } TEST(UuidTest, legacy) { diff --git a/system/gd/metrics/chromeos/metrics_allowlist.cc b/system/gd/metrics/chromeos/metrics_allowlist.cc index 47cec3af45..33f2bf6dde 100644 --- a/system/gd/metrics/chromeos/metrics_allowlist.cc +++ b/system/gd/metrics/chromeos/metrics_allowlist.cc @@ -182,7 +182,6 @@ static constexpr int device_info_allow_list_usb[][2] = { {12994, 1}, /* Fuji Yusoki Kogyo Co., Ltd. */ {44580, 34328}, - }; enum Transport { @@ -344,4 +343,4 @@ bool IsChipsetInfoInAllowList(int vendor_id, int product_id, int transport, } } // namespace metrics -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/metrics/chromeos/metrics_allowlist.h b/system/gd/metrics/chromeos/metrics_allowlist.h index 07e00a0509..6bd1530558 100644 --- a/system/gd/metrics/chromeos/metrics_allowlist.h +++ b/system/gd/metrics/chromeos/metrics_allowlist.h @@ -25,4 +25,4 @@ bool IsChipsetInfoInAllowList(int vendor_id, int product_id, int transport, const char* chipset_string, uint64_t* hval); } // namespace metrics -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/metrics/chromeos/metrics_event.h b/system/gd/metrics/chromeos/metrics_event.h index 039cf84944..56d059a853 100644 --- a/system/gd/metrics/chromeos/metrics_event.h +++ b/system/gd/metrics/chromeos/metrics_event.h @@ -110,7 +110,6 @@ enum class MetricProfileConnectionStatus : int64_t { PROFILE_CONN_STATE_REMOTE_UNAVAILABLE = 6, PROFILE_CONN_STATE_PROFILE_NOT_SUPPORTED = 7, PROFILE_CONN_STATE_UNKNOWN_ERROR = 8, - }; // ENUM definition for profile disconnection status that in sync with ChromeOS structured metrics diff --git a/system/gd/metrics/counter_metrics.h b/system/gd/metrics/counter_metrics.h index 69dd5df043..a677041d16 100644 --- a/system/gd/metrics/counter_metrics.h +++ b/system/gd/metrics/counter_metrics.h @@ -45,4 +45,4 @@ private: }; } // namespace metrics -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/os/android/parameter_provider.cc b/system/gd/os/android/parameter_provider.cc index 5f137a0252..c8507ddf32 100644 --- a/system/gd/os/android/parameter_provider.cc +++ b/system/gd/os/android/parameter_provider.cc @@ -117,4 +117,4 @@ void ParameterProvider::SetCommonCriteriaConfigCompareResult(int result) { } } // namespace os -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/os/bt_keystore.h b/system/gd/os/bt_keystore.h index be0975009b..68005acdea 100644 --- a/system/gd/os/bt_keystore.h +++ b/system/gd/os/bt_keystore.h @@ -22,4 +22,4 @@ namespace bluetooth_keystore { BluetoothKeystoreInterface* getBluetoothKeystoreInterface(); } // namespace bluetooth_keystore -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/os/files.h b/system/gd/os/files.h index e10d792f62..34a9f2f5b9 100644 --- a/system/gd/os/files.h +++ b/system/gd/os/files.h @@ -53,4 +53,4 @@ std::optional<std::chrono::time_point<std::chrono::system_clock, std::chrono::na FileCreatedTime(const std::string& path); } // namespace os -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/os/host/system_properties.cc b/system/gd/os/host/system_properties.cc index 7918aae2ce..5b28659612 100644 --- a/system/gd/os/host/system_properties.cc +++ b/system/gd/os/host/system_properties.cc @@ -54,4 +54,4 @@ bool IsRootCanalEnabled() { return false; } int GetAndroidVendorReleaseVersion() { return 0; } } // namespace os -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/os/linux_generic/files_test.cc b/system/gd/os/linux_generic/files_test.cc index ee58ae5c47..5d85d76fba 100644 --- a/system/gd/os/linux_generic/files_test.cc +++ b/system/gd/os/linux_generic/files_test.cc @@ -84,4 +84,4 @@ TEST(FilesTest, write_read_empty_string_test) { TEST(FilesTest, read_non_existing_file_test) { EXPECT_FALSE(ReadSmallFile("/woof")); } -} // namespace testing
\ No newline at end of file +} // namespace testing diff --git a/system/gd/os/parameter_provider.h b/system/gd/os/parameter_provider.h index cdb9d3f9f1..df8a8ee900 100644 --- a/system/gd/os/parameter_provider.h +++ b/system/gd/os/parameter_provider.h @@ -59,4 +59,4 @@ public: }; } // namespace os -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/os/rand.h b/system/gd/os/rand.h index e2b0b649fd..04e29d30f4 100644 --- a/system/gd/os/rand.h +++ b/system/gd/os/rand.h @@ -41,4 +41,4 @@ inline uint32_t GenerateRandom() { } } // namespace os -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/os/system_properties_common_test.cc b/system/gd/os/system_properties_common_test.cc index ac276d7fad..1550e0ad19 100644 --- a/system/gd/os/system_properties_common_test.cc +++ b/system/gd/os/system_properties_common_test.cc @@ -60,4 +60,4 @@ TEST(SystemPropertiesTest, getUint32BaseHex) { ASSERT_EQ(bluetooth::os::GetSystemPropertyUint32Base(property, 1, 10), 0u); // if parsed as a dec } -} // namespace testing
\ No newline at end of file +} // namespace testing diff --git a/system/gd/packet/custom_field_fixed_size_interface.h b/system/gd/packet/custom_field_fixed_size_interface.h index 76cdcaf138..1bf1335d27 100644 --- a/system/gd/packet/custom_field_fixed_size_interface.h +++ b/system/gd/packet/custom_field_fixed_size_interface.h @@ -39,4 +39,4 @@ public: }; } // namespace packet -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/rust/topshim/Android.bp b/system/gd/rust/topshim/Android.bp index fe3a5cca15..b7d3af79ea 100644 --- a/system/gd/rust/topshim/Android.bp +++ b/system/gd/rust/topshim/Android.bp @@ -62,7 +62,6 @@ cc_library_static { "packages/modules/Bluetooth/system/gd", "packages/modules/Bluetooth/system/gd/rust/topshim", "packages/modules/Bluetooth/system/include", - "packages/modules/Bluetooth/system/types", ], host_supported: true, static_libs: [ diff --git a/system/gd/rust/topshim/vc/vc_shim.cc b/system/gd/rust/topshim/vc/vc_shim.cc index da0e055d56..eaf96aa874 100644 --- a/system/gd/rust/topshim/vc/vc_shim.cc +++ b/system/gd/rust/topshim/vc/vc_shim.cc @@ -16,12 +16,12 @@ #include "gd/rust/topshim/vc/vc_shim.h" +#include <aics/api.h> #include <bluetooth/log.h> #include <hardware/bluetooth.h> #include <string> -#include "aics/api.h" #include "src/profiles/vc.rs.h" #include "types/raw_address.h" @@ -138,9 +138,24 @@ public: void OnExtAudioInStateChanged(const RawAddress& address, uint8_t ext_input_id, int8_t gain_setting, bluetooth::aics::Mute mute, - uint8_t gain_mode_auto) { - log::info("address={}, ext_input_id={}, gain_setting={}, gain_mode_auto={}, mute={}", address, - ext_input_id, gain_setting, gain_mode_auto, static_cast<uint8_t>(mute)); + bluetooth::aics::GainMode gain_mode) { + log::info("address={}, ext_input_id={}, gain_setting={}, mute={:#x}, gain_mode={:#x}", address, + ext_input_id, gain_setting, mute, gain_mode); + log::info("Not implemented"); + } + + void OnExtAudioInSetGainSettingFailed(const RawAddress& address, uint8_t ext_input_id) { + log::info("address={}, ext_input_id={}", address, ext_input_id); + log::info("Not implemented"); + } + + void OnExtAudioInSetMuteFailed(const RawAddress& address, uint8_t ext_input_id) { + log::info("address={}, ext_input_id={}", address, ext_input_id); + log::info("Not implemented"); + } + + void OnExtAudioInSetGainModeFailed(const RawAddress& address, uint8_t ext_input_id) { + log::info("address={}, ext_input_id={}", address, ext_input_id); log::info("Not implemented"); } @@ -155,16 +170,17 @@ public: log::info("Not implemented"); } - void OnExtAudioInGainPropsChanged(const RawAddress& address, uint8_t ext_input_id, uint8_t unit, - int8_t min, int8_t max) { + void OnExtAudioInGainSettingPropertiesChanged(const RawAddress& address, uint8_t ext_input_id, + uint8_t unit, int8_t min, int8_t max) { log::info("address={}, ext_input_id={}, unit={}, min={}, max={}", address, ext_input_id, unit, min, max); log::info("Not implemented"); } void OnExtAudioInDescriptionChanged(const RawAddress& address, uint8_t ext_input_id, - std::string descr) { - log::info("address={}, ext_input_id={}, descr={}", address, ext_input_id, descr); + std::string description, bool is_writable) { + log::info("address={}, ext_input_id={}, description={}, is_writable={}", address, ext_input_id, + description, is_writable); log::info("Not implemented"); } }; diff --git a/system/gd/storage/classic_device.cc b/system/gd/storage/classic_device.cc index 0a204e5d5c..f2104a9c07 100644 --- a/system/gd/storage/classic_device.cc +++ b/system/gd/storage/classic_device.cc @@ -49,4 +49,4 @@ bool ClassicDevice::IsPaired() const { } } // namespace storage -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/storage/config_cache_helper_test.cc b/system/gd/storage/config_cache_helper_test.cc index 1627023d1c..e149c3777c 100644 --- a/system/gd/storage/config_cache_helper_test.cc +++ b/system/gd/storage/config_cache_helper_test.cc @@ -135,4 +135,4 @@ TEST(ConfigCacheHelperTest, set_get_bin_test) { ASSERT_THAT(ConfigCacheHelper(config).GetBin("A", "B"), Optional(ContainerEq(data2))); } -} // namespace testing
\ No newline at end of file +} // namespace testing diff --git a/system/gd/storage/le_device.cc b/system/gd/storage/le_device.cc index 4abf3c470c..3cbbb7839f 100644 --- a/system/gd/storage/le_device.cc +++ b/system/gd/storage/le_device.cc @@ -49,4 +49,4 @@ bool LeDevice::IsPaired() const { } } // namespace storage -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/storage/le_device.h b/system/gd/storage/le_device.h index 9d5dd0132b..835519929e 100644 --- a/system/gd/storage/le_device.h +++ b/system/gd/storage/le_device.h @@ -104,4 +104,4 @@ struct hash<bluetooth::storage::LeDevice> { return addr_hash ^ (pointer_hash_1 << 1) ^ (pointer_hash_2 << 2); } }; -} // namespace std
\ No newline at end of file +} // namespace std diff --git a/system/gd/storage/legacy_config_file.h b/system/gd/storage/legacy_config_file.h index 38375a03f3..2a5a8bf9b0 100644 --- a/system/gd/storage/legacy_config_file.h +++ b/system/gd/storage/legacy_config_file.h @@ -37,4 +37,4 @@ private: }; } // namespace storage -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/storage/legacy_config_file_test.cc b/system/gd/storage/legacy_config_file_test.cc index 6cec332d5c..b52891793f 100644 --- a/system/gd/storage/legacy_config_file_test.cc +++ b/system/gd/storage/legacy_config_file_test.cc @@ -188,4 +188,4 @@ TEST(LegacyConfigFileTest, duplicate_section_and_key_test) { EXPECT_TRUE(std::filesystem::remove(temp_config)); } -} // namespace testing
\ No newline at end of file +} // namespace testing diff --git a/system/gd/storage/mutation.cc b/system/gd/storage/mutation.cc index 559a0415d9..e091344f36 100644 --- a/system/gd/storage/mutation.cc +++ b/system/gd/storage/mutation.cc @@ -48,4 +48,4 @@ void Mutation::Commit() { } } // namespace storage -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/storage/mutation.h b/system/gd/storage/mutation.h index 493faddace..4f24e7725b 100644 --- a/system/gd/storage/mutation.h +++ b/system/gd/storage/mutation.h @@ -38,4 +38,4 @@ private: }; } // namespace storage -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/storage/mutation_entry.cc b/system/gd/storage/mutation_entry.cc index f1c930e576..5d610e70ef 100644 --- a/system/gd/storage/mutation_entry.cc +++ b/system/gd/storage/mutation_entry.cc @@ -47,4 +47,4 @@ MutationEntry::MutationEntry(EntryType entry_type_param, PropertyType property_t } } // namespace storage -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/storage/mutation_entry.h b/system/gd/storage/mutation_entry.h index 120b99ea20..cc1a3d09ed 100644 --- a/system/gd/storage/mutation_entry.h +++ b/system/gd/storage/mutation_entry.h @@ -117,4 +117,4 @@ private: }; } // namespace storage -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/gd/storage/mutation_test.cc b/system/gd/storage/mutation_test.cc index 9a0dada790..1a1a3e82ff 100644 --- a/system/gd/storage/mutation_test.cc +++ b/system/gd/storage/mutation_test.cc @@ -126,4 +126,4 @@ TEST(MutationTest, add_to_different_configs) { ASSERT_THAT(memory_only_config.GetProperty("A", "D"), Optional(StrEq("Hello"))); } -} // namespace testing
\ No newline at end of file +} // namespace testing diff --git a/system/gd/storage/serializable.h b/system/gd/storage/serializable.h index 263539d822..ef26d3a4f4 100644 --- a/system/gd/storage/serializable.h +++ b/system/gd/storage/serializable.h @@ -50,4 +50,4 @@ public: }; } // namespace storage -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/hci/Android.bp b/system/hci/Android.bp index 5e493288a7..e4e0106606 100644 --- a/system/hci/Android.bp +++ b/system/hci/Android.bp @@ -66,6 +66,7 @@ cc_test { "libbluetooth_log", "libbt-hci", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libosi", ], sanitize: { diff --git a/system/hci/include/bt_vendor_lib.h b/system/hci/include/bt_vendor_lib.h index c666fc13bf..1f774d4bb7 100644 --- a/system/hci/include/bt_vendor_lib.h +++ b/system/hci/include/bt_vendor_lib.h @@ -197,7 +197,6 @@ typedef enum { * completion of vendor specific setup process once it has been done. */ BT_VND_OP_A2DP_OFFLOAD_STOP, - } bt_vendor_opcode_t; /** Power on/off control states */ diff --git a/system/hci/src/packet_fragmenter.cc b/system/hci/src/packet_fragmenter.cc index c95c25dfe6..0077237c19 100644 --- a/system/hci/src/packet_fragmenter.cc +++ b/system/hci/src/packet_fragmenter.cc @@ -312,9 +312,12 @@ static void reassemble_and_dispatch(BT_HDR* packet) { } } -static const packet_fragmenter_t interface = {init, cleanup, - - fragment_and_dispatch, reassemble_and_dispatch}; +static const packet_fragmenter_t interface = { + init, + cleanup, + fragment_and_dispatch, + reassemble_and_dispatch, +}; const packet_fragmenter_t* packet_fragmenter_get_interface() { buffer_allocator = buffer_allocator_get_interface(); diff --git a/system/hci/test/packet_fragmenter_test.cc b/system/hci/test/packet_fragmenter_test.cc index 03e134382f..e22a5031bb 100644 --- a/system/hci/test/packet_fragmenter_test.cc +++ b/system/hci/test/packet_fragmenter_test.cc @@ -300,12 +300,12 @@ static void expect_packet_reassembled_iso(uint16_t event, BT_HDR* packet, const STREAM_TO_UINT16(length, data); if (iso_has_ts) { STREAM_TO_UINT32(timestamp, data); - ASSERT_TRUE((packet->layer_specific & BT_ISO_HDR_CONTAINS_TS) != 0); + ASSERT_NE(0, (packet->layer_specific & BT_ISO_HDR_CONTAINS_TS)); ASSERT_EQ(timestamp, expected_timestamp); ASSERT_EQ(is_complete ? test_iso_handle_complete_with_ts : test_iso_handle_start_with_ts, handle); } else { - ASSERT_TRUE((packet->layer_specific & BT_ISO_HDR_CONTAINS_TS) == 0); + ASSERT_EQ(0, (packet->layer_specific & BT_ISO_HDR_CONTAINS_TS)); ASSERT_EQ(is_complete ? test_iso_handle_complete_without_ts : test_iso_handle_start_without_ts, handle); hdr_size -= 4; diff --git a/system/include/hardware/avrcp/avrcp.h b/system/include/hardware/avrcp/avrcp.h index e5a0f3b274..4a5d1a7ac6 100644 --- a/system/include/hardware/avrcp/avrcp.h +++ b/system/include/hardware/avrcp/avrcp.h @@ -23,7 +23,7 @@ #include <vector> #include "avrcp_common.h" -#include "raw_address.h" +#include "types/raw_address.h" namespace bluetooth { namespace avrcp { diff --git a/system/include/hardware/ble_advertiser.h b/system/include/hardware/ble_advertiser.h index 11a753e92a..fe44d587b4 100644 --- a/system/include/hardware/ble_advertiser.h +++ b/system/include/hardware/ble_advertiser.h @@ -18,13 +18,13 @@ #define ANDROID_INCLUDE_BLE_ADVERTISER_H #include <base/functional/callback_forward.h> -#include <raw_address.h> #include <stdint.h> #include <vector> #include "bt_common_types.h" #include "bt_gatt_types.h" +#include "types/raw_address.h" constexpr uint8_t kAdvertiserClientIdJni = 0xff; constexpr uint8_t kAdvertiserClientIdLeAudio = 0x1; diff --git a/system/include/hardware/ble_scanner.h b/system/include/hardware/ble_scanner.h index ebe4654dba..67e0011987 100644 --- a/system/include/hardware/ble_scanner.h +++ b/system/include/hardware/ble_scanner.h @@ -17,8 +17,6 @@ #ifndef ANDROID_INCLUDE_BLE_SCANNER_H #define ANDROID_INCLUDE_BLE_SCANNER_H -#include <bluetooth/uuid.h> -#include <raw_address.h> #include <stdint.h> #include <memory> @@ -27,6 +25,8 @@ #include "bt_common_types.h" #include "bt_gatt_client.h" #include "bt_gatt_types.h" +#include "types/bluetooth/uuid.h" +#include "types/raw_address.h" /** Callback invoked when batchscan reports are obtained */ typedef void (*batchscan_reports_callback)(int client_if, int status, int report_format, diff --git a/system/include/hardware/bluetooth.h b/system/include/hardware/bluetooth.h index 77ff10a999..5ae5549dc5 100644 --- a/system/include/hardware/bluetooth.h +++ b/system/include/hardware/bluetooth.h @@ -26,9 +26,9 @@ #include <vector> #include "avrcp/avrcp.h" -#include "bluetooth/uuid.h" -#include "bt_transport.h" -#include "raw_address.h" +#include "types/bluetooth/uuid.h" +#include "types/bt_transport.h" +#include "types/raw_address.h" /** * The Bluetooth Hardware Module ID @@ -993,7 +993,6 @@ typedef struct { /** check if pbap pse dynamic version upgrade is enable */ bool (*pbap_pse_dynamic_version_upgrade_is_enabled)(); - } bt_interface_t; #define BLUETOOTH_INTERFACE_STRING "bluetoothInterface" diff --git a/system/include/hardware/bluetooth_headset_callbacks.h b/system/include/hardware/bluetooth_headset_callbacks.h index 3ef500322b..efb53643f7 100644 --- a/system/include/hardware/bluetooth_headset_callbacks.h +++ b/system/include/hardware/bluetooth_headset_callbacks.h @@ -16,9 +16,8 @@ #pragma once -#include <raw_address.h> - #include "bt_hf.h" +#include "types/raw_address.h" namespace bluetooth { namespace headset { diff --git a/system/include/hardware/bluetooth_headset_interface.h b/system/include/hardware/bluetooth_headset_interface.h index aac8acabc2..b2b98ffe1f 100644 --- a/system/include/hardware/bluetooth_headset_interface.h +++ b/system/include/hardware/bluetooth_headset_interface.h @@ -16,11 +16,10 @@ #pragma once -#include <raw_address.h> - #include "bluetooth.h" #include "bluetooth_headset_callbacks.h" #include "bt_hf.h" +#include "types/raw_address.h" namespace bluetooth { namespace headset { diff --git a/system/include/hardware/bt_av.h b/system/include/hardware/bt_av.h index b83db16f64..c6a9d7ae5c 100644 --- a/system/include/hardware/bt_av.h +++ b/system/include/hardware/bt_av.h @@ -19,11 +19,12 @@ #include <bluetooth/log.h> #include <hardware/bluetooth.h> -#include <raw_address.h> #include <optional> #include <vector> +#include "types/raw_address.h" + __BEGIN_DECLS // Must be kept in sync with BluetoothProfile.java diff --git a/system/include/hardware/bt_common_types.h b/system/include/hardware/bt_common_types.h index a394ed6e3e..e3d6b39901 100644 --- a/system/include/hardware/bt_common_types.h +++ b/system/include/hardware/bt_common_types.h @@ -23,12 +23,11 @@ #ifndef ANDROID_INCLUDE_BT_COMMON_TYPES_H #define ANDROID_INCLUDE_BT_COMMON_TYPES_H -#include <bluetooth/uuid.h> -#include <raw_address.h> - #include <vector> #include "bluetooth.h" +#include "types/bluetooth/uuid.h" +#include "types/raw_address.h" typedef struct { uint8_t client_if; diff --git a/system/include/hardware/bt_gatt_client.h b/system/include/hardware/bt_gatt_client.h index f6c4daeca8..5fbbd5f7c7 100644 --- a/system/include/hardware/bt_gatt_client.h +++ b/system/include/hardware/bt_gatt_client.h @@ -17,12 +17,12 @@ #ifndef ANDROID_INCLUDE_BT_GATT_CLIENT_H #define ANDROID_INCLUDE_BT_GATT_CLIENT_H -#include <bluetooth/uuid.h> -#include <raw_address.h> #include <stdint.h> #include "bt_common_types.h" #include "bt_gatt_types.h" +#include "types/bluetooth/uuid.h" +#include "types/raw_address.h" __BEGIN_DECLS @@ -291,7 +291,6 @@ typedef struct { /** Request a BLE subrate request procedure */ bt_status_t (*subrate_request)(const RawAddress& bd_addr, int subrate_min, int subrate_max, int max_latency, int cont_num, int timeout); - } btgatt_client_interface_t; __END_DECLS diff --git a/system/include/hardware/bt_gatt_server.h b/system/include/hardware/bt_gatt_server.h index c83b2c9a4b..0a08575dcb 100644 --- a/system/include/hardware/bt_gatt_server.h +++ b/system/include/hardware/bt_gatt_server.h @@ -17,10 +17,10 @@ #ifndef ANDROID_INCLUDE_BT_GATT_SERVER_H #define ANDROID_INCLUDE_BT_GATT_SERVER_H -#include <raw_address.h> #include <stdint.h> #include "bt_gatt_types.h" +#include "types/raw_address.h" __BEGIN_DECLS @@ -172,7 +172,6 @@ typedef struct { bt_status_t (*read_phy)(const RawAddress& bd_addr, base::Callback<void(uint8_t tx_phy, uint8_t rx_phy, uint8_t status)> cb); - } btgatt_server_interface_t; __END_DECLS diff --git a/system/include/hardware/bt_gatt_types.h b/system/include/hardware/bt_gatt_types.h index 8f0f4a511b..1801595084 100644 --- a/system/include/hardware/bt_gatt_types.h +++ b/system/include/hardware/bt_gatt_types.h @@ -17,11 +17,12 @@ #ifndef ANDROID_INCLUDE_BT_GATT_TYPES_H #define ANDROID_INCLUDE_BT_GATT_TYPES_H -#include <bluetooth/uuid.h> #include <stdbool.h> #include <stdint.h> #include <sys/cdefs.h> +#include "types/bluetooth/uuid.h" + __BEGIN_DECLS /** diff --git a/system/include/hardware/bt_hd.h b/system/include/hardware/bt_hd.h index b570656b8c..f86e2ee22f 100644 --- a/system/include/hardware/bt_hd.h +++ b/system/include/hardware/bt_hd.h @@ -17,9 +17,10 @@ #ifndef ANDROID_INCLUDE_BT_HD_H #define ANDROID_INCLUDE_BT_HD_H -#include <raw_address.h> #include <stdint.h> +#include "types/raw_address.h" + __BEGIN_DECLS typedef enum { @@ -112,7 +113,6 @@ typedef struct { /** send Virtual Cable Unplug */ bt_status_t (*virtual_cable_unplug)(void); - } bthd_interface_t; __END_DECLS diff --git a/system/include/hardware/bt_hearing_aid.h b/system/include/hardware/bt_hearing_aid.h index f94c9e1b6f..f484c4365d 100644 --- a/system/include/hardware/bt_hearing_aid.h +++ b/system/include/hardware/bt_hearing_aid.h @@ -18,7 +18,8 @@ #define ANDROID_INCLUDE_BT_HEARING_AID_H #include <hardware/bluetooth.h> -#include <raw_address.h> + +#include "types/raw_address.h" namespace bluetooth { namespace hearing_aid { diff --git a/system/include/hardware/bt_hf_client.h b/system/include/hardware/bt_hf_client.h index 4bf24c0bab..fe4c98b3e6 100644 --- a/system/include/hardware/bt_hf_client.h +++ b/system/include/hardware/bt_hf_client.h @@ -17,7 +17,8 @@ #pragma once #include <bluetooth/log.h> -#include <raw_address.h> + +#include "types/raw_address.h" typedef enum { BTHF_CLIENT_CONNECTION_STATE_DISCONNECTED = 0, @@ -75,7 +76,6 @@ typedef enum { BTHF_CLIENT_CALLSETUP_INCOMING, BTHF_CLIENT_CALLSETUP_OUTGOING, BTHF_CLIENT_CALLSETUP_ALERTING - } bthf_client_callsetup_t; typedef enum { diff --git a/system/include/hardware/bt_hh.h b/system/include/hardware/bt_hh.h index cd6079fc16..b326fc1324 100644 --- a/system/include/hardware/bt_hh.h +++ b/system/include/hardware/bt_hh.h @@ -18,13 +18,13 @@ #define ANDROID_INCLUDE_BT_HH_H #include <base/strings/stringprintf.h> -#include <ble_address_with_type.h> -#include <raw_address.h> #include <stdint.h> #include <string> #include "macros.h" +#include "types/ble_address_with_type.h" +#include "types/raw_address.h" __BEGIN_DECLS @@ -161,7 +161,6 @@ typedef struct { bthh_get_report_callback get_report_cb; bthh_virtual_unplug_callback virtual_unplug_cb; bthh_handshake_callback handshake_cb; - } bthh_callbacks_t; /** Represents the standard BT-HH interface. */ @@ -227,7 +226,6 @@ typedef struct { /** Configure which profiles can be enabled. Affected after re-init */ void (*configure_enabled_profiles)(bool enable_hidp, bool enable_hogp); - } bthh_interface_t; __END_DECLS diff --git a/system/include/hardware/bt_le_audio.h b/system/include/hardware/bt_le_audio.h index fea9dd4f57..8feb83f090 100644 --- a/system/include/hardware/bt_le_audio.h +++ b/system/include/hardware/bt_le_audio.h @@ -25,7 +25,7 @@ #include <ostream> #include <vector> -#include "raw_address.h" +#include "types/raw_address.h" namespace bluetooth { namespace le_audio { @@ -298,7 +298,6 @@ typedef struct btle_audio_codec_config { ", frame duration: " + frame_duration_str + ", octets per frame: " + octets_per_frame_str + ", codec priroty: " + codec_priority_str; } - } btle_audio_codec_config_t; class LeAudioClientCallbacks { diff --git a/system/include/hardware/bt_pan.h b/system/include/hardware/bt_pan.h index 4eca93720e..95ce4ac469 100644 --- a/system/include/hardware/bt_pan.h +++ b/system/include/hardware/bt_pan.h @@ -17,9 +17,9 @@ #pragma once #include <bluetooth/log.h> -#include <raw_address.h> #include "hardware/bluetooth.h" +#include "types/raw_address.h" #define BTPAN_ROLE_NONE 0 #define BTPAN_ROLE_PANNAP 1 @@ -81,7 +81,6 @@ typedef struct { * Cleanup the pan interface */ void (*cleanup)(void); - } btpan_interface_t; namespace fmt { diff --git a/system/include/hardware/bt_rc.h b/system/include/hardware/bt_rc.h index aa1baf8441..d6a984e479 100644 --- a/system/include/hardware/bt_rc.h +++ b/system/include/hardware/bt_rc.h @@ -17,7 +17,7 @@ #ifndef ANDROID_INCLUDE_BT_RC_H #define ANDROID_INCLUDE_BT_RC_H -#include <raw_address.h> +#include "types/raw_address.h" __BEGIN_DECLS /* Change this macro to use multiple RC */ diff --git a/system/include/hardware/bt_sdp.h b/system/include/hardware/bt_sdp.h index db9c3b71cb..8246bc74ab 100644 --- a/system/include/hardware/bt_sdp.h +++ b/system/include/hardware/bt_sdp.h @@ -16,10 +16,9 @@ #pragma once -#include <bluetooth/uuid.h> -#include <raw_address.h> - #include "bluetooth.h" +#include "types/bluetooth/uuid.h" +#include "types/raw_address.h" #define SDP_OPP_SUPPORTED_FORMATS_MAX_LENGTH 15 diff --git a/system/include/hardware/bt_sock.h b/system/include/hardware/bt_sock.h index 4755cef5f8..fd28ff3e91 100644 --- a/system/include/hardware/bt_sock.h +++ b/system/include/hardware/bt_sock.h @@ -19,8 +19,8 @@ #include <stddef.h> #include "bluetooth.h" -#include "bluetooth/uuid.h" -#include "raw_address.h" +#include "types/bluetooth/uuid.h" +#include "types/raw_address.h" __BEGIN_DECLS @@ -118,7 +118,6 @@ typedef struct { * Get L2CAP remote channel ID with the associated connection uuid. */ bt_status_t (*get_l2cap_remote_cid)(bluetooth::Uuid& conn_uuid, uint16_t* cid); - } btsock_interface_t; __END_DECLS diff --git a/system/include/hardware/bt_vc.h b/system/include/hardware/bt_vc.h index 5e258b5953..10ede4faad 100644 --- a/system/include/hardware/bt_vc.h +++ b/system/include/hardware/bt_vc.h @@ -19,16 +19,15 @@ #include <aics/api.h> #include <hardware/bluetooth.h> -#include <raw_address.h> #include <string> #include <variant> +#include "types/raw_address.h" + namespace bluetooth { namespace vc { -using bluetooth::aics::Mute; - // Must be kept in sync with BluetoothProfile.java enum class ConnectionState { DISCONNECTED = 0, CONNECTING, CONNECTED, DISCONNECTING }; @@ -76,7 +75,12 @@ public: /* Callbacks for Audio Input Stream (AIS) - Extended Audio Inputs */ virtual void OnExtAudioInStateChanged(const RawAddress& address, uint8_t ext_input_id, - int8_t gain_setting, Mute mute, uint8_t gain_mode_auto) = 0; + int8_t gain_setting, bluetooth::aics::Mute mute, + bluetooth::aics::GainMode gain_mode) = 0; + virtual void OnExtAudioInSetGainSettingFailed(const RawAddress& address, + uint8_t ext_input_id) = 0; + virtual void OnExtAudioInSetMuteFailed(const RawAddress& address, uint8_t ext_input_id) = 0; + virtual void OnExtAudioInSetGainModeFailed(const RawAddress& address, uint8_t ext_input_id) = 0; virtual void OnExtAudioInStatusChanged(const RawAddress& address, uint8_t ext_input_id, VolumeInputStatus status) = 0; @@ -84,11 +88,12 @@ public: virtual void OnExtAudioInTypeChanged(const RawAddress& address, uint8_t ext_input_id, VolumeInputType type) = 0; - virtual void OnExtAudioInGainPropsChanged(const RawAddress& address, uint8_t ext_input_id, - uint8_t unit, int8_t min, int8_t max) = 0; + virtual void OnExtAudioInGainSettingPropertiesChanged(const RawAddress& address, + uint8_t ext_input_id, uint8_t unit, + int8_t min, int8_t max) = 0; virtual void OnExtAudioInDescriptionChanged(const RawAddress& address, uint8_t ext_input_id, - std::string descr) = 0; + std::string description, bool is_writable) = 0; }; class VolumeControlInterface { @@ -132,14 +137,14 @@ public: virtual void GetExtAudioInType(const RawAddress& address, uint8_t ext_input_id) = 0; virtual void GetExtAudioInGainProps(const RawAddress& address, uint8_t ext_input_id) = 0; virtual void GetExtAudioInDescription(const RawAddress& address, uint8_t ext_input_id) = 0; - virtual void SetExtAudioInDescription(const RawAddress& address, uint8_t ext_input_id, + virtual bool SetExtAudioInDescription(const RawAddress& address, uint8_t ext_input_id, std::string descr) = 0; - virtual void SetExtAudioInGainSetting(const RawAddress& address, uint8_t ext_input_id, + virtual bool SetExtAudioInGainSetting(const RawAddress& address, uint8_t ext_input_id, int8_t gain_setting) = 0; - virtual void SetExtAudioInGainMode(const RawAddress& address, uint8_t ext_input_id, - bool automatic) = 0; - virtual void SetExtAudioInGainMute(const RawAddress& address, uint8_t ext_input_id, - bool mute) = 0; + virtual bool SetExtAudioInGainMode(const RawAddress& address, uint8_t ext_input_id, + bluetooth::aics::GainMode gain_mode) = 0; + virtual bool SetExtAudioInMute(const RawAddress& address, uint8_t ext_input_id, + bluetooth::aics::Mute mute) = 0; }; } /* namespace vc */ diff --git a/system/include/hardware/distance_measurement_interface.h b/system/include/hardware/distance_measurement_interface.h index 2f24dbf9a2..8978fee082 100644 --- a/system/include/hardware/distance_measurement_interface.h +++ b/system/include/hardware/distance_measurement_interface.h @@ -17,7 +17,7 @@ #ifndef ANDROID_INCLUDE_DISTANCE_MEASUREMENT_INTERFACE_H #define ANDROID_INCLUDE_DISTANCE_MEASUREMENT_INTERFACE_H -#include <raw_address.h> +#include "types/raw_address.h" /** * Distance measurement callbacks related callbacks invoked from from the diff --git a/system/osi/Android.bp b/system/osi/Android.bp index aeabc7ad18..4806d61985 100644 --- a/system/osi/Android.bp +++ b/system/osi/Android.bp @@ -92,6 +92,7 @@ cc_library_static { "libaconfig_storage_read_api_cc", "libbluetooth_log", "libbt-platform-protos-lite", + "libcom.android.sysprop.bluetooth.wrapped", "server_configurable_flags", ], } @@ -145,6 +146,7 @@ cc_test { "libbluetooth_log", "libbt-common", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "libgmock", "libosi", diff --git a/system/osi/BUILD.gn b/system/osi/BUILD.gn index fdd2736fab..ffc3dfcac8 100644 --- a/system/osi/BUILD.gn +++ b/system/osi/BUILD.gn @@ -55,6 +55,7 @@ static_library("osi") { deps = [ "//bt/flags:bluetooth_flags_c_lib", + "//bt/sysprop:libcom.android.sysprop.bluetooth", "//bt/system/common", ] @@ -92,6 +93,7 @@ if (use.test) { ] deps = [ + "//bt/sysprop:libcom.android.sysprop.bluetooth", "//bt/system/osi", ] diff --git a/system/osi/include/properties.h b/system/osi/include/properties.h index c170c18331..975574e294 100644 --- a/system/osi/include/properties.h +++ b/system/osi/include/properties.h @@ -56,4 +56,4 @@ bool osi_property_get_bool(const char* key, bool default_value); // Helper function that returns the value of |key| coerced into a vector of // uint32_t. If the property is not set, then the |default_value| is used. std::vector<uint32_t> osi_property_get_uintlist(const char* key, - std::vector<uint32_t> default_value);
\ No newline at end of file + std::vector<uint32_t> default_value); diff --git a/system/osi/src/alarm.cc b/system/osi/src/alarm.cc index a280442bb0..c1a1b6da10 100644 --- a/system/osi/src/alarm.cc +++ b/system/osi/src/alarm.cc @@ -20,6 +20,7 @@ #include "osi/include/alarm.h" +#include <android_bluetooth_sysprop.h> #include <base/cancelable_callback.h> #include <bluetooth/log.h> #include <fcntl.h> @@ -312,6 +313,13 @@ static bool lazy_initialize(void) { bool timer_initialized = false; bool wakeup_timer_initialized = false; + // some platforms are not wired up to be woken up by the controller. + // on those platforms, if we go to sleep with a timer armed, it will + // continue counting during sleep. to prevent unwanted timer fires on + // those platforms, use CLOCK_MONOTONIC and don't count up during sleep. + bool wakeup_supported = android::sysprop::bluetooth::hardware::wakeup_supported().value_or(true); + clockid_t alarm_clockid = wakeup_supported ? CLOCK_BOOTTIME_ALARM : CLOCK_MONOTONIC; + std::lock_guard<std::mutex> lock(alarms_mutex); alarms = list_new(NULL); @@ -325,7 +333,7 @@ static bool lazy_initialize(void) { } timer_initialized = true; - if (!timer_create_internal(CLOCK_BOOTTIME_ALARM, &wakeup_timer)) { + if (!timer_create_internal(alarm_clockid, &wakeup_timer)) { if (!timer_create_internal(CLOCK_BOOTTIME, &wakeup_timer)) { goto error; } diff --git a/system/osi/test/fixed_queue_test.cc b/system/osi/test/fixed_queue_test.cc index 867b8e5d28..ea660d5fce 100644 --- a/system/osi/test/fixed_queue_test.cc +++ b/system/osi/test/fixed_queue_test.cc @@ -29,7 +29,7 @@ static bool is_fd_readable(int fd) { FD_SET(fd, &rfds); // Only the enqueue_fd should be readable int result = select(FD_SETSIZE, &rfds, NULL, NULL, &tv); - EXPECT_TRUE(result >= 0); + EXPECT_GE(result, 0); return FD_ISSET(fd, &rfds); } @@ -114,7 +114,7 @@ TEST_F(FixedQueueTest, test_fixed_queue_flush) { fixed_queue_try_enqueue(queue, (void*)DUMMY_DATA_STRING3); EXPECT_FALSE(fixed_queue_is_empty(queue)); fixed_queue_flush(queue, test_queue_entry_free_cb); - EXPECT_TRUE(test_queue_entry_free_counter == 3); + EXPECT_EQ(3, test_queue_entry_free_counter); EXPECT_TRUE(fixed_queue_is_empty(queue)); fixed_queue_free(queue, osi_free); } @@ -292,10 +292,10 @@ TEST_F(FixedQueueTest, test_fixed_queue_get_enqueue_dequeue_fd) { // Test validity of enqueue and dequeue file descriptors int enqueue_fd = fixed_queue_get_enqueue_fd(queue); int dequeue_fd = fixed_queue_get_dequeue_fd(queue); - EXPECT_TRUE(enqueue_fd >= 0); - EXPECT_TRUE(dequeue_fd >= 0); - EXPECT_TRUE(enqueue_fd < FD_SETSIZE); - EXPECT_TRUE(dequeue_fd < FD_SETSIZE); + EXPECT_GE(enqueue_fd, 0); + EXPECT_GE(dequeue_fd, 0); + EXPECT_LT(enqueue_fd, FD_SETSIZE); + EXPECT_LT(dequeue_fd, FD_SETSIZE); // Test the file descriptors of an empty queue // Only the enqueue_fd should be readable diff --git a/system/osi/test/fuzzers/alarm/Android.bp b/system/osi/test/fuzzers/alarm/Android.bp index e1108e8731..3af1096546 100644 --- a/system/osi/test/fuzzers/alarm/Android.bp +++ b/system/osi/test/fuzzers/alarm/Android.bp @@ -25,6 +25,7 @@ cc_fuzz { "libbluetooth_log", "libbt-common", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libgmock", "libosi", ], diff --git a/system/osi/test/fuzzers/allocator/Android.bp b/system/osi/test/fuzzers/allocator/Android.bp index f4874ff322..36b5ee4ae6 100644 --- a/system/osi/test/fuzzers/allocator/Android.bp +++ b/system/osi/test/fuzzers/allocator/Android.bp @@ -18,6 +18,7 @@ cc_fuzz { "libbase", "libbluetooth_log", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "liblog", "libosi", ], diff --git a/system/osi/test/fuzzers/fixed_queue/Android.bp b/system/osi/test/fuzzers/fixed_queue/Android.bp index 8758597a55..02ad1896bd 100644 --- a/system/osi/test/fuzzers/fixed_queue/Android.bp +++ b/system/osi/test/fuzzers/fixed_queue/Android.bp @@ -22,6 +22,7 @@ cc_fuzz { static_libs: [ "libbluetooth_log", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libosi", ], } diff --git a/system/osi/test/fuzzers/future/Android.bp b/system/osi/test/fuzzers/future/Android.bp index 46673e2659..c96dd2f984 100644 --- a/system/osi/test/fuzzers/future/Android.bp +++ b/system/osi/test/fuzzers/future/Android.bp @@ -22,6 +22,7 @@ cc_fuzz { static_libs: [ "libbluetooth_log", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libosi", ], } diff --git a/system/osi/test/fuzzers/list/Android.bp b/system/osi/test/fuzzers/list/Android.bp index 5c8f15e81e..bc5dd9a66e 100644 --- a/system/osi/test/fuzzers/list/Android.bp +++ b/system/osi/test/fuzzers/list/Android.bp @@ -18,6 +18,7 @@ cc_fuzz { "libbase", "libbluetooth_log", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "liblog", "libosi", ], diff --git a/system/osi/test/fuzzers/ringbuffer/Android.bp b/system/osi/test/fuzzers/ringbuffer/Android.bp index bbba16690f..08d308c70c 100644 --- a/system/osi/test/fuzzers/ringbuffer/Android.bp +++ b/system/osi/test/fuzzers/ringbuffer/Android.bp @@ -18,6 +18,7 @@ cc_fuzz { "libbase", "libbluetooth_log", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "liblog", "libosi", ], diff --git a/system/osi/test/list_test.cc b/system/osi/test/list_test.cc index 4b7e00fa52..5069144fae 100644 --- a/system/osi/test/list_test.cc +++ b/system/osi/test/list_test.cc @@ -202,19 +202,19 @@ TEST_F(ListTest, test_list_foreach_partial) { list_node_t* rc = list_foreach(list, list_callback_find_int, &find); EXPECT_TRUE(rc != NULL); int* rc_val = (int*)list_node(rc); - EXPECT_TRUE(*rc_val == 4); + EXPECT_EQ(4, *rc_val); find = 1; rc = list_foreach(list, list_callback_find_int, &find); EXPECT_TRUE(rc != NULL); rc_val = (int*)list_node(rc); - EXPECT_TRUE(*rc_val == 1); + EXPECT_EQ(1, *rc_val); find = 5; rc = list_foreach(list, list_callback_find_int, &find); EXPECT_TRUE(rc != NULL); rc_val = (int*)list_node(rc); - EXPECT_TRUE(*rc_val == 5); + EXPECT_EQ(5, *rc_val); find = 0; rc = list_foreach(list, list_callback_find_int, &find); diff --git a/system/osi/test/ringbuffer_test.cc b/system/osi/test/ringbuffer_test.cc index 8149b01794..06f38ff2de 100644 --- a/system/osi/test/ringbuffer_test.cc +++ b/system/osi/test/ringbuffer_test.cc @@ -25,7 +25,7 @@ TEST(RingbufferTest, test_insert_basic) { EXPECT_EQ((size_t)10, ringbuffer_size(rb)); // Ensure size doesn't change EXPECT_EQ((size_t)6, ringbuffer_available(rb)); EXPECT_EQ((size_t)10, peeked); - ASSERT_TRUE(0 == memcmp(buffer, peek, peeked)); + ASSERT_EQ(0, memcmp(buffer, peek, peeked)); ringbuffer_free(rb); } @@ -52,7 +52,7 @@ TEST(RingbufferTest, test_insert_full) { EXPECT_EQ((size_t)0, ringbuffer_available(rb)); EXPECT_EQ((size_t)5, ringbuffer_size(rb)); - ASSERT_TRUE(0 == memcmp(aa, peek, peeked)); + ASSERT_EQ(0, memcmp(aa, peek, peeked)); ringbuffer_free(rb); } @@ -80,7 +80,7 @@ TEST(RingbufferTest, test_multi_insert_delete) { uint8_t peek[16] = {0}; size_t peeked = ringbuffer_peek(rb, 0, peek, 16); EXPECT_EQ((size_t)13, peeked); - ASSERT_TRUE(0 == memcmp(content, peek, peeked)); + ASSERT_EQ(0, memcmp(content, peek, peeked)); // Delete some bytes @@ -98,7 +98,7 @@ TEST(RingbufferTest, test_multi_insert_delete) { uint8_t content2[] = {0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xCC, 0xCC}; peeked = ringbuffer_peek(rb, 0, peek, 7); EXPECT_EQ((size_t)7, peeked); - ASSERT_TRUE(0 == memcmp(content2, peek, peeked)); + ASSERT_EQ(0, memcmp(content2, peek, peeked)); // Pop buffer @@ -106,7 +106,7 @@ TEST(RingbufferTest, test_multi_insert_delete) { size_t popped = ringbuffer_pop(rb, peek, 7); EXPECT_EQ((size_t)7, popped); EXPECT_EQ((size_t)9, ringbuffer_available(rb)); - ASSERT_TRUE(0 == memcmp(content2, peek, peeked)); + ASSERT_EQ(0, memcmp(content2, peek, peeked)); // Add more again to check head motion @@ -133,7 +133,7 @@ TEST(RingbufferTest, test_multi_insert_delete) { EXPECT_EQ(added, popped); EXPECT_EQ((size_t)16, ringbuffer_available(rb)); EXPECT_EQ((size_t)0, ringbuffer_size(rb)); - ASSERT_TRUE(0 == memcmp(ae, peek, popped)); + ASSERT_EQ(0, memcmp(ae, peek, popped)); ringbuffer_free(rb); } diff --git a/system/packet/avrcp/avrcp_reject_packet.cc b/system/packet/avrcp/avrcp_reject_packet.cc index 91ea3cb3fe..cea6517560 100644 --- a/system/packet/avrcp/avrcp_reject_packet.cc +++ b/system/packet/avrcp/avrcp_reject_packet.cc @@ -43,4 +43,4 @@ bool RejectBuilder::Serialize(const std::shared_ptr<::bluetooth::Packet>& pkt) { } } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/avrcp/avrcp_reject_packet.h b/system/packet/avrcp/avrcp_reject_packet.h index b735edb686..c2b332c07f 100644 --- a/system/packet/avrcp/avrcp_reject_packet.h +++ b/system/packet/avrcp/avrcp_reject_packet.h @@ -38,4 +38,4 @@ protected: }; } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/avrcp/capabilities_packet.h b/system/packet/avrcp/capabilities_packet.h index 9ef34dbf0c..795569163c 100644 --- a/system/packet/avrcp/capabilities_packet.h +++ b/system/packet/avrcp/capabilities_packet.h @@ -130,4 +130,4 @@ public: }; } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/avrcp/change_path.h b/system/packet/avrcp/change_path.h index 8be60b0ea7..c343fa500b 100644 --- a/system/packet/avrcp/change_path.h +++ b/system/packet/avrcp/change_path.h @@ -92,4 +92,4 @@ private: }; } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/avrcp/get_current_player_application_setting_value.h b/system/packet/avrcp/get_current_player_application_setting_value.h index b00e1af2a1..9a9f6bd358 100644 --- a/system/packet/avrcp/get_current_player_application_setting_value.h +++ b/system/packet/avrcp/get_current_player_application_setting_value.h @@ -78,4 +78,4 @@ protected: }; } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/avrcp/get_folder_items.h b/system/packet/avrcp/get_folder_items.h index c13b8ab1cc..479c9d268b 100644 --- a/system/packet/avrcp/get_folder_items.h +++ b/system/packet/avrcp/get_folder_items.h @@ -124,4 +124,4 @@ protected: }; } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/avrcp/get_play_status_packet.h b/system/packet/avrcp/get_play_status_packet.h index b725bfecaa..3a22db08c2 100644 --- a/system/packet/avrcp/get_play_status_packet.h +++ b/system/packet/avrcp/get_play_status_packet.h @@ -75,4 +75,4 @@ protected: }; } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/avrcp/get_total_number_of_items.h b/system/packet/avrcp/get_total_number_of_items.h index 9f0a8810b4..a2db62adf6 100644 --- a/system/packet/avrcp/get_total_number_of_items.h +++ b/system/packet/avrcp/get_total_number_of_items.h @@ -68,4 +68,4 @@ protected: }; } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/avrcp/list_player_application_setting_attributes.h b/system/packet/avrcp/list_player_application_setting_attributes.h index 800e73cac5..127468e662 100644 --- a/system/packet/avrcp/list_player_application_setting_attributes.h +++ b/system/packet/avrcp/list_player_application_setting_attributes.h @@ -43,4 +43,4 @@ protected: }; } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/avrcp/list_player_application_setting_values.h b/system/packet/avrcp/list_player_application_setting_values.h index c1a2d4227b..d7d6b27d4a 100644 --- a/system/packet/avrcp/list_player_application_setting_values.h +++ b/system/packet/avrcp/list_player_application_setting_values.h @@ -73,4 +73,4 @@ protected: }; } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/avrcp/pass_through_packet.h b/system/packet/avrcp/pass_through_packet.h index 050ed91919..6e7301cf85 100644 --- a/system/packet/avrcp/pass_through_packet.h +++ b/system/packet/avrcp/pass_through_packet.h @@ -73,4 +73,4 @@ protected: }; } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/avrcp/play_item.h b/system/packet/avrcp/play_item.h index 32a2760575..6c46ebdf47 100644 --- a/system/packet/avrcp/play_item.h +++ b/system/packet/avrcp/play_item.h @@ -73,4 +73,4 @@ protected: }; } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/avrcp/register_notification_packet.h b/system/packet/avrcp/register_notification_packet.h index cc6ed1bc01..4d35d7cb0f 100644 --- a/system/packet/avrcp/register_notification_packet.h +++ b/system/packet/avrcp/register_notification_packet.h @@ -164,4 +164,4 @@ protected: }; } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/avrcp/set_absolute_volume.h b/system/packet/avrcp/set_absolute_volume.h index 17125938df..86e1394d12 100644 --- a/system/packet/avrcp/set_absolute_volume.h +++ b/system/packet/avrcp/set_absolute_volume.h @@ -75,4 +75,4 @@ protected: }; } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/avrcp/set_addressed_player.h b/system/packet/avrcp/set_addressed_player.h index b764f5660c..85b64c5ebf 100644 --- a/system/packet/avrcp/set_addressed_player.h +++ b/system/packet/avrcp/set_addressed_player.h @@ -69,4 +69,4 @@ protected: }; } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/avrcp/set_browsed_player.h b/system/packet/avrcp/set_browsed_player.h index 15ccc7bba3..42659caa1a 100644 --- a/system/packet/avrcp/set_browsed_player.h +++ b/system/packet/avrcp/set_browsed_player.h @@ -75,4 +75,4 @@ protected: }; } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/avrcp/set_player_application_setting_value.h b/system/packet/avrcp/set_player_application_setting_value.h index e60b5c45f7..1138527e52 100644 --- a/system/packet/avrcp/set_player_application_setting_value.h +++ b/system/packet/avrcp/set_player_application_setting_value.h @@ -73,4 +73,4 @@ protected: }; } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/avrcp/vendor_packet.h b/system/packet/avrcp/vendor_packet.h index fb28df6136..14f63173b3 100644 --- a/system/packet/avrcp/vendor_packet.h +++ b/system/packet/avrcp/vendor_packet.h @@ -82,4 +82,4 @@ protected: }; } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/base/packet_builder.h b/system/packet/base/packet_builder.h index a7f996e278..37d4a5f59e 100644 --- a/system/packet/base/packet_builder.h +++ b/system/packet/base/packet_builder.h @@ -58,4 +58,4 @@ private: bool AddPayloadOctets(const std::shared_ptr<Packet>& pkt, size_t octets, uint64_t value); }; -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/include/avrcp_packet.h b/system/packet/include/avrcp_packet.h index 773d8fb214..8bddd94e97 100644 --- a/system/packet/include/avrcp_packet.h +++ b/system/packet/include/avrcp_packet.h @@ -34,4 +34,4 @@ #include "avrcp/set_absolute_volume.h" #include "avrcp/set_addressed_player.h" #include "avrcp/set_browsed_player.h" -#include "avrcp/vendor_packet.h"
\ No newline at end of file +#include "avrcp/vendor_packet.h" diff --git a/system/packet/include/packet.h b/system/packet/include/packet.h index 01368af70b..33c31b1710 100644 --- a/system/packet/include/packet.h +++ b/system/packet/include/packet.h @@ -18,4 +18,4 @@ #include "base/iterator.h" #include "base/packet.h" -#include "base/packet_builder.h"
\ No newline at end of file +#include "base/packet_builder.h" diff --git a/system/packet/tests/avrcp/avrcp_browse_packet_test.cc b/system/packet/tests/avrcp/avrcp_browse_packet_test.cc index d5a382514b..2a49eda443 100644 --- a/system/packet/tests/avrcp/avrcp_browse_packet_test.cc +++ b/system/packet/tests/avrcp/avrcp_browse_packet_test.cc @@ -114,4 +114,4 @@ TEST(AvrcpBrowsePacketTest, invalidTest) { } } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/tests/avrcp/avrcp_packet_test.cc b/system/packet/tests/avrcp/avrcp_packet_test.cc index 222609a0df..5995d92697 100644 --- a/system/packet/tests/avrcp/avrcp_packet_test.cc +++ b/system/packet/tests/avrcp/avrcp_packet_test.cc @@ -112,4 +112,4 @@ TEST(AvrcpPacketTest, payloadBoundsTest) { } } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/tests/avrcp/avrcp_reject_packet_test.cc b/system/packet/tests/avrcp/avrcp_reject_packet_test.cc index 1a98875651..0c6aa1ff1c 100644 --- a/system/packet/tests/avrcp/avrcp_reject_packet_test.cc +++ b/system/packet/tests/avrcp/avrcp_reject_packet_test.cc @@ -38,4 +38,4 @@ TEST(RejectPacketBuilderTest, buildPacketTest) { } } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/tests/avrcp/change_path_packet_test.cc b/system/packet/tests/avrcp/change_path_packet_test.cc index 49281b7c31..ef6414db23 100644 --- a/system/packet/tests/avrcp/change_path_packet_test.cc +++ b/system/packet/tests/avrcp/change_path_packet_test.cc @@ -80,4 +80,4 @@ TEST(ChangePathRequestBuilder, builderTest) { } } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/tests/avrcp/get_capabilities_packet_test.cc b/system/packet/tests/avrcp/get_capabilities_packet_test.cc index 114992d891..d448b4c587 100644 --- a/system/packet/tests/avrcp/get_capabilities_packet_test.cc +++ b/system/packet/tests/avrcp/get_capabilities_packet_test.cc @@ -128,4 +128,4 @@ TEST(GetCapabilityResponseBuilder, eventsSupportedBuilderTest) { } } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/tests/avrcp/get_current_player_application_setting_value_test.cc b/system/packet/tests/avrcp/get_current_player_application_setting_value_test.cc index 8c9a775d0e..935ff9142e 100644 --- a/system/packet/tests/avrcp/get_current_player_application_setting_value_test.cc +++ b/system/packet/tests/avrcp/get_current_player_application_setting_value_test.cc @@ -70,4 +70,4 @@ TEST(GetCurrentPlayerApplicationSettingValueResponseBuilderTest, builderTest) { } } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/tests/avrcp/get_folder_items_packet_test.cc b/system/packet/tests/avrcp/get_folder_items_packet_test.cc index 9ad3396a29..f4c37341f8 100644 --- a/system/packet/tests/avrcp/get_folder_items_packet_test.cc +++ b/system/packet/tests/avrcp/get_folder_items_packet_test.cc @@ -246,4 +246,4 @@ TEST(GetFolderItemsRequestBuilderTest, builderTest) { } } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/tests/avrcp/get_play_status_packet_test.cc b/system/packet/tests/avrcp/get_play_status_packet_test.cc index 80c38f6bb9..43a238afc6 100644 --- a/system/packet/tests/avrcp/get_play_status_packet_test.cc +++ b/system/packet/tests/avrcp/get_play_status_packet_test.cc @@ -37,4 +37,4 @@ TEST(GetPlayStatusResponseBuilderTest, builderTest) { } } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/tests/avrcp/get_total_number_of_items_packet_test.cc b/system/packet/tests/avrcp/get_total_number_of_items_packet_test.cc index 9982ec399c..feaf289f88 100644 --- a/system/packet/tests/avrcp/get_total_number_of_items_packet_test.cc +++ b/system/packet/tests/avrcp/get_total_number_of_items_packet_test.cc @@ -69,4 +69,4 @@ TEST(GetTotalNumberOfItemsRequestTest, invalidTest) { } } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/tests/avrcp/list_player_application_setting_attributes_test.cc b/system/packet/tests/avrcp/list_player_application_setting_attributes_test.cc index 48269951ee..4c9ba0c54b 100644 --- a/system/packet/tests/avrcp/list_player_application_setting_attributes_test.cc +++ b/system/packet/tests/avrcp/list_player_application_setting_attributes_test.cc @@ -38,4 +38,4 @@ TEST(ListPlayerApplicationSettingAttributesResponseBuilderTest, builderTest) { } } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/tests/avrcp/list_player_application_setting_values_test.cc b/system/packet/tests/avrcp/list_player_application_setting_values_test.cc index 54ed1d5012..a755d6066b 100644 --- a/system/packet/tests/avrcp/list_player_application_setting_values_test.cc +++ b/system/packet/tests/avrcp/list_player_application_setting_values_test.cc @@ -68,4 +68,4 @@ TEST(ListPlayerApplicationSettingValuesResponseBuilderTest, builderTest) { } } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/tests/avrcp/pass_through_packet_test.cc b/system/packet/tests/avrcp/pass_through_packet_test.cc index 4587b35e29..e182197b66 100644 --- a/system/packet/tests/avrcp/pass_through_packet_test.cc +++ b/system/packet/tests/avrcp/pass_through_packet_test.cc @@ -70,4 +70,4 @@ TEST(PassThroughPacketTest, invalidTest) { } } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/tests/avrcp/set_absolute_volume_packet_test.cc b/system/packet/tests/avrcp/set_absolute_volume_packet_test.cc index 8be462ecd7..8f14a81cbb 100644 --- a/system/packet/tests/avrcp/set_absolute_volume_packet_test.cc +++ b/system/packet/tests/avrcp/set_absolute_volume_packet_test.cc @@ -71,4 +71,4 @@ TEST(SetAbsoluteVolumeResponseTest, invalidTest) { } } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/tests/avrcp/set_browsed_player_packet_test.cc b/system/packet/tests/avrcp/set_browsed_player_packet_test.cc index 3e3a8bbfcd..402d705d17 100644 --- a/system/packet/tests/avrcp/set_browsed_player_packet_test.cc +++ b/system/packet/tests/avrcp/set_browsed_player_packet_test.cc @@ -68,4 +68,4 @@ TEST(SetBrowsedPlayerRequestTest, invalidTest) { } } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/tests/avrcp/set_player_application_setting_value_test.cc b/system/packet/tests/avrcp/set_player_application_setting_value_test.cc index 3fa8d650b2..10c7c29878 100644 --- a/system/packet/tests/avrcp/set_player_application_setting_value_test.cc +++ b/system/packet/tests/avrcp/set_player_application_setting_value_test.cc @@ -70,4 +70,4 @@ TEST(SetPlayerApplicationSettingValueResponseBuilderBuilderTest, builderTest) { } } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/tests/avrcp/vendor_packet_test.cc b/system/packet/tests/avrcp/vendor_packet_test.cc index c826f12992..021a21e9a7 100644 --- a/system/packet/tests/avrcp/vendor_packet_test.cc +++ b/system/packet/tests/avrcp/vendor_packet_test.cc @@ -134,4 +134,4 @@ TEST_F(VendorPacketTest, invalidTest) { } } // namespace avrcp -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/tests/base/packet_builder_test.cc b/system/packet/tests/base/packet_builder_test.cc index f4c862e8d3..d0d554ae9b 100644 --- a/system/packet/tests/base/packet_builder_test.cc +++ b/system/packet/tests/base/packet_builder_test.cc @@ -69,4 +69,4 @@ TEST(PacketBuilderTest, addPayloadOctetsTest) { } } -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/packet/tests/base/packet_test.cc b/system/packet/tests/base/packet_test.cc index 09e172c4ed..48d82fb2c0 100644 --- a/system/packet/tests/base/packet_test.cc +++ b/system/packet/tests/base/packet_test.cc @@ -123,4 +123,4 @@ TEST(PacketTest, memoryFreeTest) { ASSERT_TRUE(data_ptr.expired()); } -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/profile/avrcp/Android.bp b/system/profile/avrcp/Android.bp index 133d2a4712..8db8f11b2a 100644 --- a/system/profile/avrcp/Android.bp +++ b/system/profile/avrcp/Android.bp @@ -81,6 +81,7 @@ cc_test { "libbluetooth_log", "libbtdevice", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libcutils", "libevent", "libgmock", diff --git a/system/profile/avrcp/avrcp_sdp_records.cc b/system/profile/avrcp/avrcp_sdp_records.cc index 57d90ce60b..ab04688a1b 100644 --- a/system/profile/avrcp/avrcp_sdp_records.cc +++ b/system/profile/avrcp/avrcp_sdp_records.cc @@ -98,8 +98,9 @@ uint16_t AvrcSdpRecordHelper::RemoveRecord(const uint16_t request_id) { } else { log::info("Removing the record for service uuid 0x{:x}", service_uuid); bta_sys_remove_uuid(service_uuid); + auto result = AVRC_RemoveRecord(sdp_record_handle_); sdp_record_handle_ = RECORD_NOT_ASSIGNED; - return AVRC_RemoveRecord(sdp_record_handle_); + return result; } } // Nothing to remove. diff --git a/system/profile/avrcp/connection_handler.cc b/system/profile/avrcp/connection_handler.cc index 9608294161..146c079c77 100644 --- a/system/profile/avrcp/connection_handler.cc +++ b/system/profile/avrcp/connection_handler.cc @@ -295,7 +295,6 @@ void ConnectionHandler::InitiatorControlCb(uint8_t handle, uint8_t event, uint16 instance_->vol_->DeviceConnected(newDevice->GetAddress()); } } - } break; case AVRC_CLOSE_IND_EVT: { diff --git a/system/profile/avrcp/connection_handler.h b/system/profile/avrcp/connection_handler.h index f91ed8d641..b02d69a3dd 100644 --- a/system/profile/avrcp/connection_handler.h +++ b/system/profile/avrcp/connection_handler.h @@ -26,8 +26,8 @@ #include "avrcp_internal.h" #include "packet/base/packet.h" #include "profile/avrcp/device.h" -#include "raw_address.h" #include "stack/include/sdp_status.h" +#include "types/raw_address.h" namespace bluetooth { namespace avrcp { diff --git a/system/profile/avrcp/device.cc b/system/profile/avrcp/device.cc index 3167363ca7..0201858318 100644 --- a/system/profile/avrcp/device.cc +++ b/system/profile/avrcp/device.cc @@ -782,7 +782,6 @@ void Device::GetElementAttributesResponse(uint8_t label, } } } else { // zero attributes requested which means all attributes requested - if (!com::android::bluetooth::flags::get_all_element_attributes_empty()) { for (const auto& attribute : info.attributes) { response->AddAttributeEntry(attribute); diff --git a/system/profile/avrcp/device.h b/system/profile/avrcp/device.h index 67dffbad8b..c40d29cea8 100644 --- a/system/profile/avrcp/device.h +++ b/system/profile/avrcp/device.h @@ -44,7 +44,7 @@ #include "packet/avrcp/set_player_application_setting_value.h" #include "packet/avrcp/vendor_packet.h" #include "profile/avrcp/media_id_map.h" -#include "raw_address.h" +#include "types/raw_address.h" namespace bluetooth { namespace avrcp { diff --git a/system/rust/Android.bp b/system/rust/Android.bp index 9e4cca0736..04be44dbec 100644 --- a/system/rust/Android.bp +++ b/system/rust/Android.bp @@ -116,7 +116,6 @@ cc_library_static { "packages/modules/Bluetooth/system/gd", "packages/modules/Bluetooth/system/include", "packages/modules/Bluetooth/system/stack/include", - "packages/modules/Bluetooth/system/types", ], export_include_dirs: ["."], static_libs: [ diff --git a/system/rust/BUILD.gn b/system/rust/BUILD.gn index f9c63f4986..bdfe7c54c8 100644 --- a/system/rust/BUILD.gn +++ b/system/rust/BUILD.gn @@ -32,7 +32,6 @@ static_library("core_rs") { "//bt/system/include", "//bt/system/stack/include", "//bt/system/gd", - "//bt/system/types", ] configs += [ diff --git a/system/rust/src/core/ffi.rs b/system/rust/src/core/ffi.rs index c81235d7f1..506bfd0bad 100644 --- a/system/rust/src/core/ffi.rs +++ b/system/rust/src/core/ffi.rs @@ -65,7 +65,7 @@ mod inner { #[namespace = "bluetooth"] extern "C++" { - include!("bluetooth/uuid.h"); + include!("types/bluetooth/uuid.h"); type Uuid = crate::core::uuid::Uuid; } diff --git a/system/rust/src/gatt/ffi.rs b/system/rust/src/gatt/ffi.rs index 110de114d3..4a54dd9f71 100644 --- a/system/rust/src/gatt/ffi.rs +++ b/system/rust/src/gatt/ffi.rs @@ -41,7 +41,7 @@ mod inner { #[namespace = "bluetooth"] extern "C++" { - include!("bluetooth/uuid.h"); + include!("types/bluetooth/uuid.h"); /// A C++ UUID. type Uuid = crate::core::uuid::Uuid; } diff --git a/system/stack/Android.bp b/system/stack/Android.bp index 0a7b6521c6..155dcd4208 100644 --- a/system/stack/Android.bp +++ b/system/stack/Android.bp @@ -17,7 +17,6 @@ cc_library_static { "packages/modules/Bluetooth/system/gd", "packages/modules/Bluetooth/system/include", "packages/modules/Bluetooth/system/stack/include", - "packages/modules/Bluetooth/system/types", ], static_libs: [ "libbluetooth_log", @@ -69,7 +68,6 @@ cc_library_static { "packages/modules/Bluetooth/system/bta/include", "packages/modules/Bluetooth/system/bta/sys", "packages/modules/Bluetooth/system/btif/include", - "packages/modules/Bluetooth/system/device/include", "packages/modules/Bluetooth/system/gd", "packages/modules/Bluetooth/system/gd/hal", "packages/modules/Bluetooth/system/udrv/include", @@ -368,7 +366,6 @@ cc_defaults { "packages/modules/Bluetooth/system/include", "packages/modules/Bluetooth/system/stack/include", "packages/modules/Bluetooth/system/test/common", - "packages/modules/Bluetooth/system/types", ], static_libs: [ "libchrome", @@ -832,6 +829,7 @@ cc_test { "libbtif", "libbtif-core", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libflags_rust_cpp_bridge", "libfmq", "libg722codec", @@ -933,6 +931,7 @@ cc_test { "libbt-common", "libbt-platform-protos-lite", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "libgmock", "liblog", @@ -1022,6 +1021,7 @@ cc_test { "libbt-common", "libbt-platform-protos-lite", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "libgmock", "liblog", @@ -1157,6 +1157,7 @@ cc_test { "libbt-common", "libbt-platform-protos-lite", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "libgmock", "liblog", @@ -1232,6 +1233,7 @@ cc_test { "libbluetooth_log", "libbt-common", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "libgmock", "liblog", @@ -1306,6 +1308,7 @@ cc_test { "libbluetooth_log", "libbt-common", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "libgmock", "liblog", @@ -1420,6 +1423,7 @@ cc_test { "libbt-sbc-decoder", "libbt-sbc-encoder", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libgmock", "liblog", "libopus", @@ -1475,6 +1479,7 @@ cc_test { "libbluetooth_log", "libbt-common", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "liblog", "libosi", ], @@ -1543,6 +1548,7 @@ cc_test { "libbt-common", "libbt-platform-protos-lite", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "libgmock", "liblog", @@ -1601,6 +1607,7 @@ cc_test { "libbt-common", "libbt-platform-protos-lite", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libgmock", "liblog", "libosi", @@ -1677,6 +1684,7 @@ cc_test { "libbt-common", "libbt-platform-protos-lite", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "libgmock", "liblog", @@ -1715,7 +1723,6 @@ cc_test { ], include_dirs: [ "packages/modules/Bluetooth/system", - "packages/modules/Bluetooth/system/device/include", "packages/modules/Bluetooth/system/gd", ], generated_headers: [ @@ -1869,6 +1876,7 @@ cc_test { "libbtdevice", "libbte", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libgmock", "liblog", "libosi", @@ -1928,6 +1936,7 @@ cc_test { "libbtdevice", "libbte", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "libgmock", "liblog", @@ -2003,6 +2012,7 @@ cc_test { "libbt-platform-protos-lite", "libbtdevice", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "libgmock", "liblog", @@ -2096,6 +2106,7 @@ cc_test { "libbt-platform-protos-lite", "libbtdevice", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "libflagtest", "libgmock", @@ -2193,6 +2204,7 @@ cc_test { "libbt-platform-protos-lite", "libbtdevice", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "libgmock", "liblog", @@ -2291,6 +2303,7 @@ cc_test { "libbt-platform-protos-lite", "libbtdevice", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libcutils", "libevent", "libgmock", @@ -2346,7 +2359,6 @@ cc_test { ], include_dirs: [ "packages/modules/Bluetooth/system", - "packages/modules/Bluetooth/system/device/include", "packages/modules/Bluetooth/system/gd", ], generated_headers: [ diff --git a/system/stack/BUILD.gn b/system/stack/BUILD.gn index dfbdd7db38..ab902f7b5e 100644 --- a/system/stack/BUILD.gn +++ b/system/stack/BUILD.gn @@ -211,7 +211,6 @@ source_set("stack") { "//bt/system/hcis", "//bt/system/linux_include", "//bt/system/rpc/include", - "//bt/system/types", "//bt/system/udrv/include", "//bt/system/vnd/ble", "//bt/system/vnd/include", diff --git a/system/stack/a2dp/a2dp_aac.cc b/system/stack/a2dp/a2dp_aac.cc index ca0dec4037..8ae4d68ede 100644 --- a/system/stack/a2dp/a2dp_aac.cc +++ b/system/stack/a2dp/a2dp_aac.cc @@ -28,10 +28,22 @@ #include <bluetooth/log.h> #include <string.h> +#include <algorithm> +#include <cstdint> +#include <ios> +#include <mutex> +#include <sstream> +#include <string> + +#include "a2dp_aac_constants.h" #include "a2dp_aac_decoder.h" #include "a2dp_aac_encoder.h" +#include "a2dp_api.h" +#include "a2dp_codec_api.h" +#include "a2dp_constants.h" +#include "avdt_api.h" +#include "hardware/bt_av.h" #include "internal_include/bt_trace.h" -#include "osi/include/osi.h" #include "osi/include/properties.h" #include "stack/include/bt_hdr.h" @@ -592,36 +604,36 @@ std::string A2DP_CodecInfoStringAac(const uint8_t* p_codec_info) { // Object type field.clear(); - AppendField(&field, (aac_cie.objectType == 0), "NONE"); - AppendField(&field, (aac_cie.objectType & A2DP_AAC_OBJECT_TYPE_MPEG2_LC), "(MPEG-2 AAC LC)"); - AppendField(&field, (aac_cie.objectType & A2DP_AAC_OBJECT_TYPE_MPEG4_LC), "(MPEG-4 AAC LC)"); - AppendField(&field, (aac_cie.objectType & A2DP_AAC_OBJECT_TYPE_MPEG4_LTP), "(MPEG-4 AAC LTP)"); - AppendField(&field, (aac_cie.objectType & A2DP_AAC_OBJECT_TYPE_MPEG4_SCALABLE), + AppendField(&field, aac_cie.objectType == 0, "NONE"); + AppendField(&field, aac_cie.objectType & A2DP_AAC_OBJECT_TYPE_MPEG2_LC, "(MPEG-2 AAC LC)"); + AppendField(&field, aac_cie.objectType & A2DP_AAC_OBJECT_TYPE_MPEG4_LC, "(MPEG-4 AAC LC)"); + AppendField(&field, aac_cie.objectType & A2DP_AAC_OBJECT_TYPE_MPEG4_LTP, "(MPEG-4 AAC LTP)"); + AppendField(&field, aac_cie.objectType & A2DP_AAC_OBJECT_TYPE_MPEG4_SCALABLE, "(MPEG-4 AAC Scalable)"); res << "\tobjectType: " << field << " (" << loghex(aac_cie.objectType) << ")\n"; // Sample frequency field.clear(); - AppendField(&field, (aac_cie.sampleRate == 0), "NONE"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_8000), "8000"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_11025), "11025"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_12000), "12000"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_16000), "16000"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_22050), "22050"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_24000), "24000"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_32000), "32000"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_44100), "44100"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_48000), "48000"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_64000), "64000"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_88200), "88200"); - AppendField(&field, (aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_96000), "96000"); + AppendField(&field, aac_cie.sampleRate == 0, "NONE"); + AppendField(&field, aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_8000, "8000"); + AppendField(&field, aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_11025, "11025"); + AppendField(&field, aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_12000, "12000"); + AppendField(&field, aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_16000, "16000"); + AppendField(&field, aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_22050, "22050"); + AppendField(&field, aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_24000, "24000"); + AppendField(&field, aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_32000, "32000"); + AppendField(&field, aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_44100, "44100"); + AppendField(&field, aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_48000, "48000"); + AppendField(&field, aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_64000, "64000"); + AppendField(&field, aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_88200, "88200"); + AppendField(&field, aac_cie.sampleRate & A2DP_AAC_SAMPLING_FREQ_96000, "96000"); res << "\tsamp_freq: " << field << " (" << loghex(aac_cie.sampleRate) << ")\n"; // Channel mode field.clear(); - AppendField(&field, (aac_cie.channelMode == 0), "NONE"); - AppendField(&field, (aac_cie.channelMode == A2DP_AAC_CHANNEL_MODE_MONO), "Mono"); - AppendField(&field, (aac_cie.channelMode == A2DP_AAC_CHANNEL_MODE_STEREO), "Stereo"); + AppendField(&field, aac_cie.channelMode == 0, "NONE"); + AppendField(&field, aac_cie.channelMode == A2DP_AAC_CHANNEL_MODE_MONO, "Mono"); + AppendField(&field, aac_cie.channelMode == A2DP_AAC_CHANNEL_MODE_STEREO, "Stereo"); res << "\tch_mode: " << field << " (" << loghex(aac_cie.channelMode) << ")\n"; // Variable bit rate support @@ -634,8 +646,7 @@ std::string A2DP_CodecInfoStringAac(const uint8_t* p_codec_info) { return res.str(); } -const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterfaceAac( - const uint8_t* p_codec_info) { +const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterfaceAac(const uint8_t* p_codec_info) { if (!A2DP_IsCodecValidAac(p_codec_info)) { return NULL; } @@ -643,8 +654,7 @@ const tA2DP_ENCODER_INTERFACE* A2DP_GetEncoderInterfaceAac( return &a2dp_encoder_interface_aac; } -const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterfaceAac( - const uint8_t* p_codec_info) { +const tA2DP_DECODER_INTERFACE* A2DP_GetDecoderInterfaceAac(const uint8_t* p_codec_info) { if (!A2DP_IsCodecValidAac(p_codec_info)) { return NULL; } diff --git a/system/stack/a2dp/a2dp_aac_decoder.cc b/system/stack/a2dp/a2dp_aac_decoder.cc index fba7ea44cf..999546ceb7 100644 --- a/system/stack/a2dp/a2dp_aac_decoder.cc +++ b/system/stack/a2dp/a2dp_aac_decoder.cc @@ -21,6 +21,13 @@ #include <aacdecoder_lib.h> #include <bluetooth/log.h> +#include <cstddef> +#include <cstdint> +#include <cstring> + +#include "FDK_audio.h" +#include "a2dp_codec_api.h" +#include "machine_type.h" #include "osi/include/allocator.h" #include "stack/include/bt_hdr.h" diff --git a/system/stack/a2dp/a2dp_aac_encoder.cc b/system/stack/a2dp/a2dp_aac_encoder.cc index 774fdd92ae..db455cda32 100644 --- a/system/stack/a2dp/a2dp_aac_encoder.cc +++ b/system/stack/a2dp/a2dp_aac_encoder.cc @@ -18,12 +18,20 @@ #include "a2dp_aac_encoder.h" +#include <FDK_audio.h> #include <aacenc_lib.h> #include <bluetooth/log.h> #include <inttypes.h> +#include <stdio.h> #include <string.h> +#include <algorithm> +#include <cstdint> + #include "a2dp_aac.h" +#include "a2dp_aac_constants.h" +#include "a2dp_codec_api.h" +#include "avdt_api.h" #include "common/time_util.h" #include "internal_include/bt_target.h" #include "osi/include/allocator.h" diff --git a/system/stack/a2dp/a2dp_api.cc b/system/stack/a2dp/a2dp_api.cc index 574eb16d07..4374867f15 100644 --- a/system/stack/a2dp/a2dp_api.cc +++ b/system/stack/a2dp/a2dp_api.cc @@ -29,10 +29,15 @@ #include <bluetooth/log.h> #include <string.h> +#include <cstdint> + +#include "a2dp_constants.h" #include "a2dp_int.h" #include "avdt_api.h" #include "internal_include/bt_target.h" #include "osi/include/allocator.h" +#include "sdp_discovery_db.h" +#include "sdp_status.h" #include "sdpdefs.h" #include "stack/include/bt_types.h" #include "stack/include/bt_uuid16.h" @@ -139,7 +144,6 @@ static void a2dp_sdp_cback(const RawAddress& /* bd_addr */, tSDP_STATUS status) /* we've got everything, we're done */ found = true; break; - } while (true); } diff --git a/system/stack/a2dp/a2dp_codec_config.cc b/system/stack/a2dp/a2dp_codec_config.cc index 4a39e0c93b..2469cbcbb7 100644 --- a/system/stack/a2dp/a2dp_codec_config.cc +++ b/system/stack/a2dp/a2dp_codec_config.cc @@ -21,6 +21,18 @@ #define LOG_TAG "bluetooth-a2dp" #include <bluetooth/log.h> +#include <stdio.h> + +#include <cstddef> +#include <cstdint> +#include <cstring> +#include <ios> +#include <mutex> +#include <optional> +#include <sstream> +#include <string> +#include <utility> +#include <vector> #include "a2dp_aac.h" #include "a2dp_codec_api.h" @@ -28,6 +40,12 @@ #include "a2dp_ext.h" #include "a2dp_sbc.h" #include "a2dp_vendor.h" +#include "a2dp_vendor_aptx_constants.h" +#include "a2dp_vendor_aptx_hd_constants.h" +#include "a2dp_vendor_ldac_constants.h" +#include "avdt_api.h" +#include "device/include/device_iot_conf_defs.h" +#include "hardware/bt_av.h" #if !defined(EXCLUDE_NONSTANDARD_CODECS) #include "a2dp_vendor_aptx.h" @@ -38,8 +56,6 @@ #include "audio_hal_interface/a2dp_encoding.h" #include "bta/av/bta_av_int.h" -#include "device/include/device_iot_config.h" -#include "internal_include/bt_trace.h" #include "osi/include/properties.h" #include "stack/include/bt_hdr.h" @@ -1257,87 +1273,123 @@ bool A2DP_CodecTypeEquals(const uint8_t* p_codec_info_a, const uint8_t* p_codec_ } bool A2DP_CodecEquals(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { - tA2DP_CODEC_TYPE codec_type_a = A2DP_GetCodecType(p_codec_info_a); - tA2DP_CODEC_TYPE codec_type_b = A2DP_GetCodecType(p_codec_info_b); + auto codec_id_a = bluetooth::a2dp::ParseCodecId(p_codec_info_a); + auto codec_id_b = bluetooth::a2dp::ParseCodecId(p_codec_info_b); - if (codec_type_a != codec_type_b) { + if (!codec_id_a.has_value() || !codec_id_b.has_value() || codec_id_a != codec_id_b) { return false; } - switch (codec_type_a) { - case A2DP_MEDIA_CT_SBC: + switch (codec_id_a.value()) { + case bluetooth::a2dp::CodecId::SBC: return A2DP_CodecEqualsSbc(p_codec_info_a, p_codec_info_b); #if !defined(EXCLUDE_NONSTANDARD_CODECS) - case A2DP_MEDIA_CT_AAC: + case bluetooth::a2dp::CodecId::AAC: return A2DP_CodecEqualsAac(p_codec_info_a, p_codec_info_b); - case A2DP_MEDIA_CT_NON_A2DP: - return A2DP_VendorCodecEquals(p_codec_info_a, p_codec_info_b); + case bluetooth::a2dp::CodecId::APTX: + return A2DP_VendorCodecEqualsAptx(p_codec_info_a, p_codec_info_b); + case bluetooth::a2dp::CodecId::APTX_HD: + return A2DP_VendorCodecEqualsAptxHd(p_codec_info_a, p_codec_info_b); + case bluetooth::a2dp::CodecId::LDAC: + return A2DP_VendorCodecEqualsLdac(p_codec_info_a, p_codec_info_b); + case bluetooth::a2dp::CodecId::OPUS: + return A2DP_VendorCodecEqualsOpus(p_codec_info_a, p_codec_info_b); #endif default: break; } - log::error("unsupported codec type 0x{:x}", codec_type_a); + log::error("unsupported codec id 0x{:x}", codec_id_a.value()); return false; } int A2DP_GetTrackSampleRate(const uint8_t* p_codec_info) { - tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info); + auto codec_id = bluetooth::a2dp::ParseCodecId(p_codec_info); - switch (codec_type) { - case A2DP_MEDIA_CT_SBC: + if (!codec_id.has_value()) { + return -1; + } + + switch (codec_id.value()) { + case bluetooth::a2dp::CodecId::SBC: return A2DP_GetTrackSampleRateSbc(p_codec_info); #if !defined(EXCLUDE_NONSTANDARD_CODECS) - case A2DP_MEDIA_CT_AAC: + case bluetooth::a2dp::CodecId::AAC: return A2DP_GetTrackSampleRateAac(p_codec_info); - case A2DP_MEDIA_CT_NON_A2DP: - return A2DP_VendorGetTrackSampleRate(p_codec_info); + case bluetooth::a2dp::CodecId::APTX: + return A2DP_VendorGetTrackSampleRateAptx(p_codec_info); + case bluetooth::a2dp::CodecId::APTX_HD: + return A2DP_VendorGetTrackSampleRateAptxHd(p_codec_info); + case bluetooth::a2dp::CodecId::LDAC: + return A2DP_VendorGetTrackSampleRateLdac(p_codec_info); + case bluetooth::a2dp::CodecId::OPUS: + return A2DP_VendorGetTrackSampleRateOpus(p_codec_info); #endif default: break; } - log::error("unsupported codec type 0x{:x}", codec_type); + log::error("unsupported codec id 0x{:x}", codec_id.value()); return -1; } int A2DP_GetTrackBitsPerSample(const uint8_t* p_codec_info) { - tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info); + auto codec_id = bluetooth::a2dp::ParseCodecId(p_codec_info); - switch (codec_type) { - case A2DP_MEDIA_CT_SBC: + if (!codec_id.has_value()) { + return -1; + } + + switch (codec_id.value()) { + case bluetooth::a2dp::CodecId::SBC: return A2DP_GetTrackBitsPerSampleSbc(p_codec_info); #if !defined(EXCLUDE_NONSTANDARD_CODECS) - case A2DP_MEDIA_CT_AAC: + case bluetooth::a2dp::CodecId::AAC: return A2DP_GetTrackBitsPerSampleAac(p_codec_info); - case A2DP_MEDIA_CT_NON_A2DP: - return A2DP_VendorGetTrackBitsPerSample(p_codec_info); + case bluetooth::a2dp::CodecId::APTX: + return A2DP_VendorGetTrackBitsPerSampleAptx(p_codec_info); + case bluetooth::a2dp::CodecId::APTX_HD: + return A2DP_VendorGetTrackBitsPerSampleAptxHd(p_codec_info); + case bluetooth::a2dp::CodecId::LDAC: + return A2DP_VendorGetTrackBitsPerSampleLdac(p_codec_info); + case bluetooth::a2dp::CodecId::OPUS: + return A2DP_VendorGetTrackBitsPerSampleOpus(p_codec_info); #endif default: break; } - log::error("unsupported codec type 0x{:x}", codec_type); + log::error("unsupported codec id 0x{:x}", codec_id.value()); return -1; } int A2DP_GetTrackChannelCount(const uint8_t* p_codec_info) { - tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info); + auto codec_id = bluetooth::a2dp::ParseCodecId(p_codec_info); - switch (codec_type) { - case A2DP_MEDIA_CT_SBC: + if (!codec_id.has_value()) { + return -1; + } + + switch (codec_id.value()) { + case bluetooth::a2dp::CodecId::SBC: return A2DP_GetTrackChannelCountSbc(p_codec_info); #if !defined(EXCLUDE_NONSTANDARD_CODECS) - case A2DP_MEDIA_CT_AAC: + case bluetooth::a2dp::CodecId::AAC: return A2DP_GetTrackChannelCountAac(p_codec_info); - case A2DP_MEDIA_CT_NON_A2DP: - return A2DP_VendorGetTrackChannelCount(p_codec_info); + case bluetooth::a2dp::CodecId::APTX: + return A2DP_VendorGetTrackChannelCountAptx(p_codec_info); + case bluetooth::a2dp::CodecId::APTX_HD: + return A2DP_VendorGetTrackChannelCountAptxHd(p_codec_info); + case bluetooth::a2dp::CodecId::LDAC: + return A2DP_VendorGetTrackChannelCountLdac(p_codec_info); + case bluetooth::a2dp::CodecId::OPUS: + return A2DP_VendorGetTrackChannelCountOpus(p_codec_info); #endif default: break; } - log::error("unsupported codec type 0x{:x}", codec_type); + log::error("unsupported codec id 0x{:x}", codec_id.value()); return -1; } @@ -1363,22 +1415,32 @@ int A2DP_GetSinkTrackChannelType(const uint8_t* p_codec_info) { bool A2DP_GetPacketTimestamp(const uint8_t* p_codec_info, const uint8_t* p_data, uint32_t* p_timestamp) { - tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info); + auto codec_id = bluetooth::a2dp::ParseCodecId(p_codec_info); - switch (codec_type) { - case A2DP_MEDIA_CT_SBC: + if (!codec_id.has_value()) { + return false; + } + + switch (codec_id.value()) { + case bluetooth::a2dp::CodecId::SBC: return A2DP_GetPacketTimestampSbc(p_codec_info, p_data, p_timestamp); #if !defined(EXCLUDE_NONSTANDARD_CODECS) - case A2DP_MEDIA_CT_AAC: + case bluetooth::a2dp::CodecId::AAC: return A2DP_GetPacketTimestampAac(p_codec_info, p_data, p_timestamp); - case A2DP_MEDIA_CT_NON_A2DP: - return A2DP_VendorGetPacketTimestamp(p_codec_info, p_data, p_timestamp); + case bluetooth::a2dp::CodecId::APTX: + return A2DP_VendorGetPacketTimestampAptx(p_codec_info, p_data, p_timestamp); + case bluetooth::a2dp::CodecId::APTX_HD: + return A2DP_VendorGetPacketTimestampAptxHd(p_codec_info, p_data, p_timestamp); + case bluetooth::a2dp::CodecId::LDAC: + return A2DP_VendorGetPacketTimestampLdac(p_codec_info, p_data, p_timestamp); + case bluetooth::a2dp::CodecId::OPUS: + return A2DP_VendorGetPacketTimestampOpus(p_codec_info, p_data, p_timestamp); #endif default: break; } - log::error("unsupported codec type 0x{:x}", codec_type); + log::error("unsupported codec id 0x{:x}", codec_id.value()); return false; } diff --git a/system/stack/a2dp/a2dp_ext.cc b/system/stack/a2dp/a2dp_ext.cc index fa2ca6f91c..a01bc15fe1 100644 --- a/system/stack/a2dp/a2dp_ext.cc +++ b/system/stack/a2dp/a2dp_ext.cc @@ -20,8 +20,15 @@ #include <bluetooth/log.h> +#include <cstddef> +#include <cstdint> +#include <cstring> +#include <vector> + #include "a2dp_codec_api.h" +#include "a2dp_constants.h" #include "audio_hal_interface/a2dp_encoding.h" +#include "hardware/bt_av.h" using namespace bluetooth; diff --git a/system/stack/a2dp/a2dp_sbc.cc b/system/stack/a2dp/a2dp_sbc.cc index bec3ab1dd3..cac37e686e 100644 --- a/system/stack/a2dp/a2dp_sbc.cc +++ b/system/stack/a2dp/a2dp_sbc.cc @@ -30,11 +30,21 @@ #include <bluetooth/log.h> #include <string.h> +#include <cstdint> +#include <mutex> +#include <sstream> +#include <string> + +#include "a2dp_api.h" +#include "a2dp_codec_api.h" +#include "a2dp_constants.h" +#include "a2dp_sbc_constants.h" #include "a2dp_sbc_decoder.h" #include "a2dp_sbc_encoder.h" +#include "avdt_api.h" #include "embdrv/sbc/encoder/include/sbc_encoder.h" +#include "hardware/bt_av.h" #include "internal_include/bt_trace.h" -#include "osi/include/osi.h" #include "stack/include/bt_hdr.h" #define A2DP_SBC_MAX_BITPOOL 53 diff --git a/system/stack/a2dp/a2dp_sbc_decoder.cc b/system/stack/a2dp/a2dp_sbc_decoder.cc index 7780bd0b59..b3d288107b 100644 --- a/system/stack/a2dp/a2dp_sbc_decoder.cc +++ b/system/stack/a2dp/a2dp_sbc_decoder.cc @@ -20,7 +20,12 @@ #include <bluetooth/log.h> +#include <cstddef> +#include <cstdint> + +#include "a2dp_codec_api.h" #include "embdrv/sbc/decoder/include/oi_codec_sbc.h" +#include "embdrv/sbc/decoder/include/oi_cpu_dep.h" #include "embdrv/sbc/decoder/include/oi_status.h" #include "stack/include/bt_hdr.h" diff --git a/system/stack/a2dp/a2dp_sbc_encoder.cc b/system/stack/a2dp/a2dp_sbc_encoder.cc index e5cb555262..fb455e219b 100644 --- a/system/stack/a2dp/a2dp_sbc_encoder.cc +++ b/system/stack/a2dp/a2dp_sbc_encoder.cc @@ -23,16 +23,21 @@ #include <bluetooth/log.h> #include <limits.h> +#include <stdio.h> #include <string.h> #include <cinttypes> +#include <cstdint> +#include "a2dp_api.h" +#include "a2dp_codec_api.h" #include "a2dp_sbc.h" +#include "a2dp_sbc_constants.h" #include "a2dp_sbc_up_sample.h" +#include "avdt_api.h" #include "common/time_util.h" #include "embdrv/sbc/encoder/include/sbc_encoder.h" #include "internal_include/bt_target.h" -#include "os/logging/log_adapter.h" #include "osi/include/allocator.h" #include "stack/include/bt_hdr.h" diff --git a/system/stack/a2dp/a2dp_sbc_up_sample.cc b/system/stack/a2dp/a2dp_sbc_up_sample.cc index a3fc893028..f1019d42b6 100644 --- a/system/stack/a2dp/a2dp_sbc_up_sample.cc +++ b/system/stack/a2dp/a2dp_sbc_up_sample.cc @@ -25,6 +25,8 @@ #include "a2dp_sbc_up_sample.h" +#include <cstdint> + typedef int(tA2DP_SBC_ACT)(void* p_src, void* p_dst, uint32_t src_samples, uint32_t dst_samples, uint32_t* p_ret); @@ -234,7 +236,6 @@ int a2dp_sbc_up_sample_16m(void* p_src, void* p_dst, uint32_t src_samples, uint3 a2dp_sbc_ups_cb.cur_pos -= src_sps; dst_samples--; dst_samples--; - } while (a2dp_sbc_ups_cb.cur_pos > 0 && dst_samples); a2dp_sbc_ups_cb.cur_pos += dst_sps; @@ -362,7 +363,6 @@ int a2dp_sbc_up_sample_8m(void* p_src, void* p_dst, uint32_t src_samples, uint32 a2dp_sbc_ups_cb.cur_pos -= src_sps; dst_samples -= 4; - } while (a2dp_sbc_ups_cb.cur_pos > 0 && dst_samples); a2dp_sbc_ups_cb.cur_pos += dst_sps; diff --git a/system/stack/a2dp/a2dp_vendor.cc b/system/stack/a2dp/a2dp_vendor.cc index b178c3c900..74f1b5cbad 100644 --- a/system/stack/a2dp/a2dp_vendor.cc +++ b/system/stack/a2dp/a2dp_vendor.cc @@ -22,12 +22,22 @@ #include "a2dp_vendor.h" -#include <bluetooth/log.h> +#include <cstddef> +#include <cstdint> +#include <string> +#include "a2dp_codec_api.h" +#include "a2dp_constants.h" #include "a2dp_vendor_aptx.h" +#include "a2dp_vendor_aptx_constants.h" #include "a2dp_vendor_aptx_hd.h" +#include "a2dp_vendor_aptx_hd_constants.h" #include "a2dp_vendor_ldac.h" +#include "a2dp_vendor_ldac_constants.h" #include "a2dp_vendor_opus.h" +#include "a2dp_vendor_opus_constants.h" +#include "avdt_api.h" +#include "hardware/bt_av.h" #include "stack/include/bt_hdr.h" bool A2DP_IsVendorSourceCodecValid(const uint8_t* p_codec_info) { @@ -233,49 +243,6 @@ bool A2DP_VendorCodecTypeEquals(const uint8_t* p_codec_info_a, const uint8_t* p_ return true; } -bool A2DP_VendorCodecEquals(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b) { - tA2DP_CODEC_TYPE codec_type_a = A2DP_GetCodecType(p_codec_info_a); - tA2DP_CODEC_TYPE codec_type_b = A2DP_GetCodecType(p_codec_info_b); - - if ((codec_type_a != codec_type_b) || (codec_type_a != A2DP_MEDIA_CT_NON_A2DP)) { - return false; - } - - uint32_t vendor_id_a = A2DP_VendorCodecGetVendorId(p_codec_info_a); - uint16_t codec_id_a = A2DP_VendorCodecGetCodecId(p_codec_info_a); - uint32_t vendor_id_b = A2DP_VendorCodecGetVendorId(p_codec_info_b); - uint16_t codec_id_b = A2DP_VendorCodecGetCodecId(p_codec_info_b); - - if ((vendor_id_a != vendor_id_b) || (codec_id_a != codec_id_b)) { - return false; - } - - // Check for aptX - if (vendor_id_a == A2DP_APTX_VENDOR_ID && codec_id_a == A2DP_APTX_CODEC_ID_BLUETOOTH) { - return A2DP_VendorCodecEqualsAptx(p_codec_info_a, p_codec_info_b); - } - - // Check for aptX-HD - if (vendor_id_a == A2DP_APTX_HD_VENDOR_ID && codec_id_a == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { - return A2DP_VendorCodecEqualsAptxHd(p_codec_info_a, p_codec_info_b); - } - - // Check for LDAC - if (vendor_id_a == A2DP_LDAC_VENDOR_ID && codec_id_a == A2DP_LDAC_CODEC_ID) { - return A2DP_VendorCodecEqualsLdac(p_codec_info_a, p_codec_info_b); - } - - // Check for Opus - if (vendor_id_a == A2DP_OPUS_VENDOR_ID && codec_id_a == A2DP_OPUS_CODEC_ID) { - return A2DP_VendorCodecEqualsOpus(p_codec_info_a, p_codec_info_b); - } - - // Add extra vendor-specific checks based on the - // vendor-specific data stored in "p_codec_info_a" and "p_codec_info_b". - - return false; -} - int A2DP_VendorGetBitRate(const uint8_t* p_codec_info) { uint32_t vendor_id = A2DP_VendorCodecGetVendorId(p_codec_info); uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); @@ -305,93 +272,6 @@ int A2DP_VendorGetBitRate(const uint8_t* p_codec_info) { return -1; } -int A2DP_VendorGetTrackSampleRate(const uint8_t* p_codec_info) { - uint32_t vendor_id = A2DP_VendorCodecGetVendorId(p_codec_info); - uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); - - // Check for aptX - if (vendor_id == A2DP_APTX_VENDOR_ID && codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { - return A2DP_VendorGetTrackSampleRateAptx(p_codec_info); - } - - // Check for aptX-HD - if (vendor_id == A2DP_APTX_HD_VENDOR_ID && codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { - return A2DP_VendorGetTrackSampleRateAptxHd(p_codec_info); - } - - // Check for LDAC - if (vendor_id == A2DP_LDAC_VENDOR_ID && codec_id == A2DP_LDAC_CODEC_ID) { - return A2DP_VendorGetTrackSampleRateLdac(p_codec_info); - } - - // Check for Opus - if (vendor_id == A2DP_OPUS_VENDOR_ID && codec_id == A2DP_OPUS_CODEC_ID) { - return A2DP_VendorGetTrackSampleRateOpus(p_codec_info); - } - - // Add checks based on <vendor_id, codec_id> - - return -1; -} - -int A2DP_VendorGetTrackBitsPerSample(const uint8_t* p_codec_info) { - uint32_t vendor_id = A2DP_VendorCodecGetVendorId(p_codec_info); - uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); - - // Check for aptX - if (vendor_id == A2DP_APTX_VENDOR_ID && codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { - return A2DP_VendorGetTrackBitsPerSampleAptx(p_codec_info); - } - - // Check for aptX-HD - if (vendor_id == A2DP_APTX_HD_VENDOR_ID && codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { - return A2DP_VendorGetTrackBitsPerSampleAptxHd(p_codec_info); - } - - // Check for LDAC - if (vendor_id == A2DP_LDAC_VENDOR_ID && codec_id == A2DP_LDAC_CODEC_ID) { - return A2DP_VendorGetTrackBitsPerSampleLdac(p_codec_info); - } - - // Check for Opus - if (vendor_id == A2DP_OPUS_VENDOR_ID && codec_id == A2DP_OPUS_CODEC_ID) { - return A2DP_VendorGetTrackBitsPerSampleOpus(p_codec_info); - } - - // Add checks based on <vendor_id, codec_id> - - return -1; -} - -int A2DP_VendorGetTrackChannelCount(const uint8_t* p_codec_info) { - uint32_t vendor_id = A2DP_VendorCodecGetVendorId(p_codec_info); - uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); - - // Check for aptX - if (vendor_id == A2DP_APTX_VENDOR_ID && codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { - return A2DP_VendorGetTrackChannelCountAptx(p_codec_info); - } - - // Check for aptX-HD - if (vendor_id == A2DP_APTX_HD_VENDOR_ID && codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { - return A2DP_VendorGetTrackChannelCountAptxHd(p_codec_info); - } - - // Check for LDAC - if (vendor_id == A2DP_LDAC_VENDOR_ID && codec_id == A2DP_LDAC_CODEC_ID) { - return A2DP_VendorGetTrackChannelCountLdac(p_codec_info); - } - - // Check for Opus - if (vendor_id == A2DP_OPUS_VENDOR_ID && codec_id == A2DP_OPUS_CODEC_ID) { - return A2DP_VendorGetTrackChannelCountOpus(p_codec_info); - } - - // Add checks based on <vendor_id, codec_id> - - return -1; -} - int A2DP_VendorGetSinkTrackChannelType(const uint8_t* p_codec_info) { uint32_t vendor_id = A2DP_VendorCodecGetVendorId(p_codec_info); uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); @@ -412,36 +292,6 @@ int A2DP_VendorGetSinkTrackChannelType(const uint8_t* p_codec_info) { return -1; } -bool A2DP_VendorGetPacketTimestamp(const uint8_t* p_codec_info, const uint8_t* p_data, - uint32_t* p_timestamp) { - uint32_t vendor_id = A2DP_VendorCodecGetVendorId(p_codec_info); - uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info); - - // Check for aptX - if (vendor_id == A2DP_APTX_VENDOR_ID && codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH) { - return A2DP_VendorGetPacketTimestampAptx(p_codec_info, p_data, p_timestamp); - } - - // Check for aptX-HD - if (vendor_id == A2DP_APTX_HD_VENDOR_ID && codec_id == A2DP_APTX_HD_CODEC_ID_BLUETOOTH) { - return A2DP_VendorGetPacketTimestampAptxHd(p_codec_info, p_data, p_timestamp); - } - - // Check for LDAC - if (vendor_id == A2DP_LDAC_VENDOR_ID && codec_id == A2DP_LDAC_CODEC_ID) { - return A2DP_VendorGetPacketTimestampLdac(p_codec_info, p_data, p_timestamp); - } - - // Check for Opus - if (vendor_id == A2DP_OPUS_VENDOR_ID && codec_id == A2DP_OPUS_CODEC_ID) { - return A2DP_VendorGetPacketTimestampOpus(p_codec_info, p_data, p_timestamp); - } - - // Add checks based on <vendor_id, codec_id> - - return false; -} - bool A2DP_VendorBuildCodecHeader(const uint8_t* p_codec_info, BT_HDR* p_buf, uint16_t frames_per_packet) { uint32_t vendor_id = A2DP_VendorCodecGetVendorId(p_codec_info); diff --git a/system/stack/a2dp/a2dp_vendor_aptx.cc b/system/stack/a2dp/a2dp_vendor_aptx.cc index 461e044146..203dd5e847 100644 --- a/system/stack/a2dp/a2dp_vendor_aptx.cc +++ b/system/stack/a2dp/a2dp_vendor_aptx.cc @@ -28,11 +28,21 @@ #include <bluetooth/log.h> #include <string.h> +#include <cstdint> +#include <mutex> +#include <sstream> +#include <string> + +#include "a2dp_api.h" +#include "a2dp_codec_api.h" +#include "a2dp_constants.h" #include "a2dp_vendor.h" +#include "a2dp_vendor_aptx_constants.h" #include "a2dp_vendor_aptx_encoder.h" +#include "avdt_api.h" #include "btif/include/btif_av_co.h" +#include "hardware/bt_av.h" #include "internal_include/bt_trace.h" -#include "osi/include/osi.h" #include "stack/include/bt_hdr.h" using namespace bluetooth; diff --git a/system/stack/a2dp/a2dp_vendor_aptx_encoder.cc b/system/stack/a2dp/a2dp_vendor_aptx_encoder.cc index 7bb81bf244..2aff6b14dc 100644 --- a/system/stack/a2dp/a2dp_vendor_aptx_encoder.cc +++ b/system/stack/a2dp/a2dp_vendor_aptx_encoder.cc @@ -19,13 +19,17 @@ #include "a2dp_vendor_aptx_encoder.h" #include <bluetooth/log.h> -#include <dlfcn.h> #include <inttypes.h> +#include <stdio.h> #include <string.h> +#include <cstdint> + +#include "a2dp_codec_api.h" #include "a2dp_vendor.h" #include "a2dp_vendor_aptx.h" #include "aptXbtenc.h" +#include "avdt_api.h" #include "common/time_util.h" #include "internal_include/bt_target.h" #include "osi/include/allocator.h" diff --git a/system/stack/a2dp/a2dp_vendor_aptx_hd.cc b/system/stack/a2dp/a2dp_vendor_aptx_hd.cc index e7dfd57f72..2f92aff69c 100644 --- a/system/stack/a2dp/a2dp_vendor_aptx_hd.cc +++ b/system/stack/a2dp/a2dp_vendor_aptx_hd.cc @@ -28,11 +28,21 @@ #include <bluetooth/log.h> #include <string.h> +#include <cstdint> +#include <mutex> +#include <sstream> +#include <string> + +#include "a2dp_api.h" +#include "a2dp_codec_api.h" +#include "a2dp_constants.h" #include "a2dp_vendor.h" +#include "a2dp_vendor_aptx_hd_constants.h" #include "a2dp_vendor_aptx_hd_encoder.h" +#include "avdt_api.h" #include "btif/include/btif_av_co.h" +#include "hardware/bt_av.h" #include "internal_include/bt_trace.h" -#include "osi/include/osi.h" #include "stack/include/bt_hdr.h" using namespace bluetooth; diff --git a/system/stack/a2dp/a2dp_vendor_aptx_hd_encoder.cc b/system/stack/a2dp/a2dp_vendor_aptx_hd_encoder.cc index b6996d0108..83dbfc88dc 100644 --- a/system/stack/a2dp/a2dp_vendor_aptx_hd_encoder.cc +++ b/system/stack/a2dp/a2dp_vendor_aptx_hd_encoder.cc @@ -19,13 +19,17 @@ #include "a2dp_vendor_aptx_hd_encoder.h" #include <bluetooth/log.h> -#include <dlfcn.h> #include <inttypes.h> +#include <stdio.h> #include <string.h> +#include <cstdint> + +#include "a2dp_codec_api.h" #include "a2dp_vendor.h" #include "a2dp_vendor_aptx_hd.h" #include "aptXHDbtenc.h" +#include "avdt_api.h" #include "common/time_util.h" #include "internal_include/bt_target.h" #include "osi/include/allocator.h" diff --git a/system/stack/a2dp/a2dp_vendor_ldac.cc b/system/stack/a2dp/a2dp_vendor_ldac.cc index 8c1519eb65..951be4c35b 100644 --- a/system/stack/a2dp/a2dp_vendor_ldac.cc +++ b/system/stack/a2dp/a2dp_vendor_ldac.cc @@ -28,11 +28,21 @@ #include <bluetooth/log.h> #include <string.h> +#include <cstdint> +#include <mutex> +#include <sstream> +#include <string> + +#include "a2dp_api.h" +#include "a2dp_codec_api.h" +#include "a2dp_constants.h" +#include "a2dp_vendor_ldac_constants.h" #include "a2dp_vendor_ldac_decoder.h" #include "a2dp_vendor_ldac_encoder.h" +#include "avdt_api.h" #include "btif/include/btif_av_co.h" +#include "hardware/bt_av.h" #include "internal_include/bt_trace.h" -#include "osi/include/osi.h" #include "stack/include/bt_hdr.h" using namespace bluetooth; diff --git a/system/stack/a2dp/a2dp_vendor_ldac_decoder.cc b/system/stack/a2dp/a2dp_vendor_ldac_decoder.cc index 4107e64e90..0571216767 100644 --- a/system/stack/a2dp/a2dp_vendor_ldac_decoder.cc +++ b/system/stack/a2dp/a2dp_vendor_ldac_decoder.cc @@ -25,7 +25,11 @@ #include <pthread.h> #include <string.h> +#include <cstdint> + #include "a2dp_vendor_ldac.h" +#include "a2dp_vendor_ldac_constants.h" +#include "avdt_api.h" #include "stack/include/bt_hdr.h" using namespace bluetooth; diff --git a/system/stack/a2dp/a2dp_vendor_ldac_encoder.cc b/system/stack/a2dp/a2dp_vendor_ldac_encoder.cc index d89de9a550..c2a04d64b4 100644 --- a/system/stack/a2dp/a2dp_vendor_ldac_encoder.cc +++ b/system/stack/a2dp/a2dp_vendor_ldac_encoder.cc @@ -19,11 +19,21 @@ #include "a2dp_vendor_ldac_encoder.h" +#include <stdio.h> + +#include <cstdint> +#include <string> + +#include "a2dp_codec_api.h" +#include "a2dp_vendor_ldac_constants.h" +#include "avdt_api.h" +#include "hardware/bt_av.h" +#include "ldacBT.h" + #ifdef __ANDROID__ #include <cutils/trace.h> #endif #include <bluetooth/log.h> -#include <dlfcn.h> #include <inttypes.h> #include <ldacBT_abr.h> #include <string.h> diff --git a/system/stack/a2dp/a2dp_vendor_opus.cc b/system/stack/a2dp/a2dp_vendor_opus.cc index fac881856f..d7a5685706 100644 --- a/system/stack/a2dp/a2dp_vendor_opus.cc +++ b/system/stack/a2dp/a2dp_vendor_opus.cc @@ -28,10 +28,21 @@ #include <bluetooth/log.h> #include <string.h> +#include <cstdint> +#include <mutex> +#include <sstream> +#include <string> + +#include "a2dp_api.h" +#include "a2dp_codec_api.h" +#include "a2dp_constants.h" +#include "a2dp_vendor_opus_constants.h" #include "a2dp_vendor_opus_decoder.h" #include "a2dp_vendor_opus_encoder.h" +#include "avdt_api.h" +#include "bt_hdr.h" +#include "hardware/bt_av.h" #include "internal_include/bt_trace.h" -#include "osi/include/osi.h" using namespace bluetooth; diff --git a/system/stack/a2dp/a2dp_vendor_opus_decoder.cc b/system/stack/a2dp/a2dp_vendor_opus_decoder.cc index bbbd3a2c3b..d0000b50d4 100644 --- a/system/stack/a2dp/a2dp_vendor_opus_decoder.cc +++ b/system/stack/a2dp/a2dp_vendor_opus_decoder.cc @@ -21,7 +21,14 @@ #include <bluetooth/log.h> #include <opus.h> -#include "a2dp_vendor_opus.h" +#include <cstddef> +#include <cstdint> +#include <cstring> + +#include "a2dp_codec_api.h" +#include "a2dp_vendor_opus_constants.h" +#include "bt_hdr.h" +#include "opus_defines.h" #include "osi/include/allocator.h" using namespace bluetooth; diff --git a/system/stack/a2dp/a2dp_vendor_opus_encoder.cc b/system/stack/a2dp/a2dp_vendor_opus_encoder.cc index e7476c1028..a1771f1b4c 100644 --- a/system/stack/a2dp/a2dp_vendor_opus_encoder.cc +++ b/system/stack/a2dp/a2dp_vendor_opus_encoder.cc @@ -19,15 +19,22 @@ #include "a2dp_vendor_opus_encoder.h" #include <bluetooth/log.h> -#include <dlfcn.h> #include <opus.h> +#include <stdio.h> #include <string.h> -#include "a2dp_vendor.h" +#include <cstdint> + +#include "a2dp_codec_api.h" #include "a2dp_vendor_opus.h" +#include "a2dp_vendor_opus_constants.h" +#include "avdt_api.h" #include "common/time_util.h" +#include "hardware/bt_av.h" +#include "internal_include/bt_target.h" +#include "opus_defines.h" +#include "opus_types.h" #include "osi/include/allocator.h" -#include "osi/include/osi.h" #include "stack/include/bt_hdr.h" using namespace bluetooth; diff --git a/system/stack/acl/acl.h b/system/stack/acl/acl.h index 1bcedb8085..f740409958 100644 --- a/system/stack/acl/acl.h +++ b/system/stack/acl/acl.h @@ -335,4 +335,4 @@ public: 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 +void btm_acl_encrypt_change(uint16_t handle, uint8_t status, uint8_t encr_enable); diff --git a/system/stack/acl/btm_acl.cc b/system/stack/acl/btm_acl.cc index fecf7b9547..16911e9cc5 100644 --- a/system/stack/acl/btm_acl.cc +++ b/system/stack/acl/btm_acl.cc @@ -567,9 +567,8 @@ tBTM_STATUS BTM_SwitchRoleToCentral(const RawAddress& remote_bd_addr) { return tBTM_STATUS::BTM_WRONG_MODE; } p_acl->set_switch_role_changing(); - } - /* some devices do not support switch while encryption is on */ - else { + } else { + /* some devices do not support switch while encryption is on */ if (p_acl->is_encrypted && !IsEprAvailable(*p_acl)) { /* bypass turning off encryption if change link key is already doing it */ p_acl->set_encryption_off(); @@ -630,9 +629,8 @@ void btm_acl_encrypt_change(uint16_t handle, uint8_t /* status */, uint8_t encr_ p->set_switch_role_switching(); } internal_.hci_start_role_switch_to_central(*p); - } - /* Finished enabling Encryption after role switch */ - else if (p->is_switch_role_encryption_on()) { + } else if (p->is_switch_role_encryption_on()) { + /* Finished enabling Encryption after role switch */ p->reset_switch_role(); p->set_encryption_idle(); NotifyAclRoleSwitchComplete(btm_cb.acl_cb_.switch_role_ref_data.remote_bd_addr, @@ -1976,16 +1974,14 @@ void btm_cont_rswitch_from_handle(uint16_t hci_handle) { change of link key or role switch */ if (p->is_switch_role_mode_change()) { /* Must turn off Encryption first if necessary */ - /* Some devices do not support switch or change of link key while encryption - * is on */ + /* Some devices do not support switch or change of link key while encryption is on */ if (p->is_encrypted && !IsEprAvailable(*p)) { p->set_encryption_off(); if (p->is_switch_role_mode_change()) { p->set_switch_role_encryption_off(); } - } else /* Encryption not used or EPR supported, continue with switch - and/or change of link key */ - { + } else { + /* Encryption not used or EPR supported, continue with switch and/or change of link key */ if (p->is_switch_role_mode_change()) { internal_.hci_start_role_switch_to_central(*p); } diff --git a/system/stack/avct/avct_api.cc b/system/stack/avct/avct_api.cc index 55c7cd02e7..2c3db70911 100644 --- a/system/stack/avct/avct_api.cc +++ b/system/stack/avct/avct_api.cc @@ -28,10 +28,15 @@ #include <com_android_bluetooth_flags.h> #include <string.h> +#include <cstdint> + #include "bta/include/bta_sec_api.h" #include "internal_include/bt_target.h" +#include "l2cap_types.h" +#include "l2cdefs.h" #include "main/shim/dumpsys.h" #include "osi/include/allocator.h" +#include "osi/include/fixed_queue.h" #include "stack/avct/avct_int.h" #include "stack/include/avct_api.h" #include "stack/include/bt_hdr.h" @@ -163,9 +168,8 @@ uint16_t AVCT_CreateConn(uint8_t* p_handle, tAVCT_CC* p_cc, const RawAddress& pe avct_ccb_dealloc(p_ccb, AVCT_NO_EVT, 0, NULL); result = AVCT_NO_RESOURCES; } - } - /* check if PID already in use */ - else if (avct_lcb_has_pid(p_lcb, p_cc->pid)) { + } else if (avct_lcb_has_pid(p_lcb, p_cc->pid)) { + /* check if PID already in use */ avct_ccb_dealloc(p_ccb, AVCT_NO_EVT, 0, NULL); result = AVCT_PID_IN_USE; } @@ -405,9 +409,8 @@ uint16_t AVCT_MsgReq(uint8_t handle, uint8_t label, uint8_t cr, BT_HDR* p_msg) { if (p_ccb == NULL) { result = AVCT_BAD_HANDLE; osi_free(p_msg); - } - /* verify channel is bound to link */ - else if (p_ccb->p_lcb == NULL) { + } else if (p_ccb->p_lcb == NULL) { + /* verify channel is bound to link */ result = AVCT_NOT_OPEN; osi_free(p_msg); } @@ -430,9 +433,8 @@ uint16_t AVCT_MsgReq(uint8_t handle, uint8_t label, uint8_t cr, BT_HDR* p_msg) { avct_lcb_evt.ul_msg = ul_msg; avct_bcb_event(p_ccb->p_bcb, AVCT_LCB_UL_MSG_EVT, &avct_lcb_evt); } - } - /* send msg event to lcb */ - else { + } else { + /* send msg event to lcb */ tAVCT_LCB_EVT avct_lcb_evt; avct_lcb_evt.ul_msg = ul_msg; avct_lcb_event(p_ccb->p_lcb, AVCT_LCB_UL_MSG_EVT, &avct_lcb_evt); diff --git a/system/stack/avct/avct_bcb_act.cc b/system/stack/avct/avct_bcb_act.cc index 37a5d20a97..68d10249e4 100644 --- a/system/stack/avct/avct_bcb_act.cc +++ b/system/stack/avct/avct_bcb_act.cc @@ -29,6 +29,8 @@ #include <com_android_bluetooth_flags.h> #include <string.h> +#include <cstdint> + #include "bta/include/bta_sec_api.h" #include "btif/include/btif_av.h" #include "internal_include/bt_target.h" diff --git a/system/stack/avct/avct_ccb.cc b/system/stack/avct/avct_ccb.cc index 6ffa34c3fb..d93b80ea28 100644 --- a/system/stack/avct/avct_ccb.cc +++ b/system/stack/avct/avct_ccb.cc @@ -26,6 +26,8 @@ #include <bluetooth/log.h> #include <string.h> +#include <cstdint> + #include "avct_api.h" #include "avct_int.h" #include "internal_include/bt_target.h" diff --git a/system/stack/avct/avct_l2c.cc b/system/stack/avct/avct_l2c.cc index e3001eeaa2..adde80d157 100644 --- a/system/stack/avct/avct_l2c.cc +++ b/system/stack/avct/avct_l2c.cc @@ -23,10 +23,14 @@ ******************************************************************************/ #include <bluetooth/log.h> +#include <cstddef> +#include <cstdint> + #include "avct_api.h" #include "avct_int.h" #include "btif/include/btif_av.h" #include "internal_include/bt_target.h" +#include "l2cap_types.h" #include "osi/include/allocator.h" #include "stack/include/bt_hdr.h" #include "stack/include/l2cap_interface.h" diff --git a/system/stack/avct/avct_l2c_br.cc b/system/stack/avct/avct_l2c_br.cc index 3f76e0b76f..172f0386b9 100644 --- a/system/stack/avct/avct_l2c_br.cc +++ b/system/stack/avct/avct_l2c_br.cc @@ -26,7 +26,11 @@ #include <bluetooth/log.h> +#include <cstddef> +#include <cstdint> + #include "internal_include/bt_target.h" +#include "l2cap_types.h" #include "osi/include/allocator.h" #include "stack/avct/avct_int.h" #include "stack/include/avct_api.h" diff --git a/system/stack/avct/avct_lcb.cc b/system/stack/avct/avct_lcb.cc index 43a2b9470b..ef2f392db4 100644 --- a/system/stack/avct/avct_lcb.cc +++ b/system/stack/avct/avct_lcb.cc @@ -26,12 +26,18 @@ #include <bluetooth/log.h> #include <string.h> +#include <cstdint> +#include <string> + #include "avct_api.h" #include "avct_int.h" +#include "device/include/device_iot_conf_defs.h" #include "device/include/device_iot_config.h" #include "include/macros.h" #include "internal_include/bt_target.h" +#include "l2cap_types.h" #include "osi/include/allocator.h" +#include "osi/include/fixed_queue.h" #include "types/raw_address.h" using namespace bluetooth; diff --git a/system/stack/avct/avct_lcb_act.cc b/system/stack/avct/avct_lcb_act.cc index 986bce7d34..9985a6fcbb 100644 --- a/system/stack/avct/avct_lcb_act.cc +++ b/system/stack/avct/avct_lcb_act.cc @@ -25,13 +25,18 @@ #include <com_android_bluetooth_flags.h> #include <string.h> +#include <cstdint> + #include "avct_api.h" #include "avct_int.h" #include "bta/include/bta_sec_api.h" #include "btif/include/btif_av.h" +#include "device/include/device_iot_conf_defs.h" #include "device/include/device_iot_config.h" #include "internal_include/bt_target.h" +#include "l2cap_types.h" #include "osi/include/allocator.h" +#include "osi/include/fixed_queue.h" #include "stack/avct/avct_defs.h" #include "stack/include/avct_api.h" #include "stack/include/bt_hdr.h" @@ -77,9 +82,8 @@ static BT_HDR* avct_lcb_msg_asmbl(tAVCT_LCB* p_lcb, BT_HDR* p_buf) { osi_free(p_buf); log::warn("Bad length during reassembly"); p_ret = NULL; - } - /* single packet */ - else if (pkt_type == AVCT_PKT_TYPE_SINGLE) { + } else if (pkt_type == AVCT_PKT_TYPE_SINGLE) { + /* single packet */ /* if reassembly in progress drop message and process new single */ if (p_lcb->p_rx_msg != NULL) { log::warn("Got single during reassembly"); @@ -88,9 +92,8 @@ static BT_HDR* avct_lcb_msg_asmbl(tAVCT_LCB* p_lcb, BT_HDR* p_buf) { osi_free_and_reset((void**)&p_lcb->p_rx_msg); p_ret = p_buf; - } - /* start packet */ - else if (pkt_type == AVCT_PKT_TYPE_START) { + } else if (pkt_type == AVCT_PKT_TYPE_START) { + /* start packet */ /* if reassembly in progress drop message and process new start */ if (p_lcb->p_rx_msg != NULL) { log::warn("Got start during reassembly"); @@ -127,9 +130,8 @@ static BT_HDR* avct_lcb_msg_asmbl(tAVCT_LCB* p_lcb, BT_HDR* p_buf) { p_lcb->p_rx_msg->len -= 1; p_ret = NULL; - } - /* continue or end */ - else { + } else { + /* continue or end */ /* if no reassembly in progress drop message */ if (p_lcb->p_rx_msg == NULL) { osi_free(p_buf); @@ -266,12 +268,10 @@ void avct_lcb_open_ind(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { } p_ccb->cc.p_ctrl_cback(avct_ccb_to_idx(p_ccb), AVCT_CONNECT_CFM_EVT, 0, &p_lcb->peer_addr); - } - /* if unbound acceptor and lcb doesn't already have a ccb for this PID - */ - /** M: to avoid avctp collision, make sure the collision can be checked - @{ */ - else if ((p_ccb->cc.role == AVCT_ROLE_ACCEPTOR) && avct_lcb_has_pid(p_lcb, p_ccb->cc.pid)) { + } else if ((p_ccb->cc.role == AVCT_ROLE_ACCEPTOR) && + avct_lcb_has_pid(p_lcb, p_ccb->cc.pid)) { + /* if unbound acceptor and lcb doesn't already have a ccb for this PID */ + /* to avoid avctp collision, make sure the collision can be checked */ /* bind ccb to lcb and send connect ind event */ if (is_originater) { log::error("int exist, unbind acp handle:{}", i); @@ -304,11 +304,9 @@ void avct_lcb_open_ind(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { } p_ccb->cc.p_ctrl_cback(avct_ccb_to_idx(p_ccb), AVCT_CONNECT_CFM_EVT, 0, &p_lcb->peer_addr); - } - /* if unbound acceptor and lcb doesn't already have a ccb for this PID - */ - else if ((p_ccb->p_lcb == NULL) && (p_ccb->cc.role == AVCT_ROLE_ACCEPTOR) && - (avct_lcb_has_pid(p_lcb, p_ccb->cc.pid) == NULL)) { + } else if ((p_ccb->p_lcb == NULL) && (p_ccb->cc.role == AVCT_ROLE_ACCEPTOR) && + (avct_lcb_has_pid(p_lcb, p_ccb->cc.pid) == NULL)) { + /* if unbound acceptor and lcb doesn't already have a ccb for this PID */ /* bind ccb to lcb and send connect ind event */ bind = true; p_ccb->p_lcb = p_lcb; @@ -615,10 +613,8 @@ void avct_lcb_send_msg(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) { if (p_lcb->cong) { fixed_queue_enqueue(p_lcb->tx_q, p_buf); - } - - /* send message to L2CAP */ - else { + } else { + /* send message to L2CAP */ if (stack::l2cap::get_interface().L2CA_DataWrite(p_lcb->ch_lcid, p_buf) == tL2CAP_DW_RESULT::CONGESTED) { p_lcb->cong = true; diff --git a/system/stack/avdt/avdt_ad.cc b/system/stack/avdt/avdt_ad.cc index f566688ef7..92535cb84b 100644 --- a/system/stack/avdt/avdt_ad.cc +++ b/system/stack/avdt/avdt_ad.cc @@ -28,9 +28,13 @@ #include <com_android_bluetooth_flags.h> #include <string.h> +#include <cstdint> + #include "avdt_api.h" #include "avdt_int.h" #include "internal_include/bt_target.h" +#include "l2cap_types.h" +#include "l2cdefs.h" #include "osi/include/allocator.h" #include "stack/include/bt_hdr.h" #include "stack/include/btm_sec_api_types.h" diff --git a/system/stack/avdt/avdt_api.cc b/system/stack/avdt/avdt_api.cc index 6304e78255..207c090cd4 100644 --- a/system/stack/avdt/avdt_api.cc +++ b/system/stack/avdt/avdt_api.cc @@ -29,13 +29,18 @@ #include <bluetooth/log.h> #include <com_android_bluetooth_flags.h> +#include <stdio.h> #include <string.h> +#include <cstdint> + +#include "avdt_defs.h" #include "avdt_int.h" #include "avdtc_api.h" #include "bta/include/bta_sec_api.h" #include "internal_include/bt_target.h" #include "os/logging/log_adapter.h" +#include "osi/include/alarm.h" #include "stack/include/a2dp_codec_api.h" #include "stack/include/bt_hdr.h" #include "stack/include/l2cap_interface.h" @@ -173,10 +178,8 @@ uint16_t AVDT_CreateStream(uint8_t peer_id, uint8_t* p_handle, result = AVDT_BAD_PARAMS; log::error("Invalid AVDT stream endpoint parameters peer_id={} scb_index={}", peer_id, avdtp_stream_config.scb_index); - } - - /* Allocate scb; if no scbs, return failure */ - else { + } else { + /* Allocate scb; if no scbs, return failure */ p_scb = avdt_scb_alloc(peer_id, avdtp_stream_config); if (p_scb == NULL) { log::error("Unable to create AVDT stream endpoint peer_id={} scb_index={}", peer_id, @@ -274,9 +277,8 @@ uint16_t AVDT_DiscoverReq(const RawAddress& bd_addr, uint8_t channel_index, /* make sure no discovery or get capabilities req already in progress */ if (p_ccb->proc_busy) { result = AVDT_BUSY; - } - /* send event to ccb */ - else { + } else { + /* send event to ccb */ evt.discover.p_sep_info = p_sep_info; evt.discover.num_seps = max_seps; evt.discover.p_cback = p_cback; @@ -308,9 +310,8 @@ static uint16_t avdt_get_cap_req(const RawAddress& bd_addr, uint8_t channel_inde if ((p_evt->single.seid < AVDT_SEID_MIN) || (p_evt->single.seid > AVDT_SEID_MAX)) { log::error("seid: {}", p_evt->single.seid); result = AVDT_BAD_PARAMS; - } - /* find channel control block for this bd addr; if none, allocate one */ - else { + } else { + /* find channel control block for this bd addr; if none, allocate one */ p_ccb = avdt_ccb_by_bd(bd_addr); if (p_ccb == NULL) { p_ccb = avdt_ccb_alloc_by_channel_index(bd_addr, channel_index); @@ -325,9 +326,8 @@ static uint16_t avdt_get_cap_req(const RawAddress& bd_addr, uint8_t channel_inde /* make sure no discovery or get capabilities req already in progress */ if (p_ccb->proc_busy) { result = AVDT_BUSY; - } - /* send event to ccb */ - else { + } else { + /* send event to ccb */ avdt_ccb_event(p_ccb, AVDT_CCB_API_GETCAP_REQ_EVT, (tAVDT_CCB_EVT*)p_evt); } } @@ -448,15 +448,13 @@ uint16_t AVDT_OpenReq(uint8_t handle, const RawAddress& bd_addr, uint8_t channel /* verify SEID */ if ((seid < AVDT_SEID_MIN) || (seid > AVDT_SEID_MAX)) { result = AVDT_BAD_PARAMS; - } - /* map handle to scb */ - else { + } else { + /* map handle to scb */ p_scb = avdt_scb_by_hdl(handle); if (p_scb == NULL) { result = AVDT_BAD_HANDLE; - } - /* find channel control block for this bd addr; if none, allocate one */ - else { + } else { + /* find channel control block for this bd addr; if none, allocate one */ p_ccb = avdt_ccb_by_bd(bd_addr); if (p_ccb == NULL) { p_ccb = avdt_ccb_alloc_by_channel_index(bd_addr, channel_index); @@ -509,15 +507,12 @@ uint16_t AVDT_ConfigRsp(uint8_t handle, uint8_t label, uint8_t error_code, uint8 p_scb = avdt_scb_by_hdl(handle); if (p_scb == NULL) { result = AVDT_BAD_HANDLE; - } - /* handle special case when this function is called but peer has not send - ** a configuration cmd; ignore and return error result - */ - else if (!p_scb->in_use) { + } else if (!p_scb->in_use) { + /* handle special case when this function is called but peer has not send + * a configuration cmd; ignore and return error result */ result = AVDT_BAD_HANDLE; - } - /* send event to scb */ - else { + } else { + /* send event to scb */ evt.msg.hdr.err_code = error_code; evt.msg.hdr.err_param = category; evt.msg.hdr.label = label; @@ -715,9 +710,8 @@ uint16_t AVDT_ReconfigReq(uint8_t handle, AvdtpSepConfig* p_cfg) { p_scb = avdt_scb_by_hdl(handle); if (p_scb == NULL) { result = AVDT_BAD_HANDLE; - } - /* send event to scb */ - else { + } else { + /* send event to scb */ /* force psc_mask to zero */ p_cfg->psc_mask = 0; evt.msg.reconfig_cmd.p_cfg = p_cfg; @@ -755,9 +749,8 @@ uint16_t AVDT_SecurityReq(uint8_t handle, uint8_t* p_data, uint16_t len) { p_scb = avdt_scb_by_hdl(handle); if (p_scb == NULL) { result = AVDT_BAD_HANDLE; - } - /* send event to scb */ - else { + } else { + /* send event to scb */ evt.msg.security_rsp.p_data = p_data; evt.msg.security_rsp.len = len; avdt_scb_event(p_scb, AVDT_SCB_API_SECURITY_REQ_EVT, &evt); @@ -795,9 +788,8 @@ uint16_t AVDT_SecurityRsp(uint8_t handle, uint8_t label, uint8_t error_code, uin p_scb = avdt_scb_by_hdl(handle); if (p_scb == NULL) { result = AVDT_BAD_HANDLE; - } - /* send event to scb */ - else { + } else { + /* send event to scb */ evt.msg.security_rsp.hdr.err_code = error_code; evt.msg.security_rsp.hdr.label = label; evt.msg.security_rsp.p_data = p_data; diff --git a/system/stack/avdt/avdt_ccb.cc b/system/stack/avdt/avdt_ccb.cc index eca5c1f6ad..5e94233a11 100644 --- a/system/stack/avdt/avdt_ccb.cc +++ b/system/stack/avdt/avdt_ccb.cc @@ -28,9 +28,12 @@ #include <bluetooth/log.h> #include <string.h> +#include <cstdint> + #include "avdt_int.h" #include "internal_include/bt_target.h" -#include "osi/include/osi.h" +#include "osi/include/alarm.h" +#include "osi/include/fixed_queue.h" #include "types/raw_address.h" using namespace bluetooth; diff --git a/system/stack/avdt/avdt_ccb_act.cc b/system/stack/avdt/avdt_ccb_act.cc index df905c1e79..9f8557f4b5 100644 --- a/system/stack/avdt/avdt_ccb_act.cc +++ b/system/stack/avdt/avdt_ccb_act.cc @@ -28,12 +28,16 @@ #include <bluetooth/log.h> #include <string.h> +#include <cstdint> + #include "avdt_api.h" +#include "avdt_defs.h" #include "avdt_int.h" #include "avdtc_api.h" #include "internal_include/bt_target.h" +#include "osi/include/alarm.h" #include "osi/include/allocator.h" -#include "osi/include/osi.h" +#include "osi/include/fixed_queue.h" #include "stack/include/bt_hdr.h" #include "types/raw_address.h" @@ -659,7 +663,6 @@ void avdt_ccb_clear_cmds(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* /* p_data */) { /* set up next message */ p_ccb->p_curr_cmd = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->cmd_q); - } while (p_ccb->p_curr_cmd != NULL); /* send a CC_CLOSE_EVT any active scbs associated with this ccb */ @@ -830,9 +833,8 @@ void avdt_ccb_snd_msg(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* /* p_data */) { /* are we sending a fragmented message? continue sending fragment */ if (p_ccb->p_curr_msg != NULL) { avdt_msg_send(p_ccb, NULL); - } - /* do we have responses to send? send them */ - else if (!fixed_queue_is_empty(p_ccb->rsp_q)) { + } else if (!fixed_queue_is_empty(p_ccb->rsp_q)) { + /* do we have responses to send? send them */ while ((p_msg = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->rsp_q)) != NULL) { if (avdt_msg_send(p_ccb, p_msg)) { /* break out if congested */ diff --git a/system/stack/avdt/avdt_l2c.cc b/system/stack/avdt/avdt_l2c.cc index 6eab341865..48c6ad34db 100644 --- a/system/stack/avdt/avdt_l2c.cc +++ b/system/stack/avdt/avdt_l2c.cc @@ -26,9 +26,15 @@ #include <bluetooth/log.h> +#include <cstddef> +#include <cstdint> + #include "avdt_int.h" #include "bta/include/bta_av_api.h" #include "device/include/interop.h" +#include "hcidefs.h" +#include "l2cap_types.h" +#include "l2cdefs.h" #include "osi/include/allocator.h" #include "stack/include/acl_api.h" #include "stack/include/bt_hdr.h" diff --git a/system/stack/avdt/avdt_msg.cc b/system/stack/avdt/avdt_msg.cc index 4241cd741a..09d9c6dd81 100644 --- a/system/stack/avdt/avdt_msg.cc +++ b/system/stack/avdt/avdt_msg.cc @@ -31,12 +31,17 @@ #include <bluetooth/log.h> #include <string.h> +#include <cstdint> + #include "avdt_api.h" +#include "avdt_defs.h" #include "avdt_int.h" #include "avdtc_api.h" #include "internal_include/bt_target.h" +#include "l2cap_types.h" +#include "osi/include/alarm.h" #include "osi/include/allocator.h" -#include "osi/include/osi.h" +#include "osi/include/fixed_queue.h" #include "stack/include/bt_hdr.h" #include "stack/include/bt_types.h" @@ -1064,10 +1069,9 @@ bool avdt_msg_send(AvdtpCcb* p_ccb, BT_HDR* p_msg) { pkt_type = AVDT_PKT_TYPE_SINGLE; hdr_len = AVDT_LEN_TYPE_SINGLE; p_buf = p_ccb->p_curr_msg; - } - /* if message isn't being fragmented and it doesn't fit in mtu */ - else if ((p_ccb->p_curr_msg->offset == AVDT_MSG_OFFSET) && - (p_ccb->p_curr_msg->len > p_tbl->peer_mtu - AVDT_LEN_TYPE_SINGLE)) { + } else if ((p_ccb->p_curr_msg->offset == AVDT_MSG_OFFSET) && + /* if message isn't being fragmented and it doesn't fit in mtu */ + (p_ccb->p_curr_msg->len > p_tbl->peer_mtu - AVDT_LEN_TYPE_SINGLE)) { pkt_type = AVDT_PKT_TYPE_START; hdr_len = AVDT_LEN_TYPE_START; nosp = (p_ccb->p_curr_msg->len + AVDT_LEN_TYPE_START - p_tbl->peer_mtu) / @@ -1082,10 +1086,9 @@ bool avdt_msg_send(AvdtpCcb* p_ccb, BT_HDR* p_msg) { p_buf->len = p_tbl->peer_mtu - hdr_len; memcpy((uint8_t*)(p_buf + 1) + p_buf->offset, (uint8_t*)(p_ccb->p_curr_msg + 1) + p_ccb->p_curr_msg->offset, p_buf->len); - } - /* if message is being fragmented and remaining bytes don't fit in mtu */ - else if ((p_ccb->p_curr_msg->offset > AVDT_MSG_OFFSET) && - (p_ccb->p_curr_msg->len > (p_tbl->peer_mtu - AVDT_LEN_TYPE_CONT))) { + } else if ((p_ccb->p_curr_msg->offset > AVDT_MSG_OFFSET) && + /* if message is being fragmented and remaining bytes don't fit in mtu */ + (p_ccb->p_curr_msg->len > (p_tbl->peer_mtu - AVDT_LEN_TYPE_CONT))) { pkt_type = AVDT_PKT_TYPE_CONT; hdr_len = AVDT_LEN_TYPE_CONT; @@ -1097,9 +1100,8 @@ bool avdt_msg_send(AvdtpCcb* p_ccb, BT_HDR* p_msg) { p_buf->len = p_tbl->peer_mtu - hdr_len; memcpy((uint8_t*)(p_buf + 1) + p_buf->offset, (uint8_t*)(p_ccb->p_curr_msg + 1) + p_ccb->p_curr_msg->offset, p_buf->len); - } - /* if message is being fragmented and remaining bytes do fit in mtu */ - else { + } else { + /* if message is being fragmented and remaining bytes do fit in mtu */ pkt_type = AVDT_PKT_TYPE_END; hdr_len = AVDT_LEN_TYPE_END; p_buf = p_ccb->p_curr_msg; @@ -1193,9 +1195,8 @@ static BT_HDR* avdt_msg_asmbl(AvdtpCcb* p_ccb, BT_HDR* p_buf) { osi_free(p_buf); log::warn("Bad length during reassembly"); p_ret = NULL; - } - /* single packet */ - else if (pkt_type == AVDT_PKT_TYPE_SINGLE) { + } else if (pkt_type == AVDT_PKT_TYPE_SINGLE) { + /* single packet */ /* if reassembly in progress drop message and process new single */ if (p_ccb->p_rx_msg != NULL) { log::warn("Got single during reassembly"); @@ -1204,9 +1205,8 @@ static BT_HDR* avdt_msg_asmbl(AvdtpCcb* p_ccb, BT_HDR* p_buf) { osi_free_and_reset((void**)&p_ccb->p_rx_msg); p_ret = p_buf; - } - /* start packet */ - else if (pkt_type == AVDT_PKT_TYPE_START) { + } else if (pkt_type == AVDT_PKT_TYPE_START) { + /* start packet */ /* if reassembly in progress drop message and process new single */ if (p_ccb->p_rx_msg != NULL) { log::warn("Got start during reassembly"); @@ -1243,9 +1243,8 @@ static BT_HDR* avdt_msg_asmbl(AvdtpCcb* p_ccb, BT_HDR* p_buf) { p_ccb->p_rx_msg->len -= 1; p_ret = NULL; - } - /* continue or end */ - else { + } else { + /* continue or end */ /* if no reassembly in progress drop message */ if (p_ccb->p_rx_msg == NULL) { osi_free(p_buf); @@ -1329,9 +1328,8 @@ void avdt_msg_send_cmd(AvdtpCcb* p_ccb, void* p_scb, uint8_t sig_id, tAVDT_MSG* /* for start and suspend, p_scb points to array of handles */ if ((sig_id == AVDT_SIG_START) || (sig_id == AVDT_SIG_SUSPEND)) { memcpy(p, (uint8_t*)p_scb, p_buf->len); - } - /* for all others, p_scb points to scb as usual */ - else { + } else { + /* for all others, p_scb points to scb as usual */ *p = avdt_scb_to_hdl((AvdtpScb*)p_scb); } } @@ -1523,9 +1521,8 @@ void avdt_msg_ind(AvdtpCcb* p_ccb, BT_HDR* p_buf) { if (msg_type == AVDT_MSG_TYPE_GRJ) { log::warn("Dropping msg msg_type={}", msg_type); ok = false; - } - /* check for general reject */ - else if ((msg_type == AVDT_MSG_TYPE_REJ) && (p_buf->len == AVDT_LEN_GEN_REJ)) { + } else if ((msg_type == AVDT_MSG_TYPE_REJ) && (p_buf->len == AVDT_LEN_GEN_REJ)) { + /* check for general reject */ gen_rej = true; if (p_ccb->p_curr_cmd != NULL) { msg.hdr.sig_id = sig = (uint8_t)p_ccb->p_curr_cmd->event; @@ -1633,9 +1630,8 @@ void avdt_msg_ind(AvdtpCcb* p_ccb, BT_HDR* p_buf) { tAVDT_CCB_EVT avdt_ccb_evt; avdt_ccb_evt.msg = msg; avdt_ccb_event(p_ccb, (uint8_t)(evt & ~AVDT_CCB_MKR), &avdt_ccb_evt); - } - /* if it's a scb event */ - else { + } else { + /* if it's a scb event */ /* Scb events always have a single seid. For cmd, get seid from ** message. For rej and rsp, get seid from p_curr_cmd. */ diff --git a/system/stack/avdt/avdt_scb.cc b/system/stack/avdt/avdt_scb.cc index 9adcb69988..6c1a94a0bd 100644 --- a/system/stack/avdt/avdt_scb.cc +++ b/system/stack/avdt/avdt_scb.cc @@ -28,11 +28,13 @@ #include <bluetooth/log.h> #include <string.h> +#include <cstdint> + #include "avdt_api.h" #include "avdt_int.h" #include "avdtc_api.h" #include "internal_include/bt_target.h" -#include "osi/include/osi.h" +#include "osi/include/alarm.h" using namespace bluetooth; diff --git a/system/stack/avdt/avdt_scb_act.cc b/system/stack/avdt/avdt_scb_act.cc index d16f963ab1..620cfa4f57 100644 --- a/system/stack/avdt/avdt_scb_act.cc +++ b/system/stack/avdt/avdt_scb_act.cc @@ -29,10 +29,16 @@ #include <com_android_bluetooth_flags.h> #include <string.h> +#include <cstdint> + #include "a2dp_codec_api.h" +#include "a2dp_constants.h" #include "avdt_api.h" +#include "avdt_defs.h" #include "avdt_int.h" #include "internal_include/bt_target.h" +#include "l2cap_types.h" +#include "osi/include/alarm.h" #include "osi/include/allocator.h" #include "stack/include/bt_hdr.h" #include "stack/include/bt_types.h" @@ -276,9 +282,8 @@ void avdt_scb_hdl_pkt_no_frag(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { if (pad_len >= (len - offset)) { log::warn("Got bad media packet"); osi_free_and_reset((void**)&p_data->p_pkt); - } - /* adjust offset and length and send it up */ - else { + } else { + /* adjust offset and length and send it up */ p_data->p_pkt->len -= (offset + pad_len); p_data->p_pkt->offset += offset; diff --git a/system/stack/avrc/avrc_api.cc b/system/stack/avrc/avrc_api.cc index ea82921b43..273017d07e 100644 --- a/system/stack/avrc/avrc_api.cc +++ b/system/stack/avrc/avrc_api.cc @@ -27,10 +27,16 @@ #include <bluetooth/log.h> #include <string.h> +#include <cstdint> + +#include "avct_api.h" +#include "avrc_defs.h" #include "avrc_int.h" +#include "avrcp.sysprop.h" #include "btif/include/btif_av.h" #include "btif/include/btif_config.h" #include "internal_include/bt_target.h" +#include "osi/include/alarm.h" #include "osi/include/allocator.h" #include "osi/include/fixed_queue.h" #include "osi/include/properties.h" @@ -386,9 +392,8 @@ static BT_HDR* avrc_proc_vendor_command(uint8_t handle, uint8_t label, BT_HDR* p log::error("commands must be in single packet pdu:0x{:x}", *p_data); /* use the current GKI buffer to send the reject */ status = AVRC_STS_BAD_CMD; - } - /* check if there are fragments waiting to be sent */ - else if (avrc_cb.fcb[handle].frag_enabled) { + } else if (avrc_cb.fcb[handle].frag_enabled) { + /* check if there are fragments waiting to be sent */ p_fcb = &avrc_cb.fcb[handle]; if (p_msg->company_id == AVRC_CO_METADATA) { switch (*p_data) { diff --git a/system/stack/avrc/avrc_bld_ct.cc b/system/stack/avrc/avrc_bld_ct.cc index a68c9dca9d..7ad5f17c23 100644 --- a/system/stack/avrc/avrc_bld_ct.cc +++ b/system/stack/avrc/avrc_bld_ct.cc @@ -21,6 +21,9 @@ #include <bluetooth/log.h> #include <string.h> +#include <cstdint> + +#include "avct_api.h" #include "avrc_api.h" #include "avrc_defs.h" #include "avrc_int.h" diff --git a/system/stack/avrc/avrc_bld_tg.cc b/system/stack/avrc/avrc_bld_tg.cc index a057a03b53..b90a833a0b 100644 --- a/system/stack/avrc/avrc_bld_tg.cc +++ b/system/stack/avrc/avrc_bld_tg.cc @@ -15,17 +15,20 @@ * limitations under the License. * ******************************************************************************/ + #define LOG_TAG "avrcp" #include <bluetooth/log.h> #include <string.h> +#include <cstdint> + +#include "avct_api.h" #include "avrc_api.h" #include "avrc_defs.h" #include "avrc_int.h" #include "internal_include/bt_target.h" #include "osi/include/allocator.h" -#include "osi/include/osi.h" #include "stack/avct/avct_defs.h" #include "stack/include/bt_hdr.h" #include "stack/include/bt_types.h" diff --git a/system/stack/avrc/avrc_opt.cc b/system/stack/avrc/avrc_opt.cc index 4488123f37..a52778ada6 100644 --- a/system/stack/avrc/avrc_opt.cc +++ b/system/stack/avrc/avrc_opt.cc @@ -21,10 +21,13 @@ * Interface to AVRCP optional commands * ******************************************************************************/ -#include <bluetooth/log.h> #include <string.h> +#include <cstdint> + +#include "avct_api.h" #include "avrc_api.h" +#include "avrc_defs.h" #include "avrc_int.h" #include "internal_include/bt_target.h" #include "osi/include/allocator.h" diff --git a/system/stack/avrc/avrc_pars_ct.cc b/system/stack/avrc/avrc_pars_ct.cc index b72fa63b43..a1257172f2 100644 --- a/system/stack/avrc/avrc_pars_ct.cc +++ b/system/stack/avrc/avrc_pars_ct.cc @@ -18,11 +18,12 @@ #include <bluetooth/log.h> #include <string.h> +#include <cstdint> + #include "avrc_api.h" #include "avrc_defs.h" #include "avrc_int.h" #include "osi/include/allocator.h" -#include "osi/include/osi.h" #include "stack/include/bt_types.h" using namespace bluetooth; diff --git a/system/stack/avrc/avrc_pars_tg.cc b/system/stack/avrc/avrc_pars_tg.cc index dd4f9bdcfe..b0adecd9a5 100644 --- a/system/stack/avrc/avrc_pars_tg.cc +++ b/system/stack/avrc/avrc_pars_tg.cc @@ -18,6 +18,8 @@ #include <bluetooth/log.h> #include <string.h> +#include <cstdint> + #include "avrc_api.h" #include "avrc_defs.h" #include "avrc_int.h" diff --git a/system/stack/avrc/avrc_sdp.cc b/system/stack/avrc/avrc_sdp.cc index 61ba721b5f..688e411a3d 100644 --- a/system/stack/avrc/avrc_sdp.cc +++ b/system/stack/avrc/avrc_sdp.cc @@ -21,18 +21,25 @@ * AVRCP SDP related functions * ******************************************************************************/ + #define LOG_TAG "avrcp" #include <bluetooth/log.h> #include <string.h> +#include <cstdint> + +#include "avct_api.h" #include "avrc_api.h" +#include "avrc_defs.h" #include "avrc_int.h" +#include "sdp_status.h" #include "stack/include/bt_psm_types.h" #include "stack/include/bt_types.h" #include "stack/include/bt_uuid16.h" #include "stack/include/sdp_api.h" #include "stack/include/sdpdefs.h" +#include "stack/sdp/sdp_discovery_db.h" #include "types/bluetooth/uuid.h" #include "types/raw_address.h" diff --git a/system/stack/avrc/avrc_utils.cc b/system/stack/avrc/avrc_utils.cc index 6e07b12d73..b25bfe6f80 100644 --- a/system/stack/avrc/avrc_utils.cc +++ b/system/stack/avrc/avrc_utils.cc @@ -20,7 +20,10 @@ #include <bluetooth/log.h> +#include <cstdint> + #include "avrc_api.h" +#include "avrc_defs.h" #include "avrc_int.h" #include "stack/include/bt_types.h" diff --git a/system/stack/bnep/bnep_api.cc b/system/stack/bnep/bnep_api.cc index 51e4f51641..85fb0bf04d 100644 --- a/system/stack/bnep/bnep_api.cc +++ b/system/stack/bnep/bnep_api.cc @@ -27,14 +27,19 @@ #include <bluetooth/log.h> #include <string.h> +#include <cstdint> + #include "bnep_int.h" #include "bta/include/bta_sec_api.h" #include "internal_include/bt_target.h" +#include "osi/include/alarm.h" #include "osi/include/allocator.h" +#include "osi/include/fixed_queue.h" #include "stack/include/bt_hdr.h" #include "stack/include/bt_psm_types.h" #include "stack/include/l2cap_interface.h" #include "types/bluetooth/uuid.h" +#include "types/bt_transport.h" #include "types/raw_address.h" using namespace bluetooth; @@ -389,7 +394,6 @@ tBNEP_RESULT BNEP_WriteBuf(uint16_t handle, const RawAddress& dest_addr, BT_HDR* osi_free(p_buf); return BNEP_IGNORE_CMD; } - } while (ext & 0x80); if (protocol != BNEP_802_1_P_PROTOCOL) { @@ -494,7 +498,6 @@ tBNEP_RESULT BNEP_Write(uint16_t handle, const RawAddress& dest_addr, uint8_t* p if (new_len > org_len) { return BNEP_IGNORE_CMD; } - } while (ext & 0x80); if (protocol != BNEP_802_1_P_PROTOCOL) { diff --git a/system/stack/bnep/bnep_int.h b/system/stack/bnep/bnep_int.h index fde1a97d7b..0b740dae7d 100644 --- a/system/stack/bnep/bnep_int.h +++ b/system/stack/bnep/bnep_int.h @@ -135,7 +135,6 @@ typedef struct { bluetooth::Uuid prv_dst_uuid; bluetooth::Uuid src_uuid; bluetooth::Uuid dst_uuid; - } tBNEP_CONN; /* The main BNEP control block @@ -155,7 +154,6 @@ typedef struct { tL2CAP_APPL_INFO reg_info; bool profile_registered; /* true when we got our BD addr */ - } tBNEP_CB; /* Global BNEP data diff --git a/system/stack/bnep/bnep_main.cc b/system/stack/bnep/bnep_main.cc index e0e3c4540c..add8bad93d 100644 --- a/system/stack/bnep/bnep_main.cc +++ b/system/stack/bnep/bnep_main.cc @@ -22,23 +22,28 @@ * ******************************************************************************/ -#define LOG_TAG "bluetooth" - #include <bluetooth/log.h> #include <string.h> +#include <cstdint> + #include "bnep_api.h" #include "bnep_int.h" #include "bta/include/bta_sec_api.h" #include "hci/controller_interface.h" #include "internal_include/bt_target.h" +#include "l2cap_types.h" +#include "l2cdefs.h" #include "main/shim/entry.h" #include "main/shim/helpers.h" +#include "osi/include/alarm.h" #include "osi/include/allocator.h" +#include "osi/include/fixed_queue.h" #include "stack/include/bt_hdr.h" #include "stack/include/bt_psm_types.h" #include "stack/include/bt_types.h" #include "stack/include/l2cap_interface.h" +#include "types/bt_transport.h" #include "types/raw_address.h" using namespace bluetooth; diff --git a/system/stack/bnep/bnep_utils.cc b/system/stack/bnep/bnep_utils.cc index 252facf668..921e16992c 100644 --- a/system/stack/bnep/bnep_utils.cc +++ b/system/stack/bnep/bnep_utils.cc @@ -25,16 +25,24 @@ #include <bluetooth/log.h> #include <string.h> +#include <algorithm> +#include <cstdint> + +#include "bnep_api.h" #include "bnep_int.h" #include "hci/controller_interface.h" #include "internal_include/bt_target.h" +#include "l2cap_types.h" #include "main/shim/entry.h" #include "main/shim/helpers.h" +#include "osi/include/alarm.h" #include "osi/include/allocator.h" +#include "osi/include/fixed_queue.h" #include "stack/include/bt_hdr.h" #include "stack/include/bt_types.h" #include "stack/include/l2cap_interface.h" #include "types/bluetooth/uuid.h" +#include "types/bt_transport.h" #include "types/raw_address.h" // TODO(b/369381361) Enfore -Wmissing-prototypes @@ -1203,7 +1211,6 @@ tBNEP_RESULT bnep_is_packet_allowed(tBNEP_CONN* p_bcb, const RawAddress& dest_ad p_data += len; new_len += (len + 2); - } while (ext & 0x80); } if ((new_len + 4) > org_len) { diff --git a/system/stack/btm/btm_ble_adv_filter.cc b/system/stack/btm/btm_ble_adv_filter.cc index 3e6520ebc2..73050b5047 100644 --- a/system/stack/btm/btm_ble_adv_filter.cc +++ b/system/stack/btm/btm_ble_adv_filter.cc @@ -285,10 +285,8 @@ static uint8_t btm_ble_cs_update_pf_counter(tBTM_BLE_SCAN_COND_OP action, uint8_ (BTM_BLE_PF_ADDR_FILTER == cond_type && (BTM_BLE_SCAN_COND_DELETE == action || BTM_BLE_SCAN_COND_CLEAR == action))) { btm_ble_dealloc_addr_filter_counter(p_bd_addr, cond_type); - } - /* if not feature selection, update new addition/reduction of the filter - counter */ - else if (cond_type != BTM_BLE_PF_TYPE_ALL) { + } else if (cond_type != BTM_BLE_PF_TYPE_ALL) { + /* if not feature selection, update new addition/reduction of the filter counter */ p_counter = p_addr_filter->pf_counter; if (num_available > 0) { p_counter[cond_type] += 1; diff --git a/system/stack/btm/btm_ble_gap.cc b/system/stack/btm/btm_ble_gap.cc index 9b86ae9eca..91ca0b6fe6 100644 --- a/system/stack/btm/btm_ble_gap.cc +++ b/system/stack/btm/btm_ble_gap.cc @@ -359,7 +359,6 @@ const uint8_t btm_le_state_combo_tbl[BTM_BLE_STATE_MAX][BTM_BLE_STATE_MAX] = { HCI_LE_STATES_PASS_SCAN_INIT_BIT, /* passive scan */ HCI_LE_STATES_ACTIVE_SCAN_INIT_BIT, /* active scan */ HCI_LE_STATES_SCAN_ADV_INIT_BIT /* scanable adv */ - }, { /* central */ @@ -373,7 +372,6 @@ const uint8_t btm_le_state_combo_tbl[BTM_BLE_STATE_MAX][BTM_BLE_STATE_MAX] = { HCI_LE_STATES_PASS_SCAN_CENTRAL_BIT, /* passive scan */ HCI_LE_STATES_ACTIVE_SCAN_CENTRAL_BIT, /* active scan */ HCI_LE_STATES_SCAN_ADV_CENTRAL_BIT /* scanable adv */ - }, { /* peripheral */ @@ -387,7 +385,6 @@ const uint8_t btm_le_state_combo_tbl[BTM_BLE_STATE_MAX][BTM_BLE_STATE_MAX] = { HCI_LE_STATES_PASS_SCAN_PERIPHERAL_BIT, /* passive scan */ HCI_LE_STATES_ACTIVE_SCAN_PERIPHERAL_BIT, /* active scan */ HCI_LE_STATES_SCAN_ADV_PERIPHERAL_BIT /* scanable adv */ - }, { /* lo duty cycle adv */ @@ -1176,11 +1173,9 @@ static uint8_t btm_set_conn_mode_adv_init_addr(RawAddress& p_peer_addr_ptr, /* resolving list is empty, not enabled */ *p_own_addr_type = BLE_ADDR_RANDOM; } - } - /* privacy 1.1, or privacy 1.2, general discoverable/connectable mode, disable - privacy in */ - /* controller fall back to host based privacy */ - else if (btm_cb.ble_ctr_cb.privacy_mode != BTM_PRIVACY_NONE) { + } else if (btm_cb.ble_ctr_cb.privacy_mode != BTM_PRIVACY_NONE) { + /* privacy 1.1, or privacy 1.2, general discoverable/connectable mode, disable privacy in */ + /* controller fall back to host based privacy */ *p_own_addr_type = BLE_ADDR_RANDOM; } diff --git a/system/stack/btm/btm_ble_sec.cc b/system/stack/btm/btm_ble_sec.cc index 9927751bb1..a48e283511 100644 --- a/system/stack/btm/btm_ble_sec.cc +++ b/system/stack/btm/btm_ble_sec.cc @@ -1325,9 +1325,8 @@ void btm_ble_link_encrypted(const RawAddress& bd_addr, uint8_t encr_enable) { if (p_dev_rec->sec_rec.p_callback && enc_cback) { if (encr_enable) { btm_sec_dev_rec_cback_event(p_dev_rec, tBTM_STATUS::BTM_SUCCESS, true); - } - /* LTK missing on peripheral */ - else if (p_dev_rec->role_central && (p_dev_rec->sec_rec.sec_status == HCI_ERR_KEY_MISSING)) { + } else if (p_dev_rec->role_central && (p_dev_rec->sec_rec.sec_status == HCI_ERR_KEY_MISSING)) { + /* LTK missing on peripheral */ btm_sec_dev_rec_cback_event(p_dev_rec, tBTM_STATUS::BTM_ERR_KEY_MISSING, true); } else if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_LINK_KEY_KNOWN)) { btm_sec_dev_rec_cback_event(p_dev_rec, tBTM_STATUS::BTM_FAILED_ON_SECURITY, true); diff --git a/system/stack/btm/btm_sco.h b/system/stack/btm/btm_sco.h index 4b51ce7eb4..eea4ebe94a 100644 --- a/system/stack/btm/btm_sco.h +++ b/system/stack/btm/btm_sco.h @@ -25,9 +25,9 @@ #include "device/include/esco_parameters.h" #include "internal_include/bt_target.h" #include "macros.h" -#include "raw_address.h" #include "stack/btm/sco_pkt_status.h" #include "stack/include/btm_api_types.h" +#include "types/raw_address.h" #define BTM_MSBC_CODE_SIZE 240 #define BTM_LC3_CODE_SIZE 480 @@ -255,7 +255,6 @@ public: bool is_orig; /* true if the originator */ bool rem_bd_known; /* true if remote BD addr known */ - } tSCO_CONN; /* SCO Management control block */ diff --git a/system/stack/btm/btm_sco_hfp_hal.h b/system/stack/btm/btm_sco_hfp_hal.h index f2f14569a1..ec64c02cab 100644 --- a/system/stack/btm/btm_sco_hfp_hal.h +++ b/system/stack/btm/btm_sco_hfp_hal.h @@ -23,7 +23,7 @@ #include "btm_api_types.h" #include "device/include/esco_parameters.h" #include "internal_include/bt_target.h" -#include "raw_address.h" +#include "types/raw_address.h" // Used by the Bluetooth stack to get WBS supported and codec, or notify SCO // connection change to lower layer (kernel) when SCO-over-HCI is used. So far diff --git a/system/stack/btm/btm_sec.cc b/system/stack/btm/btm_sec.cc index dc7ba92ce5..d19b9ae343 100644 --- a/system/stack/btm/btm_sec.cc +++ b/system/stack/btm/btm_sec.cc @@ -622,9 +622,8 @@ void BTM_PINCodeReply(const RawAddress& bd_addr, tBTM_STATUS res, uint8_t pin_le * connection */ /* when existing ACL link is down completely */ btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ); - } - /* if we already accepted incoming connection from pairing device */ - else if (p_dev_rec->sm4 & BTM_SM4_CONN_PEND) { + } else if (p_dev_rec->sm4 & BTM_SM4_CONN_PEND) { + /* if we already accepted incoming connection from pairing device */ log::warn( "BTM_PINCodeReply(): link is connecting so wait pin code request " "from peer"); @@ -2327,9 +2326,8 @@ void btm_sec_rmt_name_request_complete(const RawAddress* p_bd_addr, const uint8_ /* before originating */ if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) { log::warn("waiting HCI_Connection_Complete after rejecting connection"); - } - /* Both we and the peer are 2.1 - continue to create connection */ - else { + } else { + /* Both we and the peer are 2.1 - continue to create connection */ tBTM_STATUS req_status = btm_sec_dd_create_conn(p_dev_rec); bluetooth::metrics::LogAclAfterRemoteNameRequest(bd_addr, req_status); if (req_status == tBTM_STATUS::BTM_SUCCESS) { @@ -2450,7 +2448,7 @@ void btm_io_capabilities_req(RawAddress p) { auto p_dev_rec = btm_find_dev(p); if (p_dev_rec != NULL) { btm_sec_disconnect(p_dev_rec->hci_handle, HCI_ERR_AUTH_FAILURE, - "btm_io_capabilities_req Security failure"); + "btm_io_capabilities_req for bonded device"); } return; } @@ -2623,10 +2621,19 @@ void btm_io_capabilities_req(RawAddress p) { * ******************************************************************************/ void btm_io_capabilities_rsp(const tBTM_SP_IO_RSP evt_data) { - tBTM_SEC_DEV_REC* p_dev_rec; - /* Allocate a new device record or reuse the oldest one */ - p_dev_rec = btm_find_or_alloc_dev(evt_data.bd_addr); + tBTM_SEC_DEV_REC* p_dev_rec = btm_find_or_alloc_dev(evt_data.bd_addr); + + /* If device is bonded, and encrypted it's upgrading security and it's ok. + * If it's bonded and not encrypted, it's remote missing keys scenario */ + if (btm_sec_is_a_bonded_dev(evt_data.bd_addr) && !p_dev_rec->sec_rec.is_device_encrypted() && + com::android::bluetooth::flags::key_missing_classic_device()) { + log::warn("Incoming bond request, but {} is already bonded (notifying user)", evt_data.bd_addr); + bta_dm_remote_key_missing(evt_data.bd_addr); + btm_sec_disconnect(p_dev_rec->hci_handle, HCI_ERR_AUTH_FAILURE, + "btm_io_capabilities_rsp for bonded device"); + return; + } /* If no security is in progress, this indicates incoming security */ if (btm_sec_cb.pairing_state == BTM_PAIR_STATE_IDLE) { @@ -3017,6 +3024,16 @@ void btm_sec_auth_complete(uint16_t handle, tHCI_STATUS status) { tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), handle, status, p_dev_rec->sec_rec.classic_link, p_dev_rec->bd_addr, reinterpret_cast<char const*>(p_dev_rec->sec_bd_name)); + + if (status == HCI_ERR_KEY_MISSING && + com::android::bluetooth::flags::key_missing_classic_device()) { + log::warn("auth_complete KEY_MISSING {} is already bonded (notifying user)", + p_dev_rec->bd_addr); + bta_dm_remote_key_missing(p_dev_rec->bd_addr); + btm_sec_disconnect(handle, HCI_ERR_AUTH_FAILURE, "auth_cmpl KEY_MISSING for bonded device"); + return; + } + } else { log::verbose("Security Manager: in state: {}, handle: {}, status: {}", tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), handle, status); @@ -3638,20 +3655,19 @@ void btm_sec_connected(const RawAddress& bda, uint16_t handle, tHCI_STATUS statu /* We need to notify host that the key is not known any more */ NotifyBondingChange(*p_dev_rec, status); - } - /* - Do not send authentication failure, if following conditions hold good - 1. BTM Sec Pairing state is idle - 2. Link key for the remote device is present. - 3. Remote is SSP capable. - */ - else if ((p_dev_rec->sec_rec.link_key_type <= BTM_LKEY_TYPE_REMOTE_UNIT) && - ((status == HCI_ERR_AUTH_FAILURE) || (status == HCI_ERR_KEY_MISSING) || - (status == HCI_ERR_HOST_REJECT_SECURITY) || (status == HCI_ERR_PAIRING_NOT_ALLOWED) || - (status == HCI_ERR_UNIT_KEY_USED) || - (status == HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED) || - (status == HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE) || - (status == HCI_ERR_REPEATED_ATTEMPTS))) { + } else if ((p_dev_rec->sec_rec.link_key_type <= BTM_LKEY_TYPE_REMOTE_UNIT) && + ((status == HCI_ERR_AUTH_FAILURE) || (status == HCI_ERR_KEY_MISSING) || + (status == HCI_ERR_HOST_REJECT_SECURITY) || + (status == HCI_ERR_PAIRING_NOT_ALLOWED) || (status == HCI_ERR_UNIT_KEY_USED) || + (status == HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED) || + (status == HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE) || + (status == HCI_ERR_REPEATED_ATTEMPTS))) { + /* + Do not send authentication failure, if following conditions hold good + 1. BTM Sec Pairing state is idle + 2. Link key for the remote device is present. + 3. Remote is SSP capable. + */ p_dev_rec->sec_rec.security_required &= ~BTM_SEC_OUT_AUTHENTICATE; p_dev_rec->sec_rec.sec_flags &= ~(BTM_SEC_LE_LINK_KEY_KNOWN << bit_shift); @@ -4336,31 +4352,23 @@ void btm_sec_pin_code_request(const RawAddress p_bda) { btm_restore_mode(); */ btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); - } - - /* If pairing disabled OR (no PIN callback and not bonding) */ - /* OR we could not allocate entry in the database reject pairing request */ - else if (p_cb->pairing_disabled || - (p_cb->api.p_pin_callback == NULL) - - /* OR Microsoft keyboard can for some reason try to establish - * connection - */ - /* the only thing we can do here is to shut it up. Normally we will - be originator */ - /* for keyboard bonding */ - || (!p_dev_rec->IsLocallyInitiated() && - ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) == BTM_COD_MAJOR_PERIPHERAL) && - (p_dev_rec->dev_class[2] & BTM_COD_MINOR_KEYBOARD))) { + } else if (p_cb->pairing_disabled || (p_cb->api.p_pin_callback == NULL) || + (!p_dev_rec->IsLocallyInitiated() && + ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) == BTM_COD_MAJOR_PERIPHERAL) && + (p_dev_rec->dev_class[2] & BTM_COD_MINOR_KEYBOARD))) { + /* If pairing disabled + * OR no PIN callback and not bonding + * OR we could not allocate entry in the database reject pairing request + * OR Microsoft keyboard can for some reason try to establish connection the only thing we can + * do here is to shut it up. Normally we will be originator for keyboard bonding */ log::warn( "btm_sec_pin_code_request(): Pairing disabled:{}; PIN callback:{}, Dev " "Rec:{}!", p_cb->pairing_disabled, fmt::ptr(p_cb->api.p_pin_callback), fmt::ptr(p_dev_rec)); btsnd_hcic_pin_code_neg_reply(p_bda); - } - /* Notify upper layer of PIN request and start expiration timer */ - else { + } else { + /* Notify upper layer of PIN request and start expiration timer */ btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_LOCAL_PIN); /* Pin code request can not come at the same time as connection request */ p_cb->connecting_bda = p_bda; diff --git a/system/stack/btm/btm_sec_cb.cc b/system/stack/btm/btm_sec_cb.cc index 60a2f0398e..ac86e7f5b7 100644 --- a/system/stack/btm/btm_sec_cb.cc +++ b/system/stack/btm/btm_sec_cb.cc @@ -230,9 +230,8 @@ bool tBTM_SEC_CB::AddService(bool is_originator, const char* p_name, uint8_t ser record_allocated = true; break; } - } - /* Mark the first available service record */ - else if (!record_allocated) { + } else if (!record_allocated) { + /* Mark the first available service record */ *p_srec = {}; record_allocated = true; first_unused_record = index; diff --git a/system/stack/btm/hfp_lc3_decoder.cc b/system/stack/btm/hfp_lc3_decoder.cc index 245527b0dc..9cb1fa5296 100644 --- a/system/stack/btm/hfp_lc3_decoder.cc +++ b/system/stack/btm/hfp_lc3_decoder.cc @@ -21,6 +21,7 @@ #include <bluetooth/log.h> #include <lc3.h> +#include <cstdint> #include <cstring> #include "osi/include/allocator.h" diff --git a/system/stack/btm/hfp_lc3_encoder.cc b/system/stack/btm/hfp_lc3_encoder.cc index 9d909fef0d..71a2d77388 100644 --- a/system/stack/btm/hfp_lc3_encoder.cc +++ b/system/stack/btm/hfp_lc3_encoder.cc @@ -21,6 +21,7 @@ #include <bluetooth/log.h> #include <lc3.h> +#include <cstdint> #include <cstring> #include "osi/include/allocator.h" diff --git a/system/stack/btm/hfp_msbc_decoder.cc b/system/stack/btm/hfp_msbc_decoder.cc index d1396a771d..21666b4284 100644 --- a/system/stack/btm/hfp_msbc_decoder.cc +++ b/system/stack/btm/hfp_msbc_decoder.cc @@ -20,9 +20,11 @@ #include <bluetooth/log.h> +#include <cstdint> #include <cstring> #include "embdrv/sbc/decoder/include/oi_codec_sbc.h" +#include "embdrv/sbc/decoder/include/oi_cpu_dep.h" #include "embdrv/sbc/decoder/include/oi_status.h" #define HFP_MSBC_PKT_LEN 60 diff --git a/system/stack/btm/hfp_msbc_encoder.cc b/system/stack/btm/hfp_msbc_encoder.cc index 4f4d6057d1..ab086cf5cf 100644 --- a/system/stack/btm/hfp_msbc_encoder.cc +++ b/system/stack/btm/hfp_msbc_encoder.cc @@ -18,6 +18,7 @@ #include "hfp_msbc_encoder.h" +#include <cstdint> #include <cstring> #include "embdrv/sbc/encoder/include/sbc_encoder.h" diff --git a/system/stack/btm/security_device_record.h b/system/stack/btm/security_device_record.h index 6dc0cfa792..e6608903a4 100644 --- a/system/stack/btm/security_device_record.h +++ b/system/stack/btm/security_device_record.h @@ -41,7 +41,6 @@ typedef struct { uint16_t max_conn_int; uint16_t peripheral_latency; uint16_t supervision_tout; - } tBTM_LE_CONN_PRAMS; /* The MSB of the clock offset field indicates whether the offset is valid. */ @@ -61,8 +60,8 @@ typedef struct { (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT | BTM_SEC_IN_MITM | BTM_SEC_MODE4_LEVEL4) typedef struct { uint32_t mx_proto_id; /* Service runs over this multiplexer protocol */ - uint32_t orig_mx_chan_id; /* Channel on the multiplexer protocol */ - uint32_t term_mx_chan_id; /* Channel on the multiplexer protocol */ + uint32_t orig_mx_chan_id; /* Channel on the multiplexer protocol */ + uint32_t term_mx_chan_id; /* Channel on the multiplexer protocol */ uint16_t psm; /* L2CAP PSM value */ uint16_t security_flags; /* Bitmap of required security features */ uint8_t service_id; /* Passed in authorization callback */ @@ -74,15 +73,15 @@ typedef struct { typedef struct { Octet16 irk; /* peer diverified identity root */ Octet16 pltk; /* peer long term key */ - Octet16 pcsrk; /* peer SRK peer device used to secured sign local data */ + Octet16 pcsrk; /* peer SRK peer device used to secured sign local data */ Octet16 lltk; /* local long term key */ - Octet16 lcsrk; /* local SRK peer device used to secured sign local data */ + Octet16 lcsrk; /* local SRK peer device used to secured sign local data */ BT_OCTET8 rand; /* random vector for LTK generation */ uint16_t ediv; /* LTK diversifier of this peripheral device */ - uint16_t div; /* local DIV to generate local LTK=d1(ER,DIV,0) and - CSRK=d1(ER,DIV,1) */ + uint16_t div; /* local DIV to generate local LTK=d1(ER, DIV, 0) and + CSRK=d1(ER, DIV, 1) */ uint8_t sec_level; /* local pairing security level */ uint8_t key_size; /* key size of the LTK delivered to peer device */ uint8_t srk_sec_level; /* security property of peer SRK for this device */ @@ -104,8 +103,7 @@ enum tBLE_RAND_ADDR_TYPE : uint8_t { class tBTM_BLE_ADDR_INFO { public: - RawAddress pseudo_addr; /* LE pseudo address of the device if different from - device address */ + RawAddress pseudo_addr; /* LE pseudo address of the device if different from device address */ public: tBLE_ADDR_TYPE AddressType() const { return ble_addr_type_; } void SetAddressType(tBLE_ADDR_TYPE ble_addr_type) { @@ -202,12 +200,12 @@ struct tBTM_SEC_REC { tSECURITY_STATE classic_link; /* Operating state of Classic link */ tSECURITY_STATE le_link; /* Operating state of LE link */ - tHCI_STATUS sec_status; /* Status in encryption change event */ - uint16_t sec_flags; /* Current device security state */ + tHCI_STATUS sec_status; /* Status in encryption change event */ + uint16_t sec_flags; /* Current device security state */ uint8_t pin_code_length; /* Length of the pin_code used for pairing */ uint32_t required_security_flags_for_pairing; - uint16_t security_required; /* Security required for connection */ + uint16_t security_required; /* Security required for connection */ // security callback and its argument tBTM_SEC_CALLBACK* p_callback; void* p_ref_data; @@ -222,9 +220,9 @@ struct tBTM_SEC_REC { ** for SM over BR/EDR. */ // BREDR Link Key Info - LinkKey link_key; /* Device link key */ - uint8_t link_key_type; /* Type of key used in pairing */ - uint8_t enc_key_size; /* current link encryption key size */ + LinkKey link_key; /* Device link key */ + uint8_t link_key_type; /* Type of key used in pairing */ + uint8_t enc_key_size; /* current link encryption key size */ // LE Link Key Info tBTM_SEC_BLE_KEYS ble_keys; @@ -347,16 +345,15 @@ public: tBTM_BLE_ADDR_INFO ble; BD_NAME sec_bd_name; /* User friendly name of the device. (may be truncated to save space in dev_rec table) */ - DEV_CLASS dev_class; /* DEV_CLASS of the device */ + DEV_CLASS dev_class; /* DEV_CLASS of the device */ tBT_DEVICE_TYPE device_type; - uint32_t timestamp; /* Timestamp of the last connection */ + uint32_t timestamp; /* Timestamp of the last connection */ uint16_t hci_handle; /* Handle to BR/EDR ACL connection when exists */ uint16_t ble_hci_handle; /* use in DUMO connection */ - uint16_t suggested_tx_octets; /* Recently suggested tx octets for data length - extension */ - uint16_t clock_offset; /* Latest known clock offset */ + uint16_t suggested_tx_octets; /* Recently suggested tx octets for data length extension */ + uint16_t clock_offset; /* Latest known clock offset */ // whether the peer device can read GAP characteristics only visible in // "discoverable" mode @@ -375,7 +372,7 @@ public: tREMOTE_VERSION_INFO remote_version_info; - bool role_central; /* true if current mode is central (BLE) */ + bool role_central; /* true if current mode is central (BLE) */ bool is_originator; /* true if device is originating ACL connection */ // BLE connection parameters diff --git a/system/stack/connection_manager/connection_manager.h b/system/stack/connection_manager/connection_manager.h index a9a5256261..4d86eae0e3 100644 --- a/system/stack/connection_manager/connection_manager.h +++ b/system/stack/connection_manager/connection_manager.h @@ -20,7 +20,7 @@ #include <set> -#include "ble_address_with_type.h" +#include "types/ble_address_with_type.h" #include "types/raw_address.h" /* connection_manager takes care of all the low-level details of LE connection diff --git a/system/stack/gatt/gatt_cl.cc b/system/stack/gatt/gatt_cl.cc index 50844962f4..6093d572ee 100644 --- a/system/stack/gatt/gatt_cl.cc +++ b/system/stack/gatt/gatt_cl.cc @@ -884,10 +884,9 @@ static void gatt_process_read_by_type_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, ui break; } } - } - /* discover included service */ - else if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY && - p_clcb->op_subtype == GATT_DISC_INC_SRVC) { + } else if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY && + p_clcb->op_subtype == GATT_DISC_INC_SRVC) { + /* discover included service */ if (value_len < 4) { log::error("Illegal Response length, must be at least 4."); gatt_end_operation(p_clcb, GATT_INVALID_PDU, NULL); @@ -920,9 +919,8 @@ static void gatt_process_read_by_type_rsp(tGATT_TCB& tcb, tGATT_CLCB* p_clcb, ui gatt_end_operation(p_clcb, GATT_INVALID_PDU, (void*)p); return; } - } - /* read by type */ - else if (p_clcb->operation == GATTC_OPTYPE_READ && p_clcb->op_subtype == GATT_READ_BY_TYPE) { + } else if (p_clcb->operation == GATTC_OPTYPE_READ && p_clcb->op_subtype == GATT_READ_BY_TYPE) { + /* read by type */ p_clcb->counter = len - 2; p_clcb->s_handle = handle; diff --git a/system/stack/gatt/gatt_db.cc b/system/stack/gatt/gatt_db.cc index cd55ffdb71..9dd73128b5 100644 --- a/system/stack/gatt/gatt_db.cc +++ b/system/stack/gatt/gatt_db.cc @@ -55,7 +55,7 @@ void gatts_init_service_db(tGATT_SVC_DB& db, const Uuid& service_uuid, bool is_p db.next_handle = s_hdl; db.end_handle = s_hdl + num_handle; - /* add service declration record */ + /* add service declaration record */ Uuid uuid = Uuid::From16Bit(is_pri ? GATT_UUID_PRI_SERVICE : GATT_UUID_SEC_SERVICE); tGATT_ATTR& attr = allocate_attr_in_db(db, uuid, GATT_PERM_READ); attr.p_value.reset(new tGATT_ATTR_VALUE); @@ -360,7 +360,7 @@ uint16_t gatts_add_included_service(tGATT_SVC_DB& db, uint16_t s_handle, uint16_ * Function gatts_add_characteristic * * Description This function add a characteristics and its descriptor into - * a servce identified by the service database pointer. + * a service identified by the service database pointer. * * Parameter db: database. * perm: permission (authentication and key size requirements) @@ -568,12 +568,11 @@ tGATT_STATUS gatts_write_attr_perm_check(tGATT_SVC_DB* p_db, uint8_t op_code, ui /* LE security mode 2 level 1 and LE security mode 1 level 2 */ if ((perm & GATT_PERM_WRITE_SIGNED) && (perm & GATT_PERM_WRITE_ENCRYPTED)) { perm = GATT_PERM_WRITE_ENCRYPTED; - } - /* use security mode 1 level 3 when the following condition follows */ - /* LE security mode 2 level 2 and security mode 1 and LE */ - else if (((perm & GATT_PERM_WRITE_SIGNED_MITM) && (perm & GATT_PERM_WRITE_ENCRYPTED)) || - /* LE security mode 2 and security mode 1 level 3 */ - ((perm & GATT_WRITE_SIGNED_PERM) && (perm & GATT_PERM_WRITE_ENC_MITM))) { + } else if (((perm & GATT_PERM_WRITE_SIGNED_MITM) && (perm & GATT_PERM_WRITE_ENCRYPTED)) || + ((perm & GATT_WRITE_SIGNED_PERM) && (perm & GATT_PERM_WRITE_ENC_MITM))) { + /* use security mode 1 level 3 when the following condition follows */ + /* LE security mode 2 level 2 and security mode 1 and LE */ + /* LE security mode 2 and security mode 1 level 3 */ perm = GATT_PERM_WRITE_ENC_MITM; } } @@ -585,13 +584,12 @@ tGATT_STATUS gatts_write_attr_perm_check(tGATT_SVC_DB* p_db, uint8_t op_code, ui } if ((op_code == GATT_SIGN_CMD_WRITE) && sec_flag.is_encrypted) { status = GATT_INVALID_PDU; - log::error("Error!! sign cmd write sent on a encypted link"); + log::error("Error!! sign cmd write sent on a encrypted link"); } else if (!(perm & GATT_WRITE_ALLOWED)) { status = GATT_WRITE_NOT_PERMIT; log::error("GATT_WRITE_NOT_PERMIT"); - } - /* require authentication, but not been authenticated */ - else if ((perm & GATT_WRITE_AUTH_REQUIRED) && !sec_flag.is_link_key_known) { + } else if ((perm & GATT_WRITE_AUTH_REQUIRED) && !sec_flag.is_link_key_known) { + /* require authentication, but not been authenticated */ status = GATT_INSUF_AUTHENTICATION; log::error("GATT_INSUF_AUTHENTICATION"); } else if ((perm & GATT_WRITE_MITM_REQUIRED) && !sec_flag.is_link_key_authed) { @@ -604,14 +602,13 @@ tGATT_STATUS gatts_write_attr_perm_check(tGATT_SVC_DB* p_db, uint8_t op_code, ui (key_size < min_key_size)) { status = GATT_INSUF_KEY_SIZE; log::error("GATT_INSUF_KEY_SIZE"); - } - /* LE security mode 2 attribute */ - else if (perm & GATT_WRITE_SIGNED_PERM && op_code != GATT_SIGN_CMD_WRITE && - !sec_flag.is_encrypted && (perm & GATT_WRITE_ALLOWED) == 0) { + } else if (perm & GATT_WRITE_SIGNED_PERM && op_code != GATT_SIGN_CMD_WRITE && + !sec_flag.is_encrypted && (perm & GATT_WRITE_ALLOWED) == 0) { + /* LE security mode 2 attribute */ status = GATT_INSUF_AUTHENTICATION; log::error("GATT_INSUF_AUTHENTICATION: LE security mode 2 required"); - } else /* writable: must be char value declaration or char descritpors */ - { + } else { + /* writable: must be char value declaration or char descriptors */ uint16_t max_size = 0; if (p_attr->uuid.IsEmpty()) { diff --git a/system/stack/gatt/gatt_main.cc b/system/stack/gatt/gatt_main.cc index 2cf2c42a51..e530d9fd5e 100644 --- a/system/stack/gatt/gatt_main.cc +++ b/system/stack/gatt/gatt_main.cc @@ -533,10 +533,8 @@ static void gatt_le_connect_cback(uint16_t /* chan */, const RawAddress& bd_addr if (check_srv_chg) { gatt_chk_srv_chg(p_srv_chg_clt); } - } - /* this is incoming connection or background connection callback */ - - else { + } else { + /* this is incoming connection or background connection callback */ p_tcb = gatt_allocate_tcb_by_bdaddr(bd_addr, BT_TRANSPORT_LE); if (!p_tcb) { log::error("Disconnecting address:{} due to out of resources.", bd_addr); diff --git a/system/stack/hid/hidd_api.cc b/system/stack/hid/hidd_api.cc index 79f4d1d7b0..169868bbfc 100644 --- a/system/stack/hid/hidd_api.cc +++ b/system/stack/hid/hidd_api.cc @@ -32,8 +32,12 @@ #include <stdlib.h> #include <string.h> +#include <cstdint> + +#include "hid_conn.h" #include "hidd_int.h" #include "hiddefs.h" +#include "internal_include/bt_target.h" #include "osi/include/allocator.h" #include "stack/include/bt_psm_types.h" #include "stack/include/bt_types.h" @@ -41,6 +45,7 @@ #include "stack/include/sdp_api.h" #include "stack/include/sdpdefs.h" #include "stack/include/stack_metrics_logging.h" +#include "stack/sdp/sdp_discovery_db.h" #include "types/raw_address.h" using namespace bluetooth; diff --git a/system/stack/hid/hidd_conn.cc b/system/stack/hid/hidd_conn.cc index c64a7b9104..b50516d8a8 100644 --- a/system/stack/hid/hidd_conn.cc +++ b/system/stack/hid/hidd_conn.cc @@ -27,10 +27,16 @@ #include <bluetooth/log.h> #include <frameworks/proto_logging/stats/enums/bluetooth/enums.pb.h> +#include <cstddef> #include <cstdint> +#include <cstring> #include "bta/include/bta_sec_api.h" +#include "hid_conn.h" +#include "hidd_api.h" +#include "hiddefs.h" #include "internal_include/bt_target.h" +#include "l2cap_types.h" #include "osi/include/allocator.h" #include "stack/hid/hidd_int.h" #include "stack/include/bt_hdr.h" @@ -38,6 +44,7 @@ #include "stack/include/l2cap_interface.h" #include "stack/include/l2cdefs.h" #include "stack/include/stack_metrics_logging.h" +#include "types/bt_transport.h" #include "types/raw_address.h" using namespace bluetooth; diff --git a/system/stack/hid/hidh_api.cc b/system/stack/hid/hidh_api.cc index f415c48fb1..a02af75063 100644 --- a/system/stack/hid/hidh_api.cc +++ b/system/stack/hid/hidh_api.cc @@ -31,14 +31,21 @@ #include <stdlib.h> #include <string.h> +#include <cstdint> + +#include "hid_conn.h" #include "hiddefs.h" #include "hidh_int.h" #include "internal_include/bt_target.h" +#include "osi/include/alarm.h" #include "osi/include/allocator.h" +#include "sdp_api.h" +#include "sdp_status.h" #include "stack/include/bt_hdr.h" #include "stack/include/bt_uuid16.h" #include "stack/include/sdpdefs.h" #include "stack/include/stack_metrics_logging.h" +#include "stack/sdp/sdp_discovery_db.h" #include "types/bluetooth/uuid.h" #include "types/raw_address.h" @@ -494,9 +501,7 @@ tHID_STATUS HID_HostWriteDev(uint8_t dev_handle, uint8_t t_type, uint8_t param, android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_INVALID_PARAM_AT_HOST_WRITE_DEV, 1); status = HID_ERR_INVALID_PARAM; - } - - else if (hh_cb.devices[dev_handle].state != HID_DEV_CONNECTED) { + } else if (hh_cb.devices[dev_handle].state != HID_DEV_CONNECTED) { log::error("HID_ERR_NO_CONNECTION dev_handle {}", dev_handle); log_counter_metrics( android::bluetooth::CodePathCounterKeyEnum::HIDH_ERR_NO_CONNECTION_AT_HOST_WRITE_DEV, diff --git a/system/stack/hid/hidh_conn.cc b/system/stack/hid/hidh_conn.cc index 5205b322df..cc2a480b57 100644 --- a/system/stack/hid/hidh_conn.cc +++ b/system/stack/hid/hidh_conn.cc @@ -28,11 +28,18 @@ #include <frameworks/proto_logging/stats/enums/bluetooth/enums.pb.h> #include <string.h> +#include <cstdint> + #include "bta/include/bta_sec_api.h" +#include "hci_error_code.h" +#include "hid_conn.h" #include "hiddefs.h" #include "hidh_api.h" #include "hidh_int.h" #include "internal_include/bt_target.h" +#include "l2cap_types.h" +#include "l2cdefs.h" +#include "osi/include/alarm.h" #include "osi/include/allocator.h" #include "osi/include/osi.h" #include "stack/include/acl_api.h" @@ -42,6 +49,7 @@ #include "stack/include/btm_log_history.h" #include "stack/include/l2cap_interface.h" #include "stack/include/stack_metrics_logging.h" +#include "types/bt_transport.h" #include "types/raw_address.h" using namespace bluetooth; @@ -832,7 +840,6 @@ tHID_STATUS hidh_conn_snd_data(uint8_t dhandle, uint8_t trans_type, uint8_t para trans_type = HID_TRANS_DATAC; blank_datc = true; } - } while ((data_size != 0) || blank_datc); return HID_SUCCESS; diff --git a/system/stack/include/a2dp_constants.h b/system/stack/include/a2dp_constants.h index 55a9b9abd3..090c25a315 100644 --- a/system/stack/include/a2dp_constants.h +++ b/system/stack/include/a2dp_constants.h @@ -169,6 +169,8 @@ enum tA2DP_STATUS : uint8_t { namespace fmt { template <> +struct formatter<bluetooth::a2dp::CodecId> : enum_formatter<bluetooth::a2dp::CodecId> {}; +template <> struct formatter<tA2DP_CODEC_TYPE> : enum_formatter<tA2DP_CODEC_TYPE> {}; template <> struct formatter<tA2DP_STATUS> : enum_formatter<tA2DP_STATUS> {}; diff --git a/system/stack/include/a2dp_vendor.h b/system/stack/include/a2dp_vendor.h index bc78341a00..00159e7ba4 100644 --- a/system/stack/include/a2dp_vendor.h +++ b/system/stack/include/a2dp_vendor.h @@ -100,30 +100,6 @@ const char* A2DP_VendorCodecName(const uint8_t* p_codec_info); // If the codec type is not recognized, the return value is false. bool A2DP_VendorCodecTypeEquals(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b); -// Checks whether two A2DP vendor-specific codecs |p_codec_info_a| and -// |p_codec_info_b| are exactly the same. -// Returns true if the two codecs are exactly the same, otherwise false. -// If the codec type is not recognized, the return value is false. -bool A2DP_VendorCodecEquals(const uint8_t* p_codec_info_a, const uint8_t* p_codec_info_b); - -// Gets the track sample rate value for the A2DP vendor-specific codec. -// |p_codec_info| is a pointer to the vendor-specific codec_info to decode. -// Returns the track sample rate on success, or -1 if |p_codec_info| -// contains invalid codec information. -int A2DP_VendorGetTrackSampleRate(const uint8_t* p_codec_info); - -// Gets the track bits per sample value for the A2DP vendor-specific codec. -// |p_codec_info| is a pointer to the vendor-specific codec_info to decode. -// Returns the track sample rate on success, or -1 if |p_codec_info| -// contains invalid codec information. -int A2DP_VendorGetTrackBitsPerSample(const uint8_t* p_codec_info); - -// Gets the channel count for the A2DP vendor-specific codec. -// |p_codec_info| is a pointer to the vendor-specific codec_info to decode. -// Returns the channel count on success, or -1 if |p_codec_info| -// contains invalid codec information. -int A2DP_VendorGetTrackChannelCount(const uint8_t* p_codec_info); - // Gets the bitrate for the A2DP vendor-specific codec. // |p_codec_info| is a pointer to the vendor-specific codec_info to decode. // Returns the channel count on success, or -1 if |p_codec_info| @@ -137,14 +113,6 @@ int A2DP_VendorGetBitRate(const uint8_t* p_codec_info); // contains invalid codec information. int A2DP_VendorGetSinkTrackChannelType(const uint8_t* p_codec_info); -// Gets the A2DP codec-specific audio data timestamp from an audio packet. -// |p_codec_info| contains the codec information. -// |p_data| contains the audio data. -// The timestamp is stored in |p_timestamp|. -// Returns true on success, otherwise false. -bool A2DP_VendorGetPacketTimestamp(const uint8_t* p_codec_info, const uint8_t* p_data, - uint32_t* p_timestamp); - // Builds A2DP vendor-specific codec header for audio data. // |p_codec_info| contains the codec information. // |p_buf| contains the audio data. diff --git a/system/stack/include/bnep_api.h b/system/stack/include/bnep_api.h index a11ce06218..2637cadb80 100644 --- a/system/stack/include/bnep_api.h +++ b/system/stack/include/bnep_api.h @@ -70,7 +70,6 @@ enum { BNEP_IGNORE_CMD, /* To ignore the rcvd command */ BNEP_TX_FLOW_ON, /* tx data flow enabled */ BNEP_TX_FLOW_OFF /* tx data flow disabled */ - }; typedef uint8_t tBNEP_RESULT; @@ -171,7 +170,6 @@ typedef struct { tBNEP_TX_DATA_FLOW_CB* p_tx_data_flow_cb; /* data flow callback */ tBNEP_FILTER_IND_CB* p_filter_ind_cb; /* To indicate that peer set protocol filters */ tBNEP_MFILTER_IND_CB* p_mfilter_ind_cb; /* To indicate that peer set mcast filters */ - } tBNEP_REGISTER; /***************************************************************************** diff --git a/system/stack/include/btm_ble_sec_api_types.h b/system/stack/include/btm_ble_sec_api_types.h index d53b628f26..e1d1bc4e6e 100644 --- a/system/stack/include/btm_ble_sec_api_types.h +++ b/system/stack/include/btm_ble_sec_api_types.h @@ -69,8 +69,7 @@ typedef union { tBTM_LE_PENC_KEYS penc_key; /* received peer encryption key */ tBTM_LE_PCSRK_KEYS pcsrk_key; /* received peer device SRK */ tBTM_LE_PID_KEYS pid_key; /* peer device ID key */ - tBTM_LE_LENC_KEYS lenc_key; /* local encryption reproduction keys - * LTK = = d1(ER,DIV,0) */ + tBTM_LE_LENC_KEYS lenc_key; /* local encryption reproduction keys LTK = = d1(ER, DIV, 0) */ tBTM_LE_LCSRK_KEYS lcsrk_key; /* local device CSRK = d1(ER,DIV,1)*/ } tBTM_LE_KEY_VALUE; @@ -80,20 +79,18 @@ typedef struct { } tBTM_LE_KEY; typedef union { - tBTM_LE_IO_REQ io_req; /* BTM_LE_IO_REQ_EVT */ - uint32_t key_notif; /* BTM_LE_KEY_NOTIF_EVT */ + tBTM_LE_IO_REQ io_req; /* BTM_LE_IO_REQ_EVT */ + uint32_t key_notif; /* BTM_LE_KEY_NOTIF_EVT */ /* BTM_LE_NC_REQ_EVT */ - /* no callback data for - * BTM_LE_KEY_REQ_EVT - * and BTM_LE_OOB_REQ_EVT */ - tBTM_LE_COMPLT complt; /* BTM_LE_COMPLT_EVT */ + /* no callback data for BTM_LE_KEY_REQ_EVT and BTM_LE_OOB_REQ_EVT */ + tBTM_LE_COMPLT complt; /* BTM_LE_COMPLT_EVT */ tSMP_OOB_DATA_TYPE req_oob_type; tBTM_LE_KEY key; tSMP_LOC_OOB_DATA local_oob_data; RawAddress id_addr; } tBTM_LE_EVT_DATA; -/* Simple Pairing Events. Called by the stack when Simple Pairing related +/* Simple Pairing Events. Called by the stack when Simple Pairing related * events occur. */ typedef tBTM_STATUS(tBTM_LE_CALLBACK)(tBTM_LE_EVT event, const RawAddress& bda, @@ -107,7 +104,6 @@ typedef struct { Octet16 ir; Octet16 irk; Octet16 dhk; - } tBTM_BLE_LOCAL_ID_KEYS; typedef union { diff --git a/system/stack/include/gap_api.h b/system/stack/include/gap_api.h index 04329fdd9e..e4a185eefe 100644 --- a/system/stack/include/gap_api.h +++ b/system/stack/include/gap_api.h @@ -103,7 +103,6 @@ typedef union { uint16_t icon; uint8_t* p_dev_name; uint8_t addr_resolution; - } tGAP_BLE_ATTR_VALUE; typedef void(tGAP_BLE_CMPL_CBACK)(bool status, const RawAddress& addr, uint16_t length, diff --git a/system/stack/include/gatt_api.h b/system/stack/include/gatt_api.h index 54ecfdccb3..804d6390a2 100644 --- a/system/stack/include/gatt_api.h +++ b/system/stack/include/gatt_api.h @@ -279,7 +279,6 @@ typedef enum : uint16_t { GATT_CONN_TERMINATED_POWER_OFF = HCI_ERR_REMOTE_POWER_OFF, BTA_GATT_CONN_NONE = 0x0101, /* 0x0101 no connection to cancel */ - } tGATT_DISCONN_REASON; inline std::string gatt_disconnection_reason_text(const tGATT_DISCONN_REASON& reason) { @@ -502,7 +501,6 @@ typedef union { tGATT_VALUE attr_value; /* READ, HANDLE_VALUE_IND, PREPARE_WRITE */ /* READ_BLOB, READ_BY_TYPE */ uint16_t handle; /* WRITE, WRITE_BLOB */ - } tGATTS_RSP; #define GATT_PREP_WRITE_CANCEL 0x00 diff --git a/system/stack/include/sdp_api.h b/system/stack/include/sdp_api.h index 987a449a89..f639b107f7 100644 --- a/system/stack/include/sdp_api.h +++ b/system/stack/include/sdp_api.h @@ -562,7 +562,6 @@ struct tSdpApi { [[nodiscard]] tSDP_STATUS (*SDP_GetDiRecord)(uint8_t getRecordIndex, tSDP_DI_GET_RECORD* device_info, const tSDP_DISCOVERY_DB* p_db); - } device_id; }; diff --git a/system/stack/include/srvc_api.h b/system/stack/include/srvc_api.h index 43a24e1437..2e22ba49c1 100644 --- a/system/stack/include/srvc_api.h +++ b/system/stack/include/srvc_api.h @@ -59,7 +59,6 @@ typedef struct { uint16_t product_id; uint16_t product_version; uint8_t vendor_id_src; - } tDIS_PNP_ID; typedef union { @@ -106,7 +105,6 @@ typedef struct { tBA_LEVEL_DESCR ba_level_descr; tBT_TRANSPORT transport; tBA_CBACK* p_cback; - } tBA_REG_INFO; typedef union { diff --git a/system/stack/l2cap/l2c_api.cc b/system/stack/l2cap/l2c_api.cc index b9587454f1..99b0276413 100644 --- a/system/stack/l2cap/l2c_api.cc +++ b/system/stack/l2cap/l2c_api.cc @@ -552,15 +552,12 @@ uint16_t L2CA_ConnectLECocReq(uint16_t psm, const RawAddress& p_bd_addr, tL2CAP_ do_in_main_thread(base::BindOnce(&l2c_csm_execute, base::Unretained(p_ccb), L2CEVT_L2CA_CONNECT_REQ, nullptr)); } - } - - /* If link is disconnecting, save link info to retry after disconnect - * Possible Race condition when a reconnect occurs - * on the channel during a disconnect of link. This - * ccb will be automatically retried after link disconnect - * arrives - */ - else if (p_lcb->link_state == LST_DISCONNECTING) { + } else if (p_lcb->link_state == LST_DISCONNECTING) { + /* If link is disconnecting, save link info to retry after disconnect + * Possible Race condition when a reconnect occurs + * on the channel during a disconnect of link. This + * ccb will be automatically retried after link disconnect + * arrives */ log::verbose("link disconnecting: RETRY LATER"); /* Save ccb so it can be started after disconnect is finished */ diff --git a/system/stack/l2cap/l2c_csm.cc b/system/stack/l2cap/l2c_csm.cc index 776596a6f5..ba438765eb 100644 --- a/system/stack/l2cap/l2c_csm.cc +++ b/system/stack/l2cap/l2c_csm.cc @@ -212,8 +212,9 @@ void l2c_csm_execute(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) { // Log all but data events if (event != L2CEVT_L2CAP_DATA && event != L2CEVT_L2CA_DATA_READ && event != L2CEVT_L2CA_DATA_WRITE) { - log::info("Enter CSM, chnl_state:{} [{}], event:{} [{}]", channel_state_text(p_ccb->chnl_state), - p_ccb->chnl_state, l2c_csm_get_event_name(event), event); + log::info("Enter CSM, chnl_state:{} [{}] event:{} lcid:0x{:04x} rcid:0x{:04x}", + channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state, + l2c_csm_get_event_name(event), p_ccb->local_cid, p_ccb->remote_cid); } switch (p_ccb->chnl_state) { diff --git a/system/stack/l2cap/l2c_fcr.cc b/system/stack/l2cap/l2c_fcr.cc index 9b144ec897..b310b37443 100644 --- a/system/stack/l2cap/l2c_fcr.cc +++ b/system/stack/l2cap/l2c_fcr.cc @@ -1423,9 +1423,8 @@ BT_HDR* l2c_fcr_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb, uint16_t max_packet_lengt /* copy PBF setting */ p_xmit->layer_specific = p_buf->layer_specific; - } else /* Should never happen if the application has configured buffers - correctly */ - { + } else { + /* Should never happen if the application has configured buffers correctly */ log::error("L2CAP - cannot get buffer for segmentation, max_pdu: {}", max_pdu); return NULL; } @@ -1794,10 +1793,8 @@ uint8_t l2c_fcr_process_peer_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) { p_cfg->fcr.tx_win_sz = p_ccb->our_cfg.fcr.tx_win_sz; p_cfg->fcr.max_transmit = p_ccb->our_cfg.fcr.max_transmit; fcr_ok = L2CAP_PEER_CFG_UNACCEPTABLE; - } - - /* If we wanted basic, then try to renegotiate it */ - else if (p_ccb->p_rcb->ertm_info.preferred_mode == L2CAP_FCR_BASIC_MODE) { + } else if (p_ccb->p_rcb->ertm_info.preferred_mode == L2CAP_FCR_BASIC_MODE) { + /* If we wanted basic, then try to renegotiate it */ p_cfg->fcr.mode = L2CAP_FCR_BASIC_MODE; p_cfg->fcr.max_transmit = p_cfg->fcr.tx_win_sz = 0; p_cfg->fcr.rtrans_tout = p_cfg->fcr.mon_tout = p_cfg->fcr.mps = 0; diff --git a/system/stack/l2cap/l2c_link.cc b/system/stack/l2cap/l2c_link.cc index 3a3bb4290d..a202c36549 100644 --- a/system/stack/l2cap/l2c_link.cc +++ b/system/stack/l2cap/l2c_link.cc @@ -134,10 +134,9 @@ void l2c_link_hci_conn_comp(tHCI_STATUS status, uint16_t handle, const RawAddres uint64_t timeout_ms = L2CAP_LINK_STARTUP_TOUT * 1000; alarm_set_on_mloop(p_lcb->l2c_lcb_timer, timeout_ms, l2c_lcb_timer_timeout, p_lcb); } - } - /* Max number of acl connections. */ - /* If there's an lcb disconnecting set this one to holding */ - else if ((ci.hci_status == HCI_ERR_MAX_NUM_OF_CONNECTIONS) && l2cu_lcb_disconnecting()) { + } else if ((ci.hci_status == HCI_ERR_MAX_NUM_OF_CONNECTIONS) && l2cu_lcb_disconnecting()) { + /* Max number of acl connections. */ + /* If there's an lcb disconnecting set this one to holding */ log::warn("Delaying connection as reached max number of links:{}", HCI_ERR_MAX_NUM_OF_CONNECTIONS); p_lcb->link_state = LST_CONNECT_HOLDING; @@ -616,16 +615,14 @@ void l2c_link_adjust_allocation(void) { if (num_lowpri_links > low_quota) { l2cb.round_robin_quota = low_quota; qq = qq_remainder = 1; - } - /* If each low priority link can have at least one buffer */ - else if (num_lowpri_links > 0) { + } else if (num_lowpri_links > 0) { + /* If each low priority link can have at least one buffer */ l2cb.round_robin_quota = 0; l2cb.round_robin_unacked = 0; qq = low_quota / num_lowpri_links; qq_remainder = low_quota % num_lowpri_links; - } - /* If no low priority link */ - else { + } else { + /* If no low priority link */ l2cb.round_robin_quota = 0; l2cb.round_robin_unacked = 0; qq = qq_remainder = 1; @@ -924,9 +921,8 @@ void l2c_link_check_send_pkts(tL2C_LCB* p_lcb, uint16_t local_cid, BT_HDR* p_buf /* If only doing one write, break out */ log::debug("single_write is true, skipping"); break; - } - /* If nothing on the link queue, check the channel queue */ - else { + } else { + /* If nothing on the link queue, check the channel queue */ tL2C_TX_COMPLETE_CB_INFO cbi = {}; log::debug("Check next buffer"); p_buf = l2cu_get_next_buffer_to_send(p_lcb, &cbi); diff --git a/system/stack/mmc/BUILD.gn b/system/stack/mmc/BUILD.gn index 2aa3a316ef..e4df3a7f07 100644 --- a/system/stack/mmc/BUILD.gn +++ b/system/stack/mmc/BUILD.gn @@ -125,7 +125,7 @@ if (use.test) { "//bt/system/test/common/mock_functions.cc", ] include_dirs = [ - "//bt/system/types", + "//bt/system", ] configs += [ ":target_defaults", @@ -154,7 +154,7 @@ if (use.test) { "//bt/system/test/common/mock_functions.cc", ] include_dirs = [ - "//bt/system/types", + "//bt/system", ] configs += [ ":target_defaults", diff --git a/system/stack/pan/pan_api.cc b/system/stack/pan/pan_api.cc index 1fb209a17b..0d6d17f368 100644 --- a/system/stack/pan/pan_api.cc +++ b/system/stack/pan/pan_api.cc @@ -32,6 +32,7 @@ #include <cstdint> #include <cstring> +#include <string> #include "bta/sys/bta_sys.h" #include "internal_include/bt_target.h" diff --git a/system/stack/pan/pan_int.h b/system/stack/pan/pan_int.h index 6a65cdf5ad..f64f2ae6a7 100644 --- a/system/stack/pan/pan_int.h +++ b/system/stack/pan/pan_int.h @@ -74,7 +74,6 @@ typedef struct { size_t errors{0}; size_t drops{0}; } write, read; - } tPAN_CONN; /* The main PAN control block diff --git a/system/stack/pan/pan_main.cc b/system/stack/pan/pan_main.cc index 0b3cb55898..f4e7a65226 100644 --- a/system/stack/pan/pan_main.cc +++ b/system/stack/pan/pan_main.cc @@ -31,7 +31,9 @@ #include <cstdint> +#include "internal_include/bt_target.h" #include "osi/include/allocator.h" +#include "pan_api.h" #include "stack/include/bnep_api.h" #include "stack/include/bt_hdr.h" #include "stack/include/bt_uuid16.h" diff --git a/system/stack/pan/pan_utils.cc b/system/stack/pan/pan_utils.cc index eef9431004..e135bd5c21 100644 --- a/system/stack/pan/pan_utils.cc +++ b/system/stack/pan/pan_utils.cc @@ -27,8 +27,11 @@ #include <bluetooth/log.h> +#include <cstddef> #include <cstdint> +#include <cstring> +#include "bnep_api.h" #include "internal_include/bt_target.h" #include "stack/include/bt_types.h" #include "stack/include/bt_uuid16.h" diff --git a/system/stack/rfcomm/port_rfc.cc b/system/stack/rfcomm/port_rfc.cc index 387e7a7197..be15fb1217 100644 --- a/system/stack/rfcomm/port_rfc.cc +++ b/system/stack/rfcomm/port_rfc.cc @@ -953,9 +953,8 @@ uint32_t port_rfc_send_tx_data(tPORT* p_port) { events |= PORT_EV_TXEMPTY; break; } - } - /* queue is empty-- all data sent */ - else { + } else { + /* queue is empty-- all data sent */ mutex_global_unlock(); events |= PORT_EV_TXEMPTY; diff --git a/system/stack/rfcomm/port_utils.cc b/system/stack/rfcomm/port_utils.cc index 7f64661ead..88276d0d26 100644 --- a/system/stack/rfcomm/port_utils.cc +++ b/system/stack/rfcomm/port_utils.cc @@ -480,21 +480,18 @@ void port_flow_control_peer(tPORT* p_port, bool enable, uint16_t count) { p_port->rx.peer_fc = false; } - } - /* else want to disable flow from peer */ - else { + } else { + /* else want to disable flow from peer */ /* if client registered data callback, just do what they want */ if (p_port->p_data_callback || p_port->p_data_co_callback) { p_port->rx.peer_fc = true; - } - /* if queue count reached credit rx max, set peer fc */ - else if (fixed_queue_length(p_port->rx.queue) >= p_port->credit_rx_max) { + } else if (fixed_queue_length(p_port->rx.queue) >= p_port->credit_rx_max) { + /* if queue count reached credit rx max, set peer fc */ p_port->rx.peer_fc = true; } } - } - /* else using TS 07.10 flow control */ - else { + } else { + /* else using TS 07.10 flow control */ /* if want to enable flow from peer */ if (enable) { /* If rfcomm suspended traffic from the peer based on the rx_queue_size */ @@ -508,19 +505,17 @@ void port_flow_control_peer(tPORT* p_port, bool enable, uint16_t count) { RFCOMM_FlowReq(p_port->rfc.p_mcb, p_port->dlci, true); } } - } - /* else want to disable flow from peer */ - else { + } else { + /* else want to disable flow from peer */ /* if client registered data callback, just do what they want */ if (p_port->p_data_callback || p_port->p_data_co_callback) { p_port->rx.peer_fc = true; RFCOMM_FlowReq(p_port->rfc.p_mcb, p_port->dlci, false); - } - /* Check the size of the rx queue. If it exceeds certain */ - /* level and flow control has not been sent to the peer do it now */ - else if (((p_port->rx.queue_size > PORT_RX_HIGH_WM) || - (fixed_queue_length(p_port->rx.queue) > PORT_RX_BUF_HIGH_WM)) && - !p_port->rx.peer_fc) { + } else if (((p_port->rx.queue_size > PORT_RX_HIGH_WM) || + (fixed_queue_length(p_port->rx.queue) > PORT_RX_BUF_HIGH_WM)) && + !p_port->rx.peer_fc) { + /* Check the size of the rx queue. If it exceeds certain */ + /* level and flow control has not been sent to the peer do it now */ log::verbose("PORT_DataInd Data reached HW. Sending FC set."); p_port->rx.peer_fc = true; diff --git a/system/stack/sdp/sdp_db.cc b/system/stack/sdp/sdp_db.cc index 9e53a9ddf4..dbb8ba7f2b 100644 --- a/system/stack/sdp/sdp_db.cc +++ b/system/stack/sdp/sdp_db.cc @@ -341,30 +341,30 @@ uint32_t SDP_CreateRecord(void) { tSDP_DB* p_db = &sdp_cb.server_db; /* First, check if there is a free record */ - if (p_db->num_records < SDP_MAX_RECORDS) { - memset(&p_db->record[p_db->num_records], 0, sizeof(tSDP_RECORD)); - - /* We will use a handle of the first unreserved handle plus last record - ** number + 1 */ - if (p_db->num_records) { - handle = p_db->record[p_db->num_records - 1].record_handle + 1; - } else { - handle = 0x10000; - } - - p_db->record[p_db->num_records].record_handle = handle; + if (p_db->num_records >= SDP_MAX_RECORDS) { + log::error("SDP_CreateRecord fail, exceed maximum records:{}", SDP_MAX_RECORDS); + return 0; + } - p_db->num_records++; - log::verbose("SDP_CreateRecord ok, num_records:{}", p_db->num_records); - /* Add the first attribute (the handle) automatically */ - UINT32_TO_BE_FIELD(buf, handle); - SDP_AddAttribute(handle, ATTR_ID_SERVICE_RECORD_HDL, UINT_DESC_TYPE, 4, buf); + memset(&p_db->record[p_db->num_records], 0, sizeof(tSDP_RECORD)); - return p_db->record[p_db->num_records - 1].record_handle; + /* We will use a handle of the first unreserved handle plus last record + ** number + 1 */ + if (p_db->num_records) { + handle = p_db->record[p_db->num_records - 1].record_handle + 1; } else { - log::error("SDP_CreateRecord fail, exceed maximum records:{}", SDP_MAX_RECORDS); + handle = 0x10000; } - return 0; + + p_db->record[p_db->num_records].record_handle = handle; + + p_db->num_records++; + log::verbose("SDP_CreateRecord ok, num_records:{}", p_db->num_records); + /* Add the first attribute (the handle) automatically */ + UINT32_TO_BE_FIELD(buf, handle); + SDP_AddAttribute(handle, ATTR_ID_SERVICE_RECORD_HDL, UINT_DESC_TYPE, 4, buf); + + return p_db->record[p_db->num_records - 1].record_handle; } /******************************************************************************* @@ -392,32 +392,34 @@ bool SDP_DeleteRecord(uint32_t handle) { sdp_cb.server_db.di_primary_handle = 0; return true; - } else { - /* Find the record in the database */ - for (xx = 0; xx < sdp_cb.server_db.num_records; xx++, p_rec++) { - if (p_rec->record_handle == handle) { - /* Found it. Shift everything up one */ - for (yy = xx; yy < sdp_cb.server_db.num_records - 1; yy++, p_rec++) { - *p_rec = *(p_rec + 1); - - /* Adjust the attribute value pointer for each attribute */ - for (zz = 0; zz < p_rec->num_attributes; zz++) { - p_rec->attribute[zz].value_ptr -= sizeof(tSDP_RECORD); - } - } + } - sdp_cb.server_db.num_records--; + /* Find the record in the database */ + for (xx = 0; xx < sdp_cb.server_db.num_records; xx++, p_rec++) { + if (p_rec->record_handle != handle) { + continue; + } - log::verbose("SDP_DeleteRecord ok, num_records:{}", sdp_cb.server_db.num_records); - /* if we're deleting the primary DI record, clear the */ - /* value in the control block */ - if (sdp_cb.server_db.di_primary_handle == handle) { - sdp_cb.server_db.di_primary_handle = 0; - } + /* Found it. Shift everything up one */ + for (yy = xx; yy < sdp_cb.server_db.num_records - 1; yy++, p_rec++) { + *p_rec = *(p_rec + 1); - return true; + /* Adjust the attribute value pointer for each attribute */ + for (zz = 0; zz < p_rec->num_attributes; zz++) { + p_rec->attribute[zz].value_ptr -= sizeof(tSDP_RECORD); } } + + sdp_cb.server_db.num_records--; + + log::verbose("SDP_DeleteRecord ok, num_records:{}", sdp_cb.server_db.num_records); + /* if we're deleting the primary DI record, clear the */ + /* value in the control block */ + if (sdp_cb.server_db.di_primary_handle == handle) { + sdp_cb.server_db.di_primary_handle = 0; + } + + return true; } return false; } diff --git a/system/stack/smp/p_256_ecc_pp.h b/system/stack/smp/p_256_ecc_pp.h index 0f3b507a92..c407530d44 100644 --- a/system/stack/smp/p_256_ecc_pp.h +++ b/system/stack/smp/p_256_ecc_pp.h @@ -51,7 +51,6 @@ typedef struct { // base point, a point on E of order r Point G; - } elliptic_curve_t; extern elliptic_curve_t curve; diff --git a/system/stack/smp/smp_act.cc b/system/stack/smp/smp_act.cc index 6de1db3ae8..8ad85378a3 100644 --- a/system/stack/smp/smp_act.cc +++ b/system/stack/smp/smp_act.cc @@ -1296,11 +1296,10 @@ void smp_check_auth_req(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { /* if failed for encryption after pairing, send callback */ if (p_cb->flags & SMP_PAIR_FLAG_ENC_AFTER_PAIR) { smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data); - } - /* if enc failed for old security information */ - /* if central device, clean up and abck to idle; peripheral device do - * nothing */ - else if (p_cb->role == HCI_ROLE_CENTRAL) { + } else if (p_cb->role == HCI_ROLE_CENTRAL) { + /* if enc failed for old security information */ + /* if central device, clean up and abck to idle; peripheral device do + * nothing */ smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data); } } diff --git a/system/stack/smp/smp_main.cc b/system/stack/smp/smp_main.cc index ead1d83028..26635cf4d8 100644 --- a/system/stack/smp/smp_main.cc +++ b/system/stack/smp/smp_main.cc @@ -329,7 +329,8 @@ static const uint8_t smp_all_table[][SMP_SM_NUM_COLS] = { /* AUTH_CMPL */ {SMP_SEND_PAIR_FAIL, SMP_PAIRING_CMPL, SMP_STATE_IDLE}, /* L2C_DISC */ - {SMP_PAIR_TERMINATE, SMP_SM_NO_ACTION, SMP_STATE_IDLE}}; + {SMP_PAIR_TERMINATE, SMP_SM_NO_ACTION, SMP_STATE_IDLE}, +}; static const uint8_t smp_central_idle_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ @@ -342,8 +343,7 @@ static const uint8_t smp_central_idle_table[][SMP_SM_NUM_COLS] = { /* AUTH_CMPL */ {SMP_PAIRING_CMPL, SMP_SM_NO_ACTION, SMP_STATE_IDLE}, /* CR_LOC_SC_OOB_DATA */ - {SMP_CREATE_PRIVATE_KEY, SMP_SM_NO_ACTION, SMP_STATE_CREATE_LOCAL_SEC_CONN_OOB_DATA} - + {SMP_CREATE_PRIVATE_KEY, SMP_SM_NO_ACTION, SMP_STATE_CREATE_LOCAL_SEC_CONN_OOB_DATA}, }; static const uint8_t smp_central_wait_for_app_response_table[][SMP_SM_NUM_COLS] = { @@ -373,7 +373,8 @@ static const uint8_t smp_central_wait_for_app_response_table[][SMP_SM_NUM_COLS] /* KEYPR_NOTIF */ {SMP_SEND_KEYPRESS_NOTIFICATION, SMP_SM_NO_ACTION, SMP_STATE_WAIT_APP_RSP}, /* SC_OOB_DATA */ - {SMP_USE_OOB_PRIVATE_KEY, SMP_SM_NO_ACTION, SMP_STATE_PUBLIC_KEY_EXCH}}; + {SMP_USE_OOB_PRIVATE_KEY, SMP_SM_NO_ACTION, SMP_STATE_PUBLIC_KEY_EXCH}, +}; static const uint8_t smp_central_pair_request_response_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ @@ -386,18 +387,21 @@ static const uint8_t smp_central_pair_request_response_table[][SMP_SM_NUM_COLS] /* KEY_READY */ {SMP_GENERATE_CONFIRM, SMP_SM_NO_ACTION, SMP_STATE_WAIT_CONFIRM} /* PUBL_KEY_EXCH_REQ */, - {SMP_CREATE_PRIVATE_KEY, SMP_SM_NO_ACTION, SMP_STATE_PUBLIC_KEY_EXCH}}; + {SMP_CREATE_PRIVATE_KEY, SMP_SM_NO_ACTION, SMP_STATE_PUBLIC_KEY_EXCH}, +}; static const uint8_t smp_central_wait_for_confirm_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ /* KEY_READY*/ /* CONFIRM ready */ - {SMP_SEND_CONFIRM, SMP_SM_NO_ACTION, SMP_STATE_CONFIRM}}; + {SMP_SEND_CONFIRM, SMP_SM_NO_ACTION, SMP_STATE_CONFIRM}, +}; static const uint8_t smp_central_confirm_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ /* CONFIRM */ - {SMP_PROC_CONFIRM, SMP_SEND_RAND, SMP_STATE_RAND}}; + {SMP_PROC_CONFIRM, SMP_SEND_RAND, SMP_STATE_RAND}, +}; static const uint8_t smp_central_rand_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ @@ -406,7 +410,8 @@ static const uint8_t smp_central_rand_table[][SMP_SM_NUM_COLS] = { /* KEY_READY */ {SMP_PROC_COMPARE, SMP_SM_NO_ACTION, SMP_STATE_RAND}, /* Compare ready */ /* ENC_REQ */ - {SMP_GENERATE_STK, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}}; + {SMP_GENERATE_STK, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}, +}; static const uint8_t smp_central_public_key_exchange_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ @@ -493,7 +498,8 @@ static const uint8_t smp_central_enc_pending_table[][SMP_SM_NUM_COLS] = { /* ENCRYPTED */ {SMP_CHECK_AUTH_REQ, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}, /* BOND_REQ */ - {SMP_KEY_DISTRIBUTE, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}}; + {SMP_KEY_DISTRIBUTE, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, +}; static const uint8_t smp_central_bond_pending_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ @@ -519,7 +525,8 @@ static const uint8_t smp_central_create_local_sec_conn_oob_data[][SMP_SM_NUM_COL /* LOC_PUBL_KEY_CRTD */ {SMP_SET_LOCAL_OOB_KEYS, SMP_SM_NO_ACTION, SMP_STATE_CREATE_LOCAL_SEC_CONN_OOB_DATA}, /* HAVE_LOC_NONCE */ - {SMP_SET_LOCAL_OOB_RAND_COMMITMENT, SMP_SM_NO_ACTION, SMP_STATE_IDLE}}; + {SMP_SET_LOCAL_OOB_RAND_COMMITMENT, SMP_SM_NO_ACTION, SMP_STATE_IDLE}, +}; /************ SMP Peripheral FSM State/Event Indirection Table **************/ static const uint8_t smp_peripheral_entry_map[][SMP_STATE_MAX] = { @@ -621,7 +628,8 @@ static const uint8_t smp_peripheral_idle_table[][SMP_SM_NUM_COLS] = { /* PAIR_REQ */ {SMP_PROC_PAIR_CMD, SMP_SEND_APP_CBACK, SMP_STATE_WAIT_APP_RSP}, /* CR_LOC_SC_OOB_DATA */ - {SMP_CREATE_PRIVATE_KEY, SMP_SM_NO_ACTION, SMP_STATE_CREATE_LOCAL_SEC_CONN_OOB_DATA}}; + {SMP_CREATE_PRIVATE_KEY, SMP_SM_NO_ACTION, SMP_STATE_CREATE_LOCAL_SEC_CONN_OOB_DATA}, +}; static const uint8_t smp_peripheral_wait_for_app_response_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ @@ -684,7 +692,8 @@ static const uint8_t smp_peripheral_wait_confirm_table[][SMP_SM_NUM_COLS] = { /* CONFIRM */ {SMP_PROC_CONFIRM, SMP_SEND_CONFIRM, SMP_STATE_CONFIRM}, /* KEY_READY*/ - {SMP_PROC_SL_KEY, SMP_SM_NO_ACTION, SMP_STATE_WAIT_CONFIRM}}; + {SMP_PROC_SL_KEY, SMP_SM_NO_ACTION, SMP_STATE_WAIT_CONFIRM}, +}; static const uint8_t smp_peripheral_confirm_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ @@ -693,14 +702,16 @@ static const uint8_t smp_peripheral_confirm_table[][SMP_SM_NUM_COLS] = { /* TK/Confirm ready */ /* KEY_READY*/ - {SMP_PROC_SL_KEY, SMP_SM_NO_ACTION, SMP_STATE_CONFIRM}}; + {SMP_PROC_SL_KEY, SMP_SM_NO_ACTION, SMP_STATE_CONFIRM}, +}; static const uint8_t smp_peripheral_rand_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ /* KEY_READY */ {SMP_PROC_COMPARE, SMP_SM_NO_ACTION, SMP_STATE_RAND}, /* compare match */ /* RAND */ - {SMP_SEND_RAND, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}}; + {SMP_SEND_RAND, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}, +}; static const uint8_t smp_peripheral_public_key_exch_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ @@ -803,7 +814,8 @@ static const uint8_t smp_peripheral_enc_pending_table[][SMP_SM_NUM_COLS] = { /* ENCRYPTED */ {SMP_CHECK_AUTH_REQ, SMP_SM_NO_ACTION, SMP_STATE_ENCRYPTION_PENDING}, /* BOND_REQ */ - {SMP_KEY_DISTRIBUTE, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}}; + {SMP_KEY_DISTRIBUTE, SMP_SM_NO_ACTION, SMP_STATE_BOND_PENDING}, +}; static const uint8_t smp_peripheral_bond_pending_table[][SMP_SM_NUM_COLS] = { /* Event Action Next State */ @@ -832,7 +844,8 @@ static const uint8_t smp_peripheral_create_local_sec_conn_oob_data[][SMP_SM_NUM_ /* LOC_PUBL_KEY_CRTD */ {SMP_SET_LOCAL_OOB_KEYS, SMP_SM_NO_ACTION, SMP_STATE_CREATE_LOCAL_SEC_CONN_OOB_DATA}, /* HAVE_LOC_NONCE */ - {SMP_SET_LOCAL_OOB_RAND_COMMITMENT, SMP_SM_NO_ACTION, SMP_STATE_IDLE}}; + {SMP_SET_LOCAL_OOB_RAND_COMMITMENT, SMP_SM_NO_ACTION, SMP_STATE_IDLE}, +}; static const tSMP_SM_TBL smp_state_table[][2] = { /* SMP_STATE_IDLE */ diff --git a/system/stack/srvc/srvc_eng_int.h b/system/stack/srvc/srvc_eng_int.h index 6f8dde3d75..ef2c938b32 100644 --- a/system/stack/srvc/srvc_eng_int.h +++ b/system/stack/srvc/srvc_eng_int.h @@ -43,7 +43,6 @@ typedef struct { uint8_t cur_srvc_id; tDIS_VALUE dis_value; - } tSRVC_CLCB; /* service engine control block */ @@ -51,7 +50,6 @@ typedef struct { tSRVC_CLCB clcb[SRVC_MAX_APPS]; /* connection link*/ tGATT_IF gatt_if; bool enabled; - } tSRVC_ENG_CB; /* Global GATT data */ diff --git a/system/stack/test/ad_parser_unittest.cc b/system/stack/test/ad_parser_unittest.cc index 2ef0ebf178..30f253b9c8 100644 --- a/system/stack/test/ad_parser_unittest.cc +++ b/system/stack/test/ad_parser_unittest.cc @@ -199,4 +199,4 @@ TEST(AdvertiseDataParserTest, GetFieldByTypeInLoop) { match_no++; } EXPECT_EQ(match_no, 3); -}
\ No newline at end of file +} diff --git a/system/stack/test/common/mock_btif_storage.h b/system/stack/test/common/mock_btif_storage.h index 3b20838756..cc7da1cf7d 100644 --- a/system/stack/test/common/mock_btif_storage.h +++ b/system/stack/test/common/mock_btif_storage.h @@ -42,4 +42,4 @@ public: void SetMockBtifStorageInterface(MockBtifStorageInterface* mock_btif_storage_interface); } // namespace manager -} // namespace bluetooth
\ No newline at end of file +} // namespace bluetooth diff --git a/system/stack/test/fuzzers/Android.bp b/system/stack/test/fuzzers/Android.bp index 3c74de632d..af2ad8623c 100644 --- a/system/stack/test/fuzzers/Android.bp +++ b/system/stack/test/fuzzers/Android.bp @@ -25,7 +25,6 @@ cc_defaults { "packages/modules/Bluetooth/system/include/", "packages/modules/Bluetooth/system/stack/include", "packages/modules/Bluetooth/system/stack/test", - "packages/modules/Bluetooth/system/types/", ], static_libs: [ "android.hardware.audio.common@5.0", @@ -61,6 +60,7 @@ cc_defaults { "libbte", "libbtif", "libbtif-core", + "libcom.android.sysprop.bluetooth.wrapped", "libexpresslog", "libflags_rust_cpp_bridge", "libg722codec", diff --git a/system/stack/test/fuzzers/a2dp/a2dpFuzzFunctions.h b/system/stack/test/fuzzers/a2dp/a2dpFuzzFunctions.h index d2c1708eb6..e056557efd 100644 --- a/system/stack/test/fuzzers/a2dp/a2dpFuzzFunctions.h +++ b/system/stack/test/fuzzers/a2dp/a2dpFuzzFunctions.h @@ -27,9 +27,9 @@ #include "fuzzers/common/commonFuzzHelpers.h" #include "fuzzers/sdp/sdpFuzzFunctions.h" #include "osi/include/allocator.h" -#include "raw_address.h" #include "stack/a2dp/a2dp_int.h" #include "stack/include/bt_uuid16.h" +#include "types/raw_address.h" #define MAX_STR_LEN 4096 diff --git a/system/stack/test/stack_a2dp_test.cc b/system/stack/test/stack_a2dp_test.cc index c78ad6285e..ee4d56ce54 100644 --- a/system/stack/test/stack_a2dp_test.cc +++ b/system/stack/test/stack_a2dp_test.cc @@ -579,7 +579,7 @@ TEST_F(StackA2dpTest, test_a2dp_codec_equals) { // Test two identical Opus codecs memset(codec_info_opus_test, 0xAB, sizeof(codec_info_opus_test)); memcpy(codec_info_opus_test, codec_info_opus, sizeof(codec_info_opus)); - ASSERT_TRUE(A2DP_VendorCodecEquals(codec_info_opus, codec_info_opus_test)); + ASSERT_TRUE(A2DP_CodecEquals(codec_info_opus, codec_info_opus_test)); // Test two identical non-A2DP codecs that are not recognized memset(codec_info_non_a2dp_test, 0xAB, sizeof(codec_info_non_a2dp_test)); @@ -627,14 +627,14 @@ TEST_F(StackA2dpTest, test_a2dp_codec_equals) { TEST_F(StackA2dpTest, test_a2dp_get_track_sample_rate) { EXPECT_EQ(A2DP_GetTrackSampleRate(codec_info_sbc), 44100); EXPECT_EQ(A2DP_GetTrackSampleRate(codec_info_aac), 44100); - ASSERT_EQ(A2DP_VendorGetTrackSampleRate(codec_info_opus), 48000); + ASSERT_EQ(A2DP_GetTrackSampleRate(codec_info_opus), 48000); EXPECT_EQ(A2DP_GetTrackSampleRate(codec_info_non_a2dp), -1); } TEST_F(StackA2dpTest, test_a2dp_get_track_channel_count) { EXPECT_EQ(A2DP_GetTrackChannelCount(codec_info_sbc), 2); EXPECT_EQ(A2DP_GetTrackChannelCount(codec_info_aac), 2); - ASSERT_EQ(A2DP_VendorGetTrackChannelCount(codec_info_opus), 2); + ASSERT_EQ(A2DP_GetTrackChannelCount(codec_info_opus), 2); EXPECT_EQ(A2DP_GetTrackChannelCount(codec_info_non_a2dp), -1); } @@ -687,7 +687,7 @@ TEST_F(StackA2dpTest, test_a2dp_get_max_bitpool_sbc) { TEST_F(StackA2dpTest, test_a2dp_get_sink_track_channel_type) { EXPECT_EQ(A2DP_GetSinkTrackChannelType(codec_info_sbc), 3); EXPECT_EQ(A2DP_GetSinkTrackChannelType(codec_info_aac), 3); - ASSERT_EQ(A2DP_VendorGetSinkTrackChannelType(codec_info_opus), 2); + ASSERT_EQ(A2DP_GetSinkTrackChannelType(codec_info_opus), 2); EXPECT_EQ(A2DP_GetSinkTrackChannelType(codec_info_non_a2dp), -1); } @@ -735,7 +735,7 @@ TEST_F(StackA2dpTest, test_a2dp_get_packet_timestamp) { memset(a2dp_data, 0xAB, sizeof(a2dp_data)); *p_ts = 0x12345678; timestamp = 0xFFFFFFFF; - ASSERT_TRUE(A2DP_VendorGetPacketTimestamp(codec_info_opus, a2dp_data, ×tamp)); + ASSERT_TRUE(A2DP_GetPacketTimestamp(codec_info_opus, a2dp_data, ×tamp)); ASSERT_EQ(timestamp, static_cast<uint32_t>(0x12345678)); memset(a2dp_data, 0xAB, sizeof(a2dp_data)); @@ -781,14 +781,14 @@ TEST_F(StackA2dpTest, test_a2dp_adjust_codec) { memset(codec_info_sbc_test, 0xAB, sizeof(codec_info_sbc_test)); memcpy(codec_info_sbc_test, codec_info_sbc, sizeof(codec_info_sbc)); EXPECT_TRUE(A2DP_AdjustCodec(codec_info_sbc_test)); - EXPECT_TRUE(memcmp(codec_info_sbc_test, codec_info_sbc, sizeof(codec_info_sbc)) == 0); + EXPECT_EQ(0, memcmp(codec_info_sbc_test, codec_info_sbc, sizeof(codec_info_sbc))); // Test updating a valid SBC codec that needs adjustment memset(codec_info_sbc_test, 0xAB, sizeof(codec_info_sbc_test)); memcpy(codec_info_sbc_test, codec_info_sbc, sizeof(codec_info_sbc)); codec_info_sbc_test[6] = 54; // A2DP_SBC_MAX_BITPOOL + 1 EXPECT_TRUE(A2DP_AdjustCodec(codec_info_sbc_test)); - EXPECT_TRUE(memcmp(codec_info_sbc_test, codec_info_sbc, sizeof(codec_info_sbc)) == 0); + EXPECT_EQ(0, memcmp(codec_info_sbc_test, codec_info_sbc, sizeof(codec_info_sbc))); // Test updating an invalid SBC codec memset(codec_info_sbc_test, 0xAB, sizeof(codec_info_sbc_test)); @@ -800,7 +800,7 @@ TEST_F(StackA2dpTest, test_a2dp_adjust_codec) { memset(codec_info_aac_test, 0xAB, sizeof(codec_info_aac_test)); memcpy(codec_info_aac_test, codec_info_aac, sizeof(codec_info_aac)); EXPECT_TRUE(A2DP_AdjustCodec(codec_info_aac_test)); - EXPECT_TRUE(memcmp(codec_info_aac_test, codec_info_aac, sizeof(codec_info_aac)) == 0); + EXPECT_EQ(0, memcmp(codec_info_aac_test, codec_info_aac, sizeof(codec_info_aac))); // Test updating a non-A2DP codec that is not recognized memset(codec_info_non_a2dp_test, 0xAB, sizeof(codec_info_non_a2dp_test)); @@ -818,10 +818,9 @@ TEST_F(StackA2dpTest, test_a2dp_source_codec_index) { EXPECT_EQ(A2DP_SourceCodecIndex(codec_info_aac_capability), BTAV_A2DP_CODEC_INDEX_SOURCE_AAC); EXPECT_EQ(A2DP_SourceCodecIndex(codec_info_aac_sink_capability), BTAV_A2DP_CODEC_INDEX_SOURCE_AAC); - ASSERT_EQ(A2DP_VendorSourceCodecIndex(codec_info_opus), BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS); - ASSERT_EQ(A2DP_VendorSourceCodecIndex(codec_info_opus_capability), - BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS); - ASSERT_EQ(A2DP_VendorSourceCodecIndex(codec_info_opus_sink_capability), + ASSERT_EQ(A2DP_SourceCodecIndex(codec_info_opus), BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS); + ASSERT_EQ(A2DP_SourceCodecIndex(codec_info_opus_capability), BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS); + ASSERT_EQ(A2DP_SourceCodecIndex(codec_info_opus_sink_capability), BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS); EXPECT_EQ(A2DP_SourceCodecIndex(codec_info_non_a2dp), BTAV_A2DP_CODEC_INDEX_MAX); } diff --git a/system/test/headless/Android.bp b/system/test/headless/Android.bp index af86f9f664..ec61ea012f 100644 --- a/system/test/headless/Android.bp +++ b/system/test/headless/Android.bp @@ -106,6 +106,7 @@ cc_binary { "libbtif", "libbtif-core", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "libflags_rust_cpp_bridge", "libflatbuffers-cpp", diff --git a/system/test/headless/utils/power_mode_client.h b/system/test/headless/utils/power_mode_client.h index 994aeea21d..1f66c63419 100644 --- a/system/test/headless/utils/power_mode_client.h +++ b/system/test/headless/utils/power_mode_client.h @@ -114,7 +114,6 @@ 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 diff --git a/system/test/mock/mock_common_os_utils.h b/system/test/mock/mock_common_os_utils.h index 4c8d345b9f..ac620cdb58 100644 --- a/system/test/mock/mock_common_os_utils.h +++ b/system/test/mock/mock_common_os_utils.h @@ -50,4 +50,4 @@ extern struct is_bluetooth_uid is_bluetooth_uid; } // namespace mock } // namespace test -// END mockcify generation
\ No newline at end of file +// END mockcify generation diff --git a/system/test/mock/mock_osi_mutex.h b/system/test/mock/mock_osi_mutex.h index 45144253ec..fcee6fe42d 100644 --- a/system/test/mock/mock_osi_mutex.h +++ b/system/test/mock/mock_osi_mutex.h @@ -56,4 +56,4 @@ extern struct mutex_global_unlock mutex_global_unlock; } // namespace mock } // namespace test -// END mockcify generation
\ No newline at end of file +// END mockcify generation diff --git a/system/test/suite/Android.bp b/system/test/suite/Android.bp index d495cc034d..98307ada71 100644 --- a/system/test/suite/Android.bp +++ b/system/test/suite/Android.bp @@ -19,7 +19,6 @@ cc_defaults { "packages/modules/Bluetooth/system/bta/sys", "packages/modules/Bluetooth/system/btif/avrcp", "packages/modules/Bluetooth/system/btif/co", - "packages/modules/Bluetooth/system/device/include", "packages/modules/Bluetooth/system/embdrv/sbc/decoder/include", "packages/modules/Bluetooth/system/embdrv/sbc/encoder/include", "packages/modules/Bluetooth/system/gd", diff --git a/system/types/Android.bp b/system/types/Android.bp index 4bff11709b..4201bafca4 100644 --- a/system/types/Android.bp +++ b/system/types/Android.bp @@ -58,6 +58,7 @@ cc_test { "libbase", "libbluetooth-types", "libbluetooth_log", + "libcom.android.sysprop.bluetooth.wrapped", "libosi", // strlcpy ], test_suites: ["general-tests"], diff --git a/system/types/remote_version_type.h b/system/types/remote_version_type.h index 1585dabf34..307a9ef102 100644 --- a/system/types/remote_version_type.h +++ b/system/types/remote_version_type.h @@ -35,4 +35,4 @@ struct tREMOTE_VERSION_INFO { } }; -using remote_version_info = tREMOTE_VERSION_INFO;
\ No newline at end of file +using remote_version_info = tREMOTE_VERSION_INFO; diff --git a/system/types/test/ble_address_with_type_unittest.cc b/system/types/test/ble_address_with_type_unittest.cc index 2940947a91..341875b3cc 100644 --- a/system/types/test/ble_address_with_type_unittest.cc +++ b/system/types/test/ble_address_with_type_unittest.cc @@ -23,19 +23,19 @@ TEST(BleAddressWithTypeTest, to_ble_addr_type) { for (unsigned i = 0; i < 0xff + 1; i++) { switch (to_ble_addr_type((uint8_t)i)) { case BLE_ADDR_PUBLIC: - ASSERT_TRUE(i == 0); + ASSERT_EQ(0u, i); break; case BLE_ADDR_RANDOM: - ASSERT_TRUE(i == 1); + ASSERT_EQ(1u, i); break; case BLE_ADDR_PUBLIC_ID: - ASSERT_TRUE(i == 2); + ASSERT_EQ(2u, i); break; case BLE_ADDR_RANDOM_ID: - ASSERT_TRUE(i == 3); + ASSERT_EQ(3u, i); break; case BLE_ADDR_ANONYMOUS: - ASSERT_TRUE(i == 0xff); + ASSERT_EQ(0xffu, i); break; default: ASSERT_TRUE(i > 3 && i != 0xff); diff --git a/system/types/test/bluetooth/uuid_unittest.cc b/system/types/test/bluetooth/uuid_unittest.cc index 6e9e40f965..41ec8696ef 100644 --- a/system/types/test/bluetooth/uuid_unittest.cc +++ b/system/types/test/bluetooth/uuid_unittest.cc @@ -16,7 +16,8 @@ * ******************************************************************************/ -#include <bluetooth/uuid.h> +#include "types/bluetooth/uuid.h" + #include <gtest/gtest.h> using bluetooth::Uuid; @@ -72,17 +73,17 @@ TEST(UuidTest, From16Bit) { const uint8_t u2[] = {0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; Uuid uuid = Uuid::From16Bit(0x0001); - EXPECT_TRUE(memcmp(&uuid, u2, sizeof(u2)) == 0); + EXPECT_EQ(0, memcmp(&uuid, u2, sizeof(u2))); const uint8_t u3[] = {0x00, 0x00, 0x55, 0x3e, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; uuid = Uuid::From16Bit(0x553e); - EXPECT_TRUE(memcmp(&uuid, u3, sizeof(u3)) == 0); + EXPECT_EQ(0, memcmp(&uuid, u3, sizeof(u3))); const uint8_t u4[] = {0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; uuid = Uuid::From16Bit(0xffff); - EXPECT_TRUE(memcmp(&uuid, u4, sizeof(u4)) == 0); + EXPECT_EQ(0, memcmp(&uuid, u4, sizeof(u4))); } TEST(UuidTest, From32Bit) { @@ -91,17 +92,17 @@ TEST(UuidTest, From32Bit) { const uint8_t u2[] = {0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; Uuid uuid = Uuid::From32Bit(0x00000001); - EXPECT_TRUE(memcmp(&uuid, u2, sizeof(u2)) == 0); + EXPECT_EQ(0, memcmp(&uuid, u2, sizeof(u2))); const uint8_t u3[] = {0x33, 0x44, 0x55, 0x3e, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; uuid = Uuid::From32Bit(0x3344553e); - EXPECT_TRUE(memcmp(&uuid, u3, sizeof(u3)) == 0); + EXPECT_EQ(0, memcmp(&uuid, u3, sizeof(u3))); const uint8_t u4[] = {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; uuid = Uuid::From32Bit(0xffffffff); - EXPECT_TRUE(memcmp(&uuid, u4, sizeof(u4)) == 0); + EXPECT_EQ(0, memcmp(&uuid, u4, sizeof(u4))); } TEST(UuidTest, ToString) { @@ -125,21 +126,21 @@ TEST(BtifStorageTest, test_string_to_uuid) { bool is_valid = false; Uuid uuid = Uuid::FromString("e39c6285-867f-4b1d-9db0-35fbd9aebf22", &is_valid); EXPECT_TRUE(is_valid); - EXPECT_TRUE(memcmp(&uuid, u1, sizeof(u1)) == 0); + EXPECT_EQ(0, memcmp(&uuid, u1, sizeof(u1))); const uint8_t u2[] = {0x00, 0x00, 0x1a, 0xe8, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; is_valid = false; uuid = Uuid::FromString("1Ae8", &is_valid); EXPECT_TRUE(is_valid); - EXPECT_TRUE(memcmp(&uuid, u2, sizeof(u2)) == 0); + EXPECT_EQ(0, memcmp(&uuid, u2, sizeof(u2))); const uint8_t u3[] = {0x12, 0x34, 0x11, 0x28, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5f, 0x9b, 0x34, 0xfb}; is_valid = false; uuid = Uuid::FromString("12341128", &is_valid); EXPECT_TRUE(is_valid); - EXPECT_TRUE(memcmp(&uuid, u3, sizeof(u3)) == 0); + EXPECT_EQ(0, memcmp(&uuid, u3, sizeof(u3))); } TEST(BtifStorageTest, test_string_to_uuid_invalid) { diff --git a/system/types/test/raw_address_unittest.cc b/system/types/test/raw_address_unittest.cc index 247b55c60a..2fa887b896 100644 --- a/system/types/test/raw_address_unittest.cc +++ b/system/types/test/raw_address_unittest.cc @@ -16,7 +16,7 @@ * ******************************************************************************/ -#include "raw_address.h" +#include "types/raw_address.h" #include <gtest/gtest.h> diff --git a/tools/rootcanal/desktop/test_environment.cc b/tools/rootcanal/desktop/test_environment.cc index 91eae8a3e5..f556b84c4e 100644 --- a/tools/rootcanal/desktop/test_environment.cc +++ b/tools/rootcanal/desktop/test_environment.cc @@ -104,7 +104,7 @@ void TestEnvironment::SetUpHciServer( AsyncDataChannelServer* server) { // AddHciConnection needs to be executed in task thread to // prevent data races on test model. - async_manager_.ExecAsync(socket_user_id_, std::chrono::milliseconds(0), [=]() { + async_manager_.ExecAsync(socket_user_id_, std::chrono::milliseconds(0), [=, this]() { auto transport = HciSocketTransport::Create(socket); if (enable_hci_sniffer_) { transport = HciSniffer::Create(transport); diff --git a/tools/rootcanal/lib/hci/pcap_filter.cc b/tools/rootcanal/lib/hci/pcap_filter.cc index ca14ef03c7..abd20ed7fc 100644 --- a/tools/rootcanal/lib/hci/pcap_filter.cc +++ b/tools/rootcanal/lib/hci/pcap_filter.cc @@ -97,9 +97,9 @@ std::vector<uint8_t> PcapFilter::FilterHciEvent(std::vector<uint8_t> const& pack auto le_meta_event = LeMetaEventView::Create(event); ASSERT(le_meta_event.IsValid()); switch (le_meta_event.GetSubeventCode()) { - case SubeventCode::ADVERTISING_REPORT: + case SubeventCode::LE_ADVERTISING_REPORT: return FilterLeAdvertisingReport(le_meta_event); - case SubeventCode::EXTENDED_ADVERTISING_REPORT: + case SubeventCode::LE_EXTENDED_ADVERTISING_REPORT: return FilterLeExtendedAdvertisingReport(le_meta_event); default: break; diff --git a/tools/rootcanal/model/controller/controller_properties.cc b/tools/rootcanal/model/controller/controller_properties.cc index 4ee868b159..26718a9747 100644 --- a/tools/rootcanal/model/controller/controller_properties.cc +++ b/tools/rootcanal/model/controller/controller_properties.cc @@ -259,12 +259,13 @@ static std::array<uint8_t, 64> SupportedCommands() { // TESTING OpCodeIndex::READ_LOOPBACK_MODE, OpCodeIndex::WRITE_LOOPBACK_MODE, - OpCodeIndex::ENABLE_DEVICE_UNDER_TEST_MODE, OpCodeIndex::WRITE_SIMPLE_PAIRING_DEBUG_MODE, + OpCodeIndex::ENABLE_IMPLEMENTATION_UNDER_TEST_MODE, + OpCodeIndex::WRITE_SIMPLE_PAIRING_DEBUG_MODE, OpCodeIndex::WRITE_SECURE_CONNECTIONS_TEST_MODE, // LE_CONTROLLER OpCodeIndex::LE_SET_EVENT_MASK, OpCodeIndex::LE_READ_BUFFER_SIZE_V1, - OpCodeIndex::LE_READ_LOCAL_SUPPORTED_FEATURES, OpCodeIndex::LE_SET_RANDOM_ADDRESS, + OpCodeIndex::LE_READ_LOCAL_SUPPORTED_FEATURES_PAGE_0, OpCodeIndex::LE_SET_RANDOM_ADDRESS, OpCodeIndex::LE_SET_ADVERTISING_PARAMETERS, OpCodeIndex::LE_READ_ADVERTISING_PHYSICAL_CHANNEL_TX_POWER, OpCodeIndex::LE_SET_ADVERTISING_DATA, OpCodeIndex::LE_SET_SCAN_RESPONSE_DATA, @@ -275,8 +276,9 @@ static std::array<uint8_t, 64> SupportedCommands() { OpCodeIndex::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST, OpCodeIndex::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST, OpCodeIndex::LE_CONNECTION_UPDATE, OpCodeIndex::LE_SET_HOST_CHANNEL_CLASSIFICATION, OpCodeIndex::LE_READ_CHANNEL_MAP, - OpCodeIndex::LE_READ_REMOTE_FEATURES, OpCodeIndex::LE_ENCRYPT, OpCodeIndex::LE_RAND, - OpCodeIndex::LE_START_ENCRYPTION, OpCodeIndex::LE_LONG_TERM_KEY_REQUEST_REPLY, + OpCodeIndex::LE_READ_REMOTE_FEATURES_PAGE_0, OpCodeIndex::LE_ENCRYPT, + OpCodeIndex::LE_RAND, OpCodeIndex::LE_START_ENCRYPTION, + OpCodeIndex::LE_LONG_TERM_KEY_REQUEST_REPLY, OpCodeIndex::LE_LONG_TERM_KEY_REQUEST_NEGATIVE_REPLY, OpCodeIndex::LE_READ_SUPPORTED_STATES, OpCodeIndex::LE_RECEIVER_TEST_V1, OpCodeIndex::LE_TRANSMITTER_TEST_V1, OpCodeIndex::LE_TEST_END, @@ -298,18 +300,18 @@ static std::array<uint8_t, 64> SupportedCommands() { // OpCodeIndex::LE_RECEIVER_TEST_V2, // OpCodeIndex::LE_TRANSMITTER_TEST_V2, OpCodeIndex::LE_SET_ADVERTISING_SET_RANDOM_ADDRESS, - OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, + OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_PARAMETERS_V1, OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_DATA, OpCodeIndex::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_ENABLE, OpCodeIndex::LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH, OpCodeIndex::LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS, OpCodeIndex::LE_REMOVE_ADVERTISING_SET, OpCodeIndex::LE_CLEAR_ADVERTISING_SETS, - OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_PARAMETERS, + OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_PARAMETERS_V1, OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_DATA, OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_ENABLE, OpCodeIndex::LE_SET_EXTENDED_SCAN_PARAMETERS, OpCodeIndex::LE_SET_EXTENDED_SCAN_ENABLE, - OpCodeIndex::LE_EXTENDED_CREATE_CONNECTION, + OpCodeIndex::LE_EXTENDED_CREATE_CONNECTION_V1, OpCodeIndex::LE_PERIODIC_ADVERTISING_CREATE_SYNC, OpCodeIndex::LE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, OpCodeIndex::LE_PERIODIC_ADVERTISING_TERMINATE_SYNC, @@ -353,7 +355,7 @@ static std::array<uint8_t, 64> SupportedCommands() { // OpCodeIndex::LE_ISO_RECEIVE_TEST, // OpCodeIndex::LE_ISO_READ_TEST_COUNTERS, // OpCodeIndex::LE_ISO_TEST_END, - OpCodeIndex::LE_SET_HOST_FEATURE, + OpCodeIndex::LE_SET_HOST_FEATURE_V1, // OpCodeIndex::LE_READ_ISO_LINK_QUALITY, // OpCodeIndex::LE_ENHANCED_READ_TRANSMIT_POWER_LEVEL, // OpCodeIndex::LE_READ_REMOTE_TRANSMIT_POWER_LEVEL, @@ -984,7 +986,7 @@ bool ControllerProperties::CheckSupportedCommands() const { // C94: Mandatory if the LE Create Connection or LE Extended Create Connection // command is supported, otherwise excluded. auto c94 = mandatory_or_excluded(SupportsCommand(OpCodeIndex::LE_CREATE_CONNECTION) || - SupportsCommand(OpCodeIndex::LE_EXTENDED_CREATE_CONNECTION)); + SupportsCommand(OpCodeIndex::LE_EXTENDED_CREATE_CONNECTION_V1)); // C95: Mandatory if the LE Request Peer SCA command is supported, otherwise // excluded. // @@ -1235,7 +1237,7 @@ bool ControllerProperties::CheckSupportedCommands() const { check_command_(DELETE_RESERVED_LT_ADDR, c201, excluded); check_command_(DELETE_STORED_LINK_KEY, c121, excluded); check_command_(DISCONNECT, mandatory, c3); - check_command_(ENABLE_DEVICE_UNDER_TEST_MODE, c123, excluded); + check_command_(ENABLE_IMPLEMENTATION_UNDER_TEST_MODE, c123, excluded); // Table 3.1: Alphabetical list of commands and events (Sheet 5 of 49) check_command_(ENHANCED_ACCEPT_SYNCHRONOUS_CONNECTION, c135, excluded); check_command_(ENHANCED_FLUSH, mandatory, excluded); @@ -1280,7 +1282,7 @@ bool ControllerProperties::CheckSupportedCommands() const { check_command_(LE_ENCRYPT, excluded, c4); // Table 3.1: Alphabetical list of commands and events (Sheet 12 of 49) check_command_(LE_ENHANCED_READ_TRANSMIT_POWER_LEVEL, excluded, c51); - check_command_(LE_EXTENDED_CREATE_CONNECTION, excluded, c20); + check_command_(LE_EXTENDED_CREATE_CONNECTION_V1, excluded, c20); check_command_(LE_GENERATE_DHKEY_V1, excluded, c99); check_command_(LE_GENERATE_DHKEY_V2, excluded, optional); check_command_(LE_ISO_READ_TEST_COUNTERS, excluded, c46); @@ -1309,14 +1311,14 @@ bool ControllerProperties::CheckSupportedCommands() const { check_command_(LE_READ_ISO_TX_SYNC, excluded, c45); check_command_(LE_READ_LOCAL_RESOLVABLE_ADDRESS, excluded, c10); // Table 3.1: Alphabetical list of commands and events (Sheet 16 of 49) - check_command_(LE_READ_LOCAL_SUPPORTED_FEATURES, excluded, mandatory); + check_command_(LE_READ_LOCAL_SUPPORTED_FEATURES_PAGE_0, excluded, mandatory); check_command_(LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH, excluded, c17); check_command_(LE_READ_MAXIMUM_DATA_LENGTH, excluded, c8); check_command_(LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS, excluded, c17); check_command_(LE_READ_PEER_RESOLVABLE_ADDRESS, excluded, c10); check_command_(LE_READ_PERIODIC_ADVERTISER_LIST_SIZE, excluded, c21); check_command_(LE_READ_PHY, excluded, c11); - check_command_(LE_READ_REMOTE_FEATURES, excluded, c3); + check_command_(LE_READ_REMOTE_FEATURES_PAGE_0, excluded, c3); // Table 3.1: Alphabetical list of commands and events (Sheet 17 of 49) check_command_(LE_READ_REMOTE_TRANSMIT_POWER_LEVEL, excluded, c51); check_command_(LE_READ_RESOLVING_LIST_SIZE, excluded, c9); @@ -1361,18 +1363,18 @@ bool ControllerProperties::CheckSupportedCommands() const { check_command_(LE_SET_EVENT_MASK, excluded, mandatory); check_command_(LE_SET_EXTENDED_ADVERTISING_DATA, excluded, c17); check_command_(LE_SET_EXTENDED_ADVERTISING_ENABLE, excluded, c17); - check_command_(LE_SET_EXTENDED_ADVERTISING_PARAMETERS, excluded, c17); + check_command_(LE_SET_EXTENDED_ADVERTISING_PARAMETERS_V1, excluded, c17); check_command_(LE_SET_EXTENDED_SCAN_ENABLE, excluded, c19); // Table 3.1: Alphabetical list of commands and events (Sheet 22 of 49) check_command_(LE_SET_EXTENDED_SCAN_PARAMETERS, excluded, c19); check_command_(LE_SET_EXTENDED_SCAN_RESPONSE_DATA, excluded, c17); check_command_(LE_SET_HOST_CHANNEL_CLASSIFICATION, excluded, c36); - check_command_(LE_SET_HOST_FEATURE, excluded, c49); + check_command_(LE_SET_HOST_FEATURE_V1, excluded, c49); check_command_(LE_SET_PATH_LOSS_REPORTING_ENABLE, excluded, c52); check_command_(LE_SET_PATH_LOSS_REPORTING_PARAMETERS, excluded, c52); check_command_(LE_SET_PERIODIC_ADVERTISING_DATA, excluded, c18); check_command_(LE_SET_PERIODIC_ADVERTISING_ENABLE, excluded, c18); - check_command_(LE_SET_PERIODIC_ADVERTISING_PARAMETERS, excluded, c18); + check_command_(LE_SET_PERIODIC_ADVERTISING_PARAMETERS_V1, excluded, c18); // Table 3.1: Alphabetical list of commands and events (Sheet 23 of 49) check_command_(LE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE, excluded, c32); check_command_(LE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMETERS, excluded, c35); @@ -1593,7 +1595,7 @@ ControllerProperties::ControllerProperties() // Commands enabled by the LE Extended Advertising feature bit. static std::vector<OpCodeIndex> le_extended_advertising_commands_ = { OpCodeIndex::LE_CLEAR_ADVERTISING_SETS, - OpCodeIndex::LE_EXTENDED_CREATE_CONNECTION, + OpCodeIndex::LE_EXTENDED_CREATE_CONNECTION_V1, OpCodeIndex::LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH, OpCodeIndex::LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS, OpCodeIndex::LE_RECEIVER_TEST_V2, @@ -1602,7 +1604,7 @@ static std::vector<OpCodeIndex> le_extended_advertising_commands_ = { OpCodeIndex::LE_SET_DATA_RELATED_ADDRESS_CHANGES, OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_DATA, OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_ENABLE, - OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, + OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_PARAMETERS_V1, OpCodeIndex::LE_SET_EXTENDED_SCAN_ENABLE, OpCodeIndex::LE_SET_EXTENDED_SCAN_PARAMETERS, OpCodeIndex::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, @@ -1621,7 +1623,7 @@ static std::vector<OpCodeIndex> le_periodic_advertising_commands_ = { OpCodeIndex::LE_SET_DATA_RELATED_ADDRESS_CHANGES, OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_DATA, OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_ENABLE, - OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_PARAMETERS, + OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_PARAMETERS_V1, }; // Commands enabled by the LL Privacy feature bit. diff --git a/tools/rootcanal/model/controller/dual_mode_controller.cc b/tools/rootcanal/model/controller/dual_mode_controller.cc index 5563d8319d..15f788b438 100644 --- a/tools/rootcanal/model/controller/dual_mode_controller.cc +++ b/tools/rootcanal/model/controller/dual_mode_controller.cc @@ -1725,8 +1725,8 @@ void DualModeController::LeRequestPeerSca(CommandView command) { } } -void DualModeController::LeSetHostFeature(CommandView command) { - auto command_view = bluetooth::hci::LeSetHostFeatureView::Create(command); +void DualModeController::LeSetHostFeatureV1(CommandView command) { + auto command_view = bluetooth::hci::LeSetHostFeatureV1View::Create(command); CHECK_PACKET_VIEW(command_view); uint8_t bit_number = static_cast<uint8_t>(command_view.GetBitNumber()); uint8_t bit_value = static_cast<uint8_t>(command_view.GetBitValue()); @@ -1736,7 +1736,8 @@ void DualModeController::LeSetHostFeature(CommandView command) { DEBUG(id_, " bit_value={}", bit_value); ErrorCode status = link_layer_controller_.LeSetHostFeature(bit_number, bit_value); - send_event_(bluetooth::hci::LeSetHostFeatureCompleteBuilder::Create(kNumCommandPackets, status)); + send_event_( + bluetooth::hci::LeSetHostFeatureV1CompleteBuilder::Create(kNumCommandPackets, status)); } void DualModeController::LeReadBufferSizeV1(CommandView command) { @@ -1796,14 +1797,14 @@ void DualModeController::LeSetResolvablePrivateAddressTimeout(CommandView comman kNumCommandPackets, status)); } -void DualModeController::LeReadLocalSupportedFeatures(CommandView command) { - auto command_view = bluetooth::hci::LeReadLocalSupportedFeaturesView::Create(command); +void DualModeController::LeReadLocalSupportedFeaturesPage0(CommandView command) { + auto command_view = bluetooth::hci::LeReadLocalSupportedFeaturesPage0View::Create(command); CHECK_PACKET_VIEW(command_view); - DEBUG(id_, "<< LE Read Local Supported Features"); + DEBUG(id_, "<< LE Read Local Supported Features Page 0"); uint64_t le_features = link_layer_controller_.GetLeSupportedFeatures(); - send_event_(bluetooth::hci::LeReadLocalSupportedFeaturesCompleteBuilder::Create( + send_event_(bluetooth::hci::LeReadLocalSupportedFeaturesPage0CompleteBuilder::Create( kNumCommandPackets, ErrorCode::SUCCESS, le_features)); } @@ -2300,17 +2301,17 @@ void DualModeController::LeRemoveDeviceFromResolvingList(CommandView command) { kNumCommandPackets, status)); } -void DualModeController::LeSetPeriodicAdvertisingParameters(CommandView command) { - auto command_view = bluetooth::hci::LeSetPeriodicAdvertisingParametersView::Create(command); +void DualModeController::LeSetPeriodicAdvertisingParametersV1(CommandView command) { + auto command_view = bluetooth::hci::LeSetPeriodicAdvertisingParametersV1View::Create(command); CHECK_PACKET_VIEW(command_view); - DEBUG(id_, "<< LE Set Periodic Advertising Parameters"); + DEBUG(id_, "<< LE Set Periodic Advertising Parameters V1"); DEBUG(id_, " advertising_handle={}", command_view.GetAdvertisingHandle()); ErrorCode status = link_layer_controller_.LeSetPeriodicAdvertisingParameters( command_view.GetAdvertisingHandle(), command_view.GetPeriodicAdvertisingIntervalMin(), command_view.GetPeriodicAdvertisingIntervalMax(), command_view.GetIncludeTxPower()); - send_event_(bluetooth::hci::LeSetPeriodicAdvertisingParametersCompleteBuilder::Create( + send_event_(bluetooth::hci::LeSetPeriodicAdvertisingParametersV1CompleteBuilder::Create( kNumCommandPackets, status)); } @@ -2464,11 +2465,11 @@ void DualModeController::LeSetExtendedScanEnable(CommandView command) { status)); } -void DualModeController::LeExtendedCreateConnection(CommandView command) { - auto command_view = bluetooth::hci::LeExtendedCreateConnectionView::Create(command); +void DualModeController::LeExtendedCreateConnectionV1(CommandView command) { + auto command_view = bluetooth::hci::LeExtendedCreateConnectionV1View::Create(command); CHECK_PACKET_VIEW(command_view); - DEBUG(id_, "<< LE Extended Create Connection"); + DEBUG(id_, "<< LE Extended Create Connection V1"); DEBUG(id_, " peer_address={}", command_view.GetPeerAddress()); DEBUG(id_, " peer_address_type={}", bluetooth::hci::PeerAddressTypeText(command_view.GetPeerAddressType())); @@ -2493,8 +2494,8 @@ void DualModeController::LeExtendedCreateConnection(CommandView command) { peer_address_type, }, command_view.GetInitiatingPhys(), command_view.GetInitiatingPhyParameters()); - send_event_(bluetooth::hci::LeExtendedCreateConnectionStatusBuilder::Create(status, - kNumCommandPackets)); + send_event_(bluetooth::hci::LeExtendedCreateConnectionV1StatusBuilder::Create( + status, kNumCommandPackets)); } void DualModeController::LeSetPrivacyMode(CommandView command) { @@ -2513,19 +2514,19 @@ void DualModeController::LeSetPrivacyMode(CommandView command) { send_event_(bluetooth::hci::LeSetPrivacyModeCompleteBuilder::Create(kNumCommandPackets, status)); } -void DualModeController::LeReadRemoteFeatures(CommandView command) { - auto command_view = bluetooth::hci::LeReadRemoteFeaturesView::Create(command); +void DualModeController::LeReadRemoteFeaturesPage0(CommandView command) { + auto command_view = bluetooth::hci::LeReadRemoteFeaturesPage0View::Create(command); CHECK_PACKET_VIEW(command_view); uint16_t handle = command_view.GetConnectionHandle(); - DEBUG(id_, "<< LE Read Remote Features"); + DEBUG(id_, "<< LE Read Remote Features Page 0"); DEBUG(id_, " connection_handle=0x{:x}", handle); - auto status = link_layer_controller_.SendCommandToRemoteByHandle(OpCode::LE_READ_REMOTE_FEATURES, - command_view.bytes(), handle); + auto status = link_layer_controller_.SendCommandToRemoteByHandle( + OpCode::LE_READ_REMOTE_FEATURES_PAGE_0, command_view.bytes(), handle); - send_event_( - bluetooth::hci::LeReadRemoteFeaturesStatusBuilder::Create(status, kNumCommandPackets)); + send_event_(bluetooth::hci::LeReadRemoteFeaturesPage0StatusBuilder::Create(status, + kNumCommandPackets)); } void DualModeController::LeEncrypt(CommandView command) { @@ -3079,11 +3080,11 @@ void DualModeController::LeSetAdvertisingSetRandomAddress(CommandView command) { kNumCommandPackets, status)); } -void DualModeController::LeSetExtendedAdvertisingParameters(CommandView command) { - auto command_view = bluetooth::hci::LeSetExtendedAdvertisingParametersView::Create(command); +void DualModeController::LeSetExtendedAdvertisingParametersV1(CommandView command) { + auto command_view = bluetooth::hci::LeSetExtendedAdvertisingParametersV1View::Create(command); CHECK_PACKET_VIEW(command_view); - DEBUG(id_, "<< LE Set Extended Advertising Parameters"); + DEBUG(id_, "<< LE Set Extended Advertising Parameters V1"); DEBUG(id_, " advertising_handle={}", command_view.GetAdvertisingHandle()); ErrorCode status = link_layer_controller_.LeSetExtendedAdvertisingParameters( @@ -3098,7 +3099,7 @@ void DualModeController::LeSetExtendedAdvertisingParameters(CommandView command) command_view.GetScanRequestNotificationEnable() == Enable::ENABLED); // The selected TX power is always the requested TX power // at the moment. - send_event_(bluetooth::hci::LeSetExtendedAdvertisingParametersCompleteBuilder::Create( + send_event_(bluetooth::hci::LeSetExtendedAdvertisingParametersV1CompleteBuilder::Create( kNumCommandPackets, status, command_view.GetAdvertisingTxPower())); } @@ -3508,7 +3509,8 @@ const std::unordered_map<OpCode, OpCodeIndex> DualModeController::hci_command_op // TESTING {OpCode::READ_LOOPBACK_MODE, OpCodeIndex::READ_LOOPBACK_MODE}, {OpCode::WRITE_LOOPBACK_MODE, OpCodeIndex::WRITE_LOOPBACK_MODE}, - {OpCode::ENABLE_DEVICE_UNDER_TEST_MODE, OpCodeIndex::ENABLE_DEVICE_UNDER_TEST_MODE}, + {OpCode::ENABLE_IMPLEMENTATION_UNDER_TEST_MODE, + OpCodeIndex::ENABLE_IMPLEMENTATION_UNDER_TEST_MODE}, {OpCode::WRITE_SIMPLE_PAIRING_DEBUG_MODE, OpCodeIndex::WRITE_SIMPLE_PAIRING_DEBUG_MODE}, {OpCode::WRITE_SECURE_CONNECTIONS_TEST_MODE, OpCodeIndex::WRITE_SECURE_CONNECTIONS_TEST_MODE}, @@ -3516,7 +3518,8 @@ const std::unordered_map<OpCode, OpCodeIndex> DualModeController::hci_command_op // LE_CONTROLLER {OpCode::LE_SET_EVENT_MASK, OpCodeIndex::LE_SET_EVENT_MASK}, {OpCode::LE_READ_BUFFER_SIZE_V1, OpCodeIndex::LE_READ_BUFFER_SIZE_V1}, - {OpCode::LE_READ_LOCAL_SUPPORTED_FEATURES, OpCodeIndex::LE_READ_LOCAL_SUPPORTED_FEATURES}, + {OpCode::LE_READ_LOCAL_SUPPORTED_FEATURES_PAGE_0, + OpCodeIndex::LE_READ_LOCAL_SUPPORTED_FEATURES_PAGE_0}, {OpCode::LE_SET_RANDOM_ADDRESS, OpCodeIndex::LE_SET_RANDOM_ADDRESS}, {OpCode::LE_SET_ADVERTISING_PARAMETERS, OpCodeIndex::LE_SET_ADVERTISING_PARAMETERS}, {OpCode::LE_READ_ADVERTISING_PHYSICAL_CHANNEL_TX_POWER, @@ -3538,7 +3541,7 @@ const std::unordered_map<OpCode, OpCodeIndex> DualModeController::hci_command_op {OpCode::LE_SET_HOST_CHANNEL_CLASSIFICATION, OpCodeIndex::LE_SET_HOST_CHANNEL_CLASSIFICATION}, {OpCode::LE_READ_CHANNEL_MAP, OpCodeIndex::LE_READ_CHANNEL_MAP}, - {OpCode::LE_READ_REMOTE_FEATURES, OpCodeIndex::LE_READ_REMOTE_FEATURES}, + {OpCode::LE_READ_REMOTE_FEATURES_PAGE_0, OpCodeIndex::LE_READ_REMOTE_FEATURES_PAGE_0}, {OpCode::LE_ENCRYPT, OpCodeIndex::LE_ENCRYPT}, {OpCode::LE_RAND, OpCodeIndex::LE_RAND}, {OpCode::LE_START_ENCRYPTION, OpCodeIndex::LE_START_ENCRYPTION}, @@ -3578,8 +3581,8 @@ const std::unordered_map<OpCode, OpCodeIndex> DualModeController::hci_command_op {OpCode::LE_TRANSMITTER_TEST_V2, OpCodeIndex::LE_TRANSMITTER_TEST_V2}, {OpCode::LE_SET_ADVERTISING_SET_RANDOM_ADDRESS, OpCodeIndex::LE_SET_ADVERTISING_SET_RANDOM_ADDRESS}, - {OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, - OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_PARAMETERS}, + {OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS_V1, + OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_PARAMETERS_V1}, {OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_DATA}, {OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, OpCodeIndex::LE_SET_EXTENDED_SCAN_RESPONSE_DATA}, @@ -3591,14 +3594,14 @@ const std::unordered_map<OpCode, OpCodeIndex> DualModeController::hci_command_op OpCodeIndex::LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS}, {OpCode::LE_REMOVE_ADVERTISING_SET, OpCodeIndex::LE_REMOVE_ADVERTISING_SET}, {OpCode::LE_CLEAR_ADVERTISING_SETS, OpCodeIndex::LE_CLEAR_ADVERTISING_SETS}, - {OpCode::LE_SET_PERIODIC_ADVERTISING_PARAMETERS, - OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_PARAMETERS}, + {OpCode::LE_SET_PERIODIC_ADVERTISING_PARAMETERS_V1, + OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_PARAMETERS_V1}, {OpCode::LE_SET_PERIODIC_ADVERTISING_DATA, OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_DATA}, {OpCode::LE_SET_PERIODIC_ADVERTISING_ENABLE, OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_ENABLE}, {OpCode::LE_SET_EXTENDED_SCAN_PARAMETERS, OpCodeIndex::LE_SET_EXTENDED_SCAN_PARAMETERS}, {OpCode::LE_SET_EXTENDED_SCAN_ENABLE, OpCodeIndex::LE_SET_EXTENDED_SCAN_ENABLE}, - {OpCode::LE_EXTENDED_CREATE_CONNECTION, OpCodeIndex::LE_EXTENDED_CREATE_CONNECTION}, + {OpCode::LE_EXTENDED_CREATE_CONNECTION_V1, OpCodeIndex::LE_EXTENDED_CREATE_CONNECTION_V1}, {OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC, OpCodeIndex::LE_PERIODIC_ADVERTISING_CREATE_SYNC}, {OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, @@ -3665,7 +3668,7 @@ const std::unordered_map<OpCode, OpCodeIndex> DualModeController::hci_command_op {OpCode::LE_ISO_RECEIVE_TEST, OpCodeIndex::LE_ISO_RECEIVE_TEST}, {OpCode::LE_ISO_READ_TEST_COUNTERS, OpCodeIndex::LE_ISO_READ_TEST_COUNTERS}, {OpCode::LE_ISO_TEST_END, OpCodeIndex::LE_ISO_TEST_END}, - {OpCode::LE_SET_HOST_FEATURE, OpCodeIndex::LE_SET_HOST_FEATURE}, + {OpCode::LE_SET_HOST_FEATURE_V1, OpCodeIndex::LE_SET_HOST_FEATURE_V1}, {OpCode::LE_READ_ISO_LINK_QUALITY, OpCodeIndex::LE_READ_ISO_LINK_QUALITY}, {OpCode::LE_ENHANCED_READ_TRANSMIT_POWER_LEVEL, OpCodeIndex::LE_ENHANCED_READ_TRANSMIT_POWER_LEVEL}, @@ -3681,6 +3684,49 @@ const std::unordered_map<OpCode, OpCodeIndex> DualModeController::hci_command_op OpCodeIndex::LE_SET_DATA_RELATED_ADDRESS_CHANGES}, {OpCode::LE_SET_DEFAULT_SUBRATE, OpCodeIndex::LE_SET_DEFAULT_SUBRATE}, {OpCode::LE_SUBRATE_REQUEST, OpCodeIndex::LE_SUBRATE_REQUEST}, + {OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS_V2, + OpCodeIndex::LE_SET_EXTENDED_ADVERTISING_PARAMETERS_V2}, + {OpCode::LE_SET_DECISION_DATA, OpCodeIndex::LE_SET_DECISION_DATA}, + {OpCode::LE_SET_DECISION_INSTRUCTIONS, OpCodeIndex::LE_SET_DECISION_INSTRUCTIONS}, + {OpCode::LE_SET_PERIODIC_ADVERTISING_SUBEVENT_DATA, + OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_SUBEVENT_DATA}, + {OpCode::LE_SET_PERIODIC_ADVERTISING_RESPONSE_DATA, + OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_RESPONSE_DATA}, + {OpCode::LE_SET_PERIODIC_SYNC_SUBEVENT, OpCodeIndex::LE_SET_PERIODIC_SYNC_SUBEVENT}, + {OpCode::LE_EXTENDED_CREATE_CONNECTION_V2, OpCodeIndex::LE_EXTENDED_CREATE_CONNECTION_V2}, + {OpCode::LE_SET_PERIODIC_ADVERTISING_PARAMETERS_V2, + OpCodeIndex::LE_SET_PERIODIC_ADVERTISING_PARAMETERS_V2}, + {OpCode::LE_READ_ALL_LOCAL_SUPPORTED_FEATURES, + OpCodeIndex::LE_READ_ALL_LOCAL_SUPPORTED_FEATURES}, + {OpCode::LE_READ_ALL_REMOTE_FEATURES, OpCodeIndex::LE_READ_ALL_REMOTE_FEATURES}, + {OpCode::LE_CS_READ_LOCAL_SUPPORTED_CAPABILITIES, + OpCodeIndex::LE_CS_READ_LOCAL_SUPPORTED_CAPABILITIES}, + {OpCode::LE_CS_READ_REMOTE_SUPPORTED_CAPABILITIES, + OpCodeIndex::LE_CS_READ_REMOTE_SUPPORTED_CAPABILITIES}, + {OpCode::LE_CS_WRITE_CACHED_REMOTE_SUPPORTED_CAPABILITIES, + OpCodeIndex::LE_CS_WRITE_CACHED_REMOTE_SUPPORTED_CAPABILITIES}, + {OpCode::LE_CS_SECURITY_ENABLE, OpCodeIndex::LE_CS_SECURITY_ENABLE}, + {OpCode::LE_CS_SET_DEFAULT_SETTINGS, OpCodeIndex::LE_CS_SET_DEFAULT_SETTINGS}, + {OpCode::LE_CS_READ_REMOTE_FAE_TABLE, OpCodeIndex::LE_CS_READ_REMOTE_FAE_TABLE}, + {OpCode::LE_CS_WRITE_CACHED_REMOTE_FAE_TABLE, + OpCodeIndex::LE_CS_WRITE_CACHED_REMOTE_FAE_TABLE}, + {OpCode::LE_CS_CREATE_CONFIG, OpCodeIndex::LE_CS_CREATE_CONFIG}, + {OpCode::LE_CS_REMOVE_CONFIG, OpCodeIndex::LE_CS_REMOVE_CONFIG}, + {OpCode::LE_CS_SET_CHANNEL_CLASSIFICATION, OpCodeIndex::LE_CS_SET_CHANNEL_CLASSIFICATION}, + {OpCode::LE_CS_SET_PROCEDURE_PARAMETERS, OpCodeIndex::LE_CS_SET_PROCEDURE_PARAMETERS}, + {OpCode::LE_CS_PROCEDURE_ENABLE, OpCodeIndex::LE_CS_PROCEDURE_ENABLE}, + {OpCode::LE_CS_TEST, OpCodeIndex::LE_CS_TEST}, + {OpCode::LE_CS_TEST_END, OpCodeIndex::LE_CS_TEST_END}, + {OpCode::LE_ADD_DEVICE_TO_MONITORED_ADVERTISERS_LIST, + OpCodeIndex::LE_ADD_DEVICE_TO_MONITORED_ADVERTISERS_LIST}, + {OpCode::LE_REMOVE_DEVICE_FROM_MONITORED_ADVERTISERS_LIST, + OpCodeIndex::LE_REMOVE_DEVICE_FROM_MONITORED_ADVERTISERS_LIST}, + {OpCode::LE_CLEAR_MONITORED_ADVERTISERS_LIST, + OpCodeIndex::LE_CLEAR_MONITORED_ADVERTISERS_LIST}, + {OpCode::LE_READ_MONITORED_ADVERTISERS_LIST_SIZE, + OpCodeIndex::LE_READ_MONITORED_ADVERTISERS_LIST_SIZE}, + {OpCode::LE_ENABLE_MONITORING_ADVERTISERS, OpCodeIndex::LE_ENABLE_MONITORING_ADVERTISERS}, + {OpCode::LE_FRAME_SPACE_UPDATE, OpCodeIndex::LE_FRAME_SPACE_UPDATE}, }; const std::unordered_map<OpCode, DualModeController::CommandHandler> @@ -3970,8 +4016,8 @@ const std::unordered_map<OpCode, DualModeController::CommandHandler> // LE_CONTROLLER {OpCode::LE_SET_EVENT_MASK, &DualModeController::LeSetEventMask}, {OpCode::LE_READ_BUFFER_SIZE_V1, &DualModeController::LeReadBufferSizeV1}, - {OpCode::LE_READ_LOCAL_SUPPORTED_FEATURES, - &DualModeController::LeReadLocalSupportedFeatures}, + {OpCode::LE_READ_LOCAL_SUPPORTED_FEATURES_PAGE_0, + &DualModeController::LeReadLocalSupportedFeaturesPage0}, {OpCode::LE_SET_RANDOM_ADDRESS, &DualModeController::LeSetRandomAddress}, {OpCode::LE_SET_ADVERTISING_PARAMETERS, &DualModeController::LeSetAdvertisingParameters}, @@ -3996,7 +4042,8 @@ const std::unordered_map<OpCode, DualModeController::CommandHandler> //{OpCode::LE_SET_HOST_CHANNEL_CLASSIFICATION, //&DualModeController::LeSetHostChannelClassification}, //{OpCode::LE_READ_CHANNEL_MAP, &DualModeController::LeReadChannelMap}, - {OpCode::LE_READ_REMOTE_FEATURES, &DualModeController::LeReadRemoteFeatures}, + {OpCode::LE_READ_REMOTE_FEATURES_PAGE_0, + &DualModeController::LeReadRemoteFeaturesPage0}, {OpCode::LE_ENCRYPT, &DualModeController::LeEncrypt}, {OpCode::LE_RAND, &DualModeController::LeRand}, {OpCode::LE_START_ENCRYPTION, &DualModeController::LeStartEncryption}, @@ -4045,8 +4092,8 @@ const std::unordered_map<OpCode, DualModeController::CommandHandler> //&DualModeController::LeTransmitterTestV2}, {OpCode::LE_SET_ADVERTISING_SET_RANDOM_ADDRESS, &DualModeController::LeSetAdvertisingSetRandomAddress}, - {OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS, - &DualModeController::LeSetExtendedAdvertisingParameters}, + {OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS_V1, + &DualModeController::LeSetExtendedAdvertisingParametersV1}, {OpCode::LE_SET_EXTENDED_ADVERTISING_DATA, &DualModeController::LeSetExtendedAdvertisingData}, {OpCode::LE_SET_EXTENDED_SCAN_RESPONSE_DATA, @@ -4059,8 +4106,8 @@ const std::unordered_map<OpCode, DualModeController::CommandHandler> &DualModeController::LeReadNumberOfSupportedAdvertisingSets}, {OpCode::LE_REMOVE_ADVERTISING_SET, &DualModeController::LeRemoveAdvertisingSet}, {OpCode::LE_CLEAR_ADVERTISING_SETS, &DualModeController::LeClearAdvertisingSets}, - {OpCode::LE_SET_PERIODIC_ADVERTISING_PARAMETERS, - &DualModeController::LeSetPeriodicAdvertisingParameters}, + {OpCode::LE_SET_PERIODIC_ADVERTISING_PARAMETERS_V1, + &DualModeController::LeSetPeriodicAdvertisingParametersV1}, {OpCode::LE_SET_PERIODIC_ADVERTISING_DATA, &DualModeController::LeSetPeriodicAdvertisingData}, {OpCode::LE_SET_PERIODIC_ADVERTISING_ENABLE, @@ -4068,8 +4115,8 @@ const std::unordered_map<OpCode, DualModeController::CommandHandler> {OpCode::LE_SET_EXTENDED_SCAN_PARAMETERS, &DualModeController::LeSetExtendedScanParameters}, {OpCode::LE_SET_EXTENDED_SCAN_ENABLE, &DualModeController::LeSetExtendedScanEnable}, - {OpCode::LE_EXTENDED_CREATE_CONNECTION, - &DualModeController::LeExtendedCreateConnection}, + {OpCode::LE_EXTENDED_CREATE_CONNECTION_V1, + &DualModeController::LeExtendedCreateConnectionV1}, {OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC, &DualModeController::LePeriodicAdvertisingCreateSync}, {OpCode::LE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, @@ -4147,7 +4194,7 @@ const std::unordered_map<OpCode, DualModeController::CommandHandler> //{OpCode::LE_ISO_READ_TEST_COUNTERS, //&DualModeController::LeIsoReadTestCounters}, //{OpCode::LE_ISO_TEST_END, &DualModeController::LeIsoTestEnd}, - {OpCode::LE_SET_HOST_FEATURE, &DualModeController::LeSetHostFeature}, + {OpCode::LE_SET_HOST_FEATURE_V1, &DualModeController::LeSetHostFeatureV1}, //{OpCode::LE_READ_ISO_LINK_QUALITY, //&DualModeController::LeReadIsoLinkQuality}, //{OpCode::LE_ENHANCED_READ_TRANSMIT_POWER_LEVEL, @@ -4167,6 +4214,57 @@ const std::unordered_map<OpCode, DualModeController::CommandHandler> //{OpCode::LE_SET_DEFAULT_SUBRATE, //&DualModeController::LeSetDefaultSubrate}, //{OpCode::LE_SUBRATE_REQUEST, &DualModeController::LeSubrateRequest}, + //{OpCode::LE_SET_EXTENDED_ADVERTISING_PARAMETERS_V2, + //&DualModeController::LeSetExtendedAdvertisingParametersV2}, + //{OpCode::LE_SET_DECISION_DATA, &DualModeController::LeSetDecisionData}, + //{OpCode::LE_SET_DECISION_INSTRUCTIONS, + //&DualModeController::LeSetDecisionInstructions}, + //{OpCode::LE_SET_PERIODIC_ADVERTISING_SUBEVENT_DATA, + //&DualModeController::LeSetPeriodicAdvertisingSubeventData}, + //{OpCode::LE_SET_PERIODIC_ADVERTISING_RESPONSE_DATA, + //&DualModeController::LeSetPeriodicAdvertisingResponseData}, + //{OpCode::LE_SET_PERIODIC_SYNC_SUBEVENT, + //&DualModeController::LeSetPeriodicSyncSubevent}, + //{OpCode::LE_EXTENDED_CREATE_CONNECTION_V2, + //&DualModeController::LeExtendedCreateConnectionV2}, + //{OpCode::LE_SET_PERIODIC_ADVERTISING_PARAMETERS_V2, + //&DualModeController::LeSetPeriodicAdvertisingParametersV2}, + //{OpCode::LE_READ_ALL_LOCAL_SUPPORTED_FEATURES, + //&DualModeController::LeReadAllLocalSupportedFeatures}, + //{OpCode::LE_READ_ALL_REMOTE_FEATURES, + //&DualModeController::LeReadAllRemoteFeatures}, + //{OpCode::LE_CS_READ_LOCAL_SUPPORTED_CAPABILITIES, + //&DualModeController::LeCsReadLocalSupportedCapabilities}, + //{OpCode::LE_CS_READ_REMOTE_SUPPORTED_CAPABILITIES, + //&DualModeController::LeCsReadRemoteSupportedCapabilities}, + //{OpCode::LE_CS_WRITE_CACHED_REMOTE_SUPPORTED_CAPABILITIES, + //&DualModeController::LeCsWriteCachedRemoteSupportedCapabilities}, + //{OpCode::LE_CS_SECURITY_ENABLE, &DualModeController::LeCsSecurityEnable}, + //{OpCode::LE_CS_SET_DEFAULT_SETTINGS, &DualModeController::LeCsSetDefaultSettings}, + //{OpCode::LE_CS_READ_REMOTE_FAE_TABLE, + //&DualModeController::LeCsReadRemoteFaeTable}, + //{OpCode::LE_CS_WRITE_CACHED_REMOTE_FAE_TABLE, + //&DualModeController::LeCsWriteCachedRemoteFaeTable}, + //{OpCode::LE_CS_CREATE_CONFIG, &DualModeController::LeCsCreateConfig}, + //{OpCode::LE_CS_REMOVE_CONFIG, &DualModeController::LeCsRemoveConfig}, + //{OpCode::LE_CS_SET_CHANNEL_CLASSIFICATION, + //&DualModeController::LeCsSetChannelClassification}, + //{OpCode::LE_CS_SET_PROCEDURE_PARAMETERS, + //&DualModeController::LeCsSetProcedureParameters}, + //{OpCode::LE_CS_PROCEDURE_ENABLE, &DualModeController::LeCsProcedureEnable}, + //{OpCode::LE_CS_TEST, &DualModeController::LeCsTest}, + //{OpCode::LE_CS_TEST_END, &DualModeController::LeCsTestEnd}, + //{OpCode::LE_ADD_DEVICE_TO_MONITORED_ADVERTISERS_LIST, + //&DualModeController::LeAddDeviceToMonitoredAdvertisersList}, + //{OpCode::LE_REMOVE_DEVICE_FROM_MONITORED_ADVERTISERS_LIST, + //&DualModeController::LeRemoveDeviceFromMonitoredAdvertisersList}, + //{OpCode::LE_CLEAR_MONITORED_ADVERTISERS_LIST, + //&DualModeController::LeClearMonitoredAdvertisersList}, + //{OpCode::LE_READ_MONITORED_ADVERTISERS_LIST_SIZE, + //&DualModeController::LeReadMonitoredAdvertisersListSize}, + //{OpCode::LE_ENABLE_MONITORED_ADVERTISERS, + //&DualModeController::LeEnableMonitoredAdvertisers}, + //{OpCode::LE_FRAME_SPACE_UPDATE, &DualModeController::LeFrameSpaceUpdate}, // VENDOR {OpCode(CSR_VENDOR), &DualModeController::CsrVendorCommand}, diff --git a/tools/rootcanal/model/controller/dual_mode_controller.h b/tools/rootcanal/model/controller/dual_mode_controller.h index 901d13d802..d0394a7bfd 100644 --- a/tools/rootcanal/model/controller/dual_mode_controller.h +++ b/tools/rootcanal/model/controller/dual_mode_controller.h @@ -394,7 +394,7 @@ public: void LeReadBufferSizeV2(CommandView command); // 7.8.3 - void LeReadLocalSupportedFeatures(CommandView command); + void LeReadLocalSupportedFeaturesPage0(CommandView command); // 7.8.4 void LeSetRandomAddress(CommandView command); @@ -424,7 +424,7 @@ public: void LeConnectionUpdate(CommandView command); // 7.8.21 - void LeReadRemoteFeatures(CommandView command); + void LeReadRemoteFeaturesPage0(CommandView command); // 7.8.22 void LeEncrypt(CommandView command); @@ -477,7 +477,7 @@ public: // 7.8.52 - 7.8.60 void LeSetAdvertisingSetRandomAddress(CommandView command); - void LeSetExtendedAdvertisingParameters(CommandView command); + void LeSetExtendedAdvertisingParametersV1(CommandView command); void LeSetExtendedAdvertisingData(CommandView command); void LeSetExtendedScanResponseData(CommandView command); void LeSetExtendedAdvertisingEnable(CommandView command); @@ -487,7 +487,7 @@ public: void LeClearAdvertisingSets(CommandView command); // 7.8.61 - 7.8.63 - void LeSetPeriodicAdvertisingParameters(CommandView command); + void LeSetPeriodicAdvertisingParametersV1(CommandView command); void LeSetPeriodicAdvertisingData(CommandView command); void LeSetPeriodicAdvertisingEnable(CommandView command); @@ -507,7 +507,7 @@ public: void LeSetExtendedScanEnable(CommandView command); // 7.8.66 - void LeExtendedCreateConnection(CommandView command); + void LeExtendedCreateConnectionV1(CommandView command); // 7.8.77 void LeSetPrivacyMode(CommandView command); @@ -516,7 +516,7 @@ public: void LeRequestPeerSca(CommandView command); // 7.8.115 - void LeSetHostFeature(CommandView command); + void LeSetHostFeatureV1(CommandView command); // Vendor-specific Commands void LeGetVendorCapabilities(CommandView command); diff --git a/tools/rootcanal/model/controller/le_advertiser.cc b/tools/rootcanal/model/controller/le_advertiser.cc index 7f5a89fd12..cd9ae5610c 100644 --- a/tools/rootcanal/model/controller/le_advertiser.cc +++ b/tools/rootcanal/model/controller/le_advertiser.cc @@ -1199,7 +1199,7 @@ uint16_t ExtendedAdvertiser::GetMaxAdvertisingDataLength( max_advertising_data_length -= 6; // AdvA max_advertising_data_length -= 2; // ADI max_advertising_data_length -= 6 * properties.directed_; // TargetA - max_advertising_data_length -= 1 * properties.tx_power_; // TxPower + max_advertising_data_length -= 1 * properties.include_tx_power_; // TxPower // TODO(pedantic): configure the ACAD field in order to leave the least // amount of AdvData space to the user (191). } @@ -1252,7 +1252,7 @@ uint16_t ExtendedAdvertiser::GetRawAdvertisingEventProperties( if (properties.anonymous_) { mask |= 0x20; } - if (properties.tx_power_) { + if (properties.include_tx_power_) { mask |= 0x40; } return mask; @@ -1584,13 +1584,13 @@ void LinkLayerController::LeAdvertising() { // is unmasked. #if 0 if (IsLeEventUnmasked(SubeventCode::ENHANCED_CONNECTION_COMPLETE)) { - send_event_(bluetooth::hci::LeEnhancedConnectionCompleteBuilder::Create( + send_event_(bluetooth::hci::LeEnhancedConnectionCompleteV1Builder::Create( ErrorCode::ADVERTISING_TIMEOUT, 0, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS, Address(), Address(), Address(), 0, 0, 0, ClockAccuracy::PPM_500)); } else #endif - if (IsLeEventUnmasked(SubeventCode::CONNECTION_COMPLETE)) { + if (IsLeEventUnmasked(SubeventCode::LE_CONNECTION_COMPLETE)) { send_event_(bluetooth::hci::LeConnectionCompleteBuilder::Create( ErrorCode::ADVERTISING_TIMEOUT, 0, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS, Address(), 0, 0, 0, ClockAccuracy::PPM_500)); @@ -1662,19 +1662,19 @@ void LinkLayerController::LeAdvertising() { // HCI_LE_Enhanced_Connection_Complete event (see Section 7.7.65.10) // is unmasked. if (high_duty_cycle_connectable_directed_advertising && - IsLeEventUnmasked(SubeventCode::ENHANCED_CONNECTION_COMPLETE)) { - send_event_(bluetooth::hci::LeEnhancedConnectionCompleteBuilder::Create( + IsLeEventUnmasked(SubeventCode::LE_ENHANCED_CONNECTION_COMPLETE_V1)) { + send_event_(bluetooth::hci::LeEnhancedConnectionCompleteV1Builder::Create( ErrorCode::ADVERTISING_TIMEOUT, 0, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS, Address(), Address(), Address(), 0, 0, 0, ClockAccuracy::PPM_500)); } else if (high_duty_cycle_connectable_directed_advertising && - IsLeEventUnmasked(SubeventCode::CONNECTION_COMPLETE)) { + IsLeEventUnmasked(SubeventCode::LE_CONNECTION_COMPLETE)) { send_event_(bluetooth::hci::LeConnectionCompleteBuilder::Create( ErrorCode::ADVERTISING_TIMEOUT, 0, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS, Address(), 0, 0, 0, ClockAccuracy::PPM_500)); } - if (IsLeEventUnmasked(SubeventCode::ADVERTISING_SET_TERMINATED)) { + if (IsLeEventUnmasked(SubeventCode::LE_ADVERTISING_SET_TERMINATED)) { // The parameter Num_Completed_Extended_Advertising_Events is set // only when Max_Extended_Advertising_Events was configured as // non-zero in the advertising parameters. @@ -1698,7 +1698,7 @@ void LinkLayerController::LeAdvertising() { INFO(id_, "Max Extended Advertising count reached"); advertiser.Disable(); - if (IsLeEventUnmasked(SubeventCode::ADVERTISING_SET_TERMINATED)) { + if (IsLeEventUnmasked(SubeventCode::LE_ADVERTISING_SET_TERMINATED)) { send_event_(bluetooth::hci::LeAdvertisingSetTerminatedBuilder::Create( ErrorCode::ADVERTISING_TIMEOUT, advertiser.advertising_handle, 0, advertiser.num_completed_extended_advertising_events)); diff --git a/tools/rootcanal/model/controller/link_layer_controller.cc b/tools/rootcanal/model/controller/link_layer_controller.cc index e793ac16e3..04416e84c4 100644 --- a/tools/rootcanal/model/controller/link_layer_controller.cc +++ b/tools/rootcanal/model/controller/link_layer_controller.cc @@ -132,7 +132,7 @@ bool LinkLayerController::FilterAcceptListBusy() { // command is pending. if (initiator_.IsEnabled() && initiator_.initiator_filter_policy == - bluetooth::hci::InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST) { + bluetooth::hci::InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST_WITH_PEER_ADDRESS) { return true; } @@ -522,7 +522,7 @@ void LinkLayerController::IncomingLlPhyReq(model::packets::LinkLayerPacketView i // Notify the host when the phy selection has changed // (responder in this case). if ((phy_c_to_p != connection.GetTxPhy() || phy_p_to_c != connection.GetRxPhy()) && - IsLeEventUnmasked(SubeventCode::PHY_UPDATE_COMPLETE)) { + IsLeEventUnmasked(SubeventCode::LE_PHY_UPDATE_COMPLETE)) { send_event_(bluetooth::hci::LePhyUpdateCompleteBuilder::Create( ErrorCode::SUCCESS, connection_handle, phy_c_to_p, phy_p_to_c)); } @@ -569,7 +569,7 @@ void LinkLayerController::IncomingLlPhyRsp(model::packets::LinkLayerPacketView i // Always notify the host, even if the phy selection has not changed // (initiator in this case). - if (IsLeEventUnmasked(SubeventCode::PHY_UPDATE_COMPLETE)) { + if (IsLeEventUnmasked(SubeventCode::LE_PHY_UPDATE_COMPLETE)) { send_event_(bluetooth::hci::LePhyUpdateCompleteBuilder::Create( ErrorCode::SUCCESS, connection_handle, phy_c_to_p, phy_p_to_c)); } @@ -600,7 +600,7 @@ void LinkLayerController::IncomingLlPhyUpdateInd(model::packets::LinkLayerPacket // Update local state, and notify the host. // The notification is sent only when the local host is initiator // of the Phy update procedure or the phy selection has changed. - if (IsLeEventUnmasked(SubeventCode::PHY_UPDATE_COMPLETE) && + if (IsLeEventUnmasked(SubeventCode::LE_PHY_UPDATE_COMPLETE) && (tx_phy != connection.GetTxPhy() || rx_phy != connection.GetRxPhy() || connection.InitiatedPhyUpdate())) { send_event_(bluetooth::hci::LePhyUpdateCompleteBuilder::Create( @@ -1126,9 +1126,9 @@ ErrorCode LinkLayerController::LePeriodicAdvertisingCreateSyncCancel() { // successful, the Controller sends an HCI_LE_Periodic_Advertising_Sync_- // Established event to the Host with the error code Operation Cancelled // by Host (0x44). - if (IsLeEventUnmasked(SubeventCode::PERIODIC_ADVERTISING_SYNC_ESTABLISHED)) { + if (IsLeEventUnmasked(SubeventCode::LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHED_V1)) { ScheduleTask(0ms, [this] { - send_event_(bluetooth::hci::LePeriodicAdvertisingSyncEstablishedBuilder::Create( + send_event_(bluetooth::hci::LePeriodicAdvertisingSyncEstablishedV1Builder::Create( ErrorCode::OPERATION_CANCELLED_BY_HOST, 0, 0, AddressType::PUBLIC_DEVICE_ADDRESS, Address::kEmpty, bluetooth::hci::SecondaryPhyType::NO_PACKETS, 0, bluetooth::hci::ClockAccuracy::PPM_500)); @@ -1625,13 +1625,13 @@ ErrorCode LinkLayerController::LeCreateConnectionCancel() { // Connection Complete or an HCI_LE_Enhanced_Connection_Complete event // shall be generated. In either case, the event shall be sent with the error // code Unknown Connection Identifier (0x02). - if (IsLeEventUnmasked(SubeventCode::ENHANCED_CONNECTION_COMPLETE)) { + if (IsLeEventUnmasked(SubeventCode::LE_ENHANCED_CONNECTION_COMPLETE_V1)) { ScheduleTask(0ms, [this] { - send_event_(bluetooth::hci::LeEnhancedConnectionCompleteBuilder::Create( + send_event_(bluetooth::hci::LeEnhancedConnectionCompleteV1Builder::Create( ErrorCode::UNKNOWN_CONNECTION, 0, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS, Address(), Address(), Address(), 0, 0, 0, bluetooth::hci::ClockAccuracy::PPM_500)); }); - } else if (IsLeEventUnmasked(SubeventCode::CONNECTION_COMPLETE)) { + } else if (IsLeEventUnmasked(SubeventCode::LE_CONNECTION_COMPLETE)) { ScheduleTask(0ms, [this] { send_event_(bluetooth::hci::LeConnectionCompleteBuilder::Create( ErrorCode::UNKNOWN_CONNECTION, 0, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS, @@ -2049,7 +2049,7 @@ ErrorCode LinkLayerController::SendLeCommandToRemoteByAddress(OpCode opcode, const Address& own_address, const Address& peer_address) { switch (opcode) { - case (OpCode::LE_READ_REMOTE_FEATURES): + case (OpCode::LE_READ_REMOTE_FEATURES_PAGE_0): SendLeLinkLayerPacket( model::packets::LeReadRemoteFeaturesBuilder::Create(own_address, peer_address)); break; @@ -2105,7 +2105,7 @@ ErrorCode LinkLayerController::SendCommandToRemoteByHandle(OpCode opcode, pdl::p } switch (opcode) { - case (OpCode::LE_READ_REMOTE_FEATURES): + case (OpCode::LE_READ_REMOTE_FEATURES_PAGE_0): return SendLeCommandToRemoteByAddress(opcode, connections_.GetOwnAddress(handle).GetAddress(), connections_.GetAddress(handle).GetAddress()); default: @@ -2849,7 +2849,7 @@ void LinkLayerController::ScanIncomingLeLegacyAdvertisingPdu( // Legacy scanning, directed advertising. if (LegacyAdvertising() && should_send_advertising_report && should_send_directed_advertising_report && - IsLeEventUnmasked(SubeventCode::DIRECTED_ADVERTISING_REPORT)) { + IsLeEventUnmasked(SubeventCode::LE_DIRECTED_ADVERTISING_REPORT)) { bluetooth::hci::LeDirectedAdvertisingResponse response; response.event_type_ = bluetooth::hci::DirectAdvertisingEventType::ADV_DIRECT_IND; response.address_type_ = static_cast<bluetooth::hci::DirectAdvertisingAddressType>( @@ -2865,7 +2865,7 @@ void LinkLayerController::ScanIncomingLeLegacyAdvertisingPdu( // Legacy scanning, un-directed advertising. if (LegacyAdvertising() && should_send_advertising_report && !should_send_directed_advertising_report && - IsLeEventUnmasked(SubeventCode::ADVERTISING_REPORT)) { + IsLeEventUnmasked(SubeventCode::LE_ADVERTISING_REPORT)) { bluetooth::hci::LeAdvertisingResponse response; response.address_type_ = resolved_advertising_address.GetAddressType(); response.address_ = resolved_advertising_address.GetAddress(); @@ -2892,7 +2892,7 @@ void LinkLayerController::ScanIncomingLeLegacyAdvertisingPdu( // Extended scanning. if (ExtendedAdvertising() && should_send_advertising_report && - IsLeEventUnmasked(SubeventCode::EXTENDED_ADVERTISING_REPORT)) { + IsLeEventUnmasked(SubeventCode::LE_EXTENDED_ADVERTISING_REPORT)) { bluetooth::hci::LeExtendedAdvertisingResponse response; response.connectable_ = connectable_advertising; response.scannable_ = scannable_advertising; @@ -3061,7 +3061,7 @@ void LinkLayerController::ConnectIncomingLeLegacyAdvertisingPdu( return; } break; - case bluetooth::hci::InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST: + case bluetooth::hci::InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST_WITH_PEER_ADDRESS: if (!LeFilterAcceptListContainsDevice(resolved_advertising_address)) { DEBUG(id_, "Legacy advertising ignored by initiator because the " @@ -3070,6 +3070,12 @@ void LinkLayerController::ConnectIncomingLeLegacyAdvertisingPdu( return; } break; + case bluetooth::hci::InitiatorFilterPolicy::USE_DECISION_PDUS: + case bluetooth::hci::InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST_WITH_DECISION_PDUS: + DEBUG(id_, + "Legacy advertising ignored by initiated because the " + "initiator filter policy is unsupported"); + return; } // When an initiator receives a directed connectable advertising event that @@ -3295,7 +3301,7 @@ void LinkLayerController::ScanIncomingLeExtendedAdvertisingPdu( } if (should_send_advertising_report && - IsLeEventUnmasked(SubeventCode::EXTENDED_ADVERTISING_REPORT)) { + IsLeEventUnmasked(SubeventCode::LE_EXTENDED_ADVERTISING_REPORT)) { bluetooth::hci::LeExtendedAdvertisingResponse response; response.connectable_ = connectable_advertising; response.scannable_ = scannable_advertising; @@ -3476,7 +3482,7 @@ void LinkLayerController::ConnectIncomingLeExtendedAdvertisingPdu( return; } break; - case bluetooth::hci::InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST: + case bluetooth::hci::InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST_WITH_PEER_ADDRESS: if (!LeFilterAcceptListContainsDevice(resolved_advertising_address)) { DEBUG(id_, "Extended advertising ignored by initiator because the " @@ -3485,6 +3491,12 @@ void LinkLayerController::ConnectIncomingLeExtendedAdvertisingPdu( return; } break; + case bluetooth::hci::InitiatorFilterPolicy::USE_DECISION_PDUS: + case bluetooth::hci::InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST_WITH_DECISION_PDUS: + DEBUG(id_, + "Extended advertising ignored by initiator because the " + "initiator filter policy is not supported"); + return; } // When an initiator receives a directed connectable advertising event that @@ -3654,8 +3666,8 @@ void LinkLayerController::IncomingLePeriodicAdvertisingPdu( } // Notify of the new Synchronized train. - if (IsLeEventUnmasked(SubeventCode::PERIODIC_ADVERTISING_SYNC_ESTABLISHED)) { - send_event_(bluetooth::hci::LePeriodicAdvertisingSyncEstablishedBuilder::Create( + if (IsLeEventUnmasked(SubeventCode::LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHED_V1)) { + send_event_(bluetooth::hci::LePeriodicAdvertisingSyncEstablishedV1Builder::Create( ErrorCode::SUCCESS, sync_handle, advertising_sid, resolved_advertiser_address.GetAddressType(), resolved_advertiser_address.GetAddress(), bluetooth::hci::SecondaryPhyType::LE_1M, @@ -3696,7 +3708,7 @@ void LinkLayerController::IncomingLePeriodicAdvertisingPdu( // and refresh the timeout for sync termination. The periodic // advertising event might need to be fragmented to fit the maximum // size of an HCI event. - if (IsLeEventUnmasked(SubeventCode::PERIODIC_ADVERTISING_REPORT)) { + if (IsLeEventUnmasked(SubeventCode::LE_PERIODIC_ADVERTISING_REPORT_V1)) { // Each extended advertising report can only pass 229 bytes of // advertising data (255 - 8 = size of report fields). std::vector<uint8_t> advertising_data = pdu.GetAdvertisingData(); @@ -3712,7 +3724,7 @@ void LinkLayerController::IncomingLePeriodicAdvertisingPdu( std::vector<uint8_t> fragment_data(advertising_data.begin() + offset, advertising_data.begin() + offset + fragment_size); offset += fragment_size; - send_event_(bluetooth::hci::LePeriodicAdvertisingReportBuilder::Create( + send_event_(bluetooth::hci::LePeriodicAdvertisingReportV1Builder::Create( sync.sync_handle, pdu.GetTxPower(), rssi, bluetooth::hci::CteType::NO_CONSTANT_TONE_EXTENSION, data_status, fragment_data)); } while (offset < advertising_data.size()); @@ -4001,7 +4013,7 @@ uint16_t LinkLayerController::HandleLeConnection( return kReservedHandle; } - if (IsLeEventUnmasked(SubeventCode::ENHANCED_CONNECTION_COMPLETE)) { + if (IsLeEventUnmasked(SubeventCode::LE_ENHANCED_CONNECTION_COMPLETE_V1)) { AddressWithType peer_resolved_address = connections_.GetResolvedAddress(handle); Address peer_resolvable_private_address; Address connection_address = address.GetAddress(); @@ -4016,12 +4028,12 @@ uint16_t LinkLayerController::HandleLeConnection( local_resolved_address = Address::kEmpty; } - send_event_(bluetooth::hci::LeEnhancedConnectionCompleteBuilder::Create( + send_event_(bluetooth::hci::LeEnhancedConnectionCompleteV1Builder::Create( ErrorCode::SUCCESS, handle, role, peer_address_type, connection_address, local_resolved_address, peer_resolvable_private_address, connection_interval, connection_latency, supervision_timeout, static_cast<bluetooth::hci::ClockAccuracy>(0x00))); - } else if (IsLeEventUnmasked(SubeventCode::CONNECTION_COMPLETE)) { + } else if (IsLeEventUnmasked(SubeventCode::LE_CONNECTION_COMPLETE)) { send_event_(bluetooth::hci::LeConnectionCompleteBuilder::Create( ErrorCode::SUCCESS, handle, role, address.GetAddressType(), address.GetAddress(), connection_interval, connection_latency, supervision_timeout, @@ -4037,7 +4049,7 @@ uint16_t LinkLayerController::HandleLeConnection( // an HCI_LE_Channel_Selection_Algorithm event if the connection is created // using the LE_Extended_Create_Connection command (see Section 7.7.8.66). if (send_le_channel_selection_algorithm_event && - IsLeEventUnmasked(SubeventCode::CHANNEL_SELECTION_ALGORITHM)) { + IsLeEventUnmasked(SubeventCode::LE_CHANNEL_SELECTION_ALGORITHM)) { // The selection channel algorithm probably will have no impact // on emulation. send_event_(bluetooth::hci::LeChannelSelectionAlgorithmBuilder::Create( @@ -4269,7 +4281,7 @@ bool LinkLayerController::ProcessIncomingExtendedConnectRequest( // event with the Status parameter set to 0x00. The Controller should not send // any other events in between these two events - if (IsLeEventUnmasked(SubeventCode::ADVERTISING_SET_TERMINATED)) { + if (IsLeEventUnmasked(SubeventCode::LE_ADVERTISING_SET_TERMINATED)) { send_event_(bluetooth::hci::LeAdvertisingSetTerminatedBuilder::Create( ErrorCode::SUCCESS, advertiser.advertising_handle, connection_handle, advertiser.num_completed_extended_advertising_events)); @@ -4328,7 +4340,7 @@ void LinkLayerController::IncomingLeConnectionParameterRequest( return; } - if (IsLeEventUnmasked(SubeventCode::REMOTE_CONNECTION_PARAMETER_REQUEST)) { + if (IsLeEventUnmasked(SubeventCode::LE_REMOTE_CONNECTION_PARAMETER_REQUEST)) { send_event_(bluetooth::hci::LeRemoteConnectionParameterRequestBuilder::Create( handle, request.GetIntervalMin(), request.GetIntervalMax(), request.GetLatency(), request.GetTimeout())); @@ -4352,7 +4364,7 @@ void LinkLayerController::IncomingLeConnectionParameterUpdate( INFO(id_, "@{}: Unknown connection @{}", incoming.GetDestinationAddress(), peer); return; } - if (IsLeEventUnmasked(SubeventCode::CONNECTION_UPDATE_COMPLETE)) { + if (IsLeEventUnmasked(SubeventCode::LE_CONNECTION_UPDATE_COMPLETE)) { send_event_(bluetooth::hci::LeConnectionUpdateCompleteBuilder::Create( static_cast<ErrorCode>(update.GetStatus()), handle, update.GetInterval(), update.GetLatency(), update.GetTimeout())); @@ -4446,7 +4458,7 @@ void LinkLayerController::IncomingLeReadRemoteFeaturesResponse( status = static_cast<ErrorCode>(response.GetStatus()); } if (IsEventUnmasked(EventCode::LE_META_EVENT)) { - send_event_(bluetooth::hci::LeReadRemoteFeaturesCompleteBuilder::Create( + send_event_(bluetooth::hci::LeReadRemoteFeaturesPage0CompleteBuilder::Create( status, handle, response.GetFeatures())); } } @@ -4668,7 +4680,7 @@ void LinkLayerController::IncomingLeScanResponsePacket(model::packets::LinkLayer } if (LegacyAdvertising() && should_send_advertising_report && - IsLeEventUnmasked(SubeventCode::ADVERTISING_REPORT)) { + IsLeEventUnmasked(SubeventCode::LE_ADVERTISING_REPORT)) { bluetooth::hci::LeAdvertisingResponse response; response.event_type_ = bluetooth::hci::AdvertisingEventType::SCAN_RESPONSE; response.address_ = resolved_advertising_address.GetAddress(); @@ -4679,7 +4691,7 @@ void LinkLayerController::IncomingLeScanResponsePacket(model::packets::LinkLayer } if (ExtendedAdvertising() && should_send_advertising_report && - IsLeEventUnmasked(SubeventCode::EXTENDED_ADVERTISING_REPORT)) { + IsLeEventUnmasked(SubeventCode::LE_EXTENDED_ADVERTISING_REPORT)) { bluetooth::hci::LeExtendedAdvertisingResponse response; response.address_ = resolved_advertising_address.GetAddress(); response.address_type_ = static_cast<bluetooth::hci::DirectAdvertisingAddressType>( @@ -4741,7 +4753,7 @@ void LinkLayerController::LeScanning() { scanner_.scan_enable = false; scanner_.pending_scan_request = {}; scanner_.history.clear(); - if (IsLeEventUnmasked(SubeventCode::SCAN_TIMEOUT)) { + if (IsLeEventUnmasked(SubeventCode::LE_SCAN_TIMEOUT)) { send_event_(bluetooth::hci::LeScanTimeoutBuilder::Create()); } } @@ -4779,7 +4791,7 @@ void LinkLayerController::LeSynchronization() { INFO(id_, "Periodic advertising sync with handle 0x{:x} lost", sync.sync_handle); removed_sync_handles.push_back(sync.sync_handle); } - if (IsLeEventUnmasked(SubeventCode::PERIODIC_ADVERTISING_SYNC_LOST)) { + if (IsLeEventUnmasked(SubeventCode::LE_PERIODIC_ADVERTISING_SYNC_LOST)) { send_event_(bluetooth::hci::LePeriodicAdvertisingSyncLostBuilder::Create(sync.sync_handle)); } } @@ -5525,7 +5537,7 @@ void LinkLayerController::LeConnectionUpdateComplete(uint16_t handle, uint16_t i connections_.GetAddress(handle).GetAddress(), static_cast<uint8_t>(ErrorCode::SUCCESS), interval, latency, supervision_timeout)); - if (IsLeEventUnmasked(SubeventCode::CONNECTION_UPDATE_COMPLETE)) { + if (IsLeEventUnmasked(SubeventCode::LE_CONNECTION_UPDATE_COMPLETE)) { send_event_(bluetooth::hci::LeConnectionUpdateCompleteBuilder::Create( status, handle, interval, latency, supervision_timeout)); } @@ -5548,7 +5560,7 @@ ErrorCode LinkLayerController::LeConnectionUpdate(uint16_t handle, uint16_t inte connections_.GetAddress(handle).GetAddress(), static_cast<uint8_t>(ErrorCode::SUCCESS), interval_max, latency, supervision_timeout)); - if (IsLeEventUnmasked(SubeventCode::CONNECTION_UPDATE_COMPLETE)) { + if (IsLeEventUnmasked(SubeventCode::LE_CONNECTION_UPDATE_COMPLETE)) { send_event_(bluetooth::hci::LeConnectionUpdateCompleteBuilder::Create( ErrorCode::SUCCESS, handle, interval_max, latency, supervision_timeout)); } diff --git a/tools/rootcanal/packets/hci_packets.pdl b/tools/rootcanal/packets/hci_packets.pdl index db7c51d294..23abb93b29 100644 --- a/tools/rootcanal/packets/hci_packets.pdl +++ b/tools/rootcanal/packets/hci_packets.pdl @@ -236,14 +236,14 @@ enum OpCode : 16 { // TESTING READ_LOOPBACK_MODE = 0x1801, WRITE_LOOPBACK_MODE = 0x1802, - ENABLE_DEVICE_UNDER_TEST_MODE = 0x1803, + ENABLE_IMPLEMENTATION_UNDER_TEST_MODE = 0x1803, WRITE_SIMPLE_PAIRING_DEBUG_MODE = 0x1804, WRITE_SECURE_CONNECTIONS_TEST_MODE = 0x180A, // LE_CONTROLLER LE_SET_EVENT_MASK = 0x2001, LE_READ_BUFFER_SIZE_V1 = 0x2002, - LE_READ_LOCAL_SUPPORTED_FEATURES = 0x2003, + LE_READ_LOCAL_SUPPORTED_FEATURES_PAGE_0 = 0x2003, LE_SET_RANDOM_ADDRESS = 0x2005, LE_SET_ADVERTISING_PARAMETERS = 0x2006, LE_READ_ADVERTISING_PHYSICAL_CHANNEL_TX_POWER = 0x2007, @@ -261,7 +261,7 @@ enum OpCode : 16 { LE_CONNECTION_UPDATE = 0x2013, LE_SET_HOST_CHANNEL_CLASSIFICATION = 0x2014, LE_READ_CHANNEL_MAP = 0x2015, - LE_READ_REMOTE_FEATURES = 0x2016, + LE_READ_REMOTE_FEATURES_PAGE_0 = 0x2016, LE_ENCRYPT = 0x2017, LE_RAND = 0x2018, LE_START_ENCRYPTION = 0x2019, @@ -293,7 +293,7 @@ enum OpCode : 16 { LE_RECEIVER_TEST_V2 = 0x2033, LE_TRANSMITTER_TEST_V2 = 0x2034, LE_SET_ADVERTISING_SET_RANDOM_ADDRESS = 0x2035, - LE_SET_EXTENDED_ADVERTISING_PARAMETERS = 0x2036, + LE_SET_EXTENDED_ADVERTISING_PARAMETERS_V1 = 0x2036, LE_SET_EXTENDED_ADVERTISING_DATA = 0x2037, LE_SET_EXTENDED_SCAN_RESPONSE_DATA = 0x2038, LE_SET_EXTENDED_ADVERTISING_ENABLE = 0x2039, @@ -301,12 +301,12 @@ enum OpCode : 16 { LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS = 0x203B, LE_REMOVE_ADVERTISING_SET = 0x203C, LE_CLEAR_ADVERTISING_SETS = 0x203D, - LE_SET_PERIODIC_ADVERTISING_PARAMETERS = 0x203E, + LE_SET_PERIODIC_ADVERTISING_PARAMETERS_V1 = 0x203E, LE_SET_PERIODIC_ADVERTISING_DATA = 0x203F, LE_SET_PERIODIC_ADVERTISING_ENABLE = 0x2040, LE_SET_EXTENDED_SCAN_PARAMETERS = 0x2041, LE_SET_EXTENDED_SCAN_ENABLE = 0x2042, - LE_EXTENDED_CREATE_CONNECTION = 0x2043, + LE_EXTENDED_CREATE_CONNECTION_V1 = 0x2043, LE_PERIODIC_ADVERTISING_CREATE_SYNC = 0x2044, LE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL = 0x2045, LE_PERIODIC_ADVERTISING_TERMINATE_SYNC = 0x2046, @@ -355,7 +355,7 @@ enum OpCode : 16 { LE_ISO_RECEIVE_TEST = 0x2071, LE_ISO_READ_TEST_COUNTERS = 0x2072, LE_ISO_TEST_END = 0x2073, - LE_SET_HOST_FEATURE = 0x2074, + LE_SET_HOST_FEATURE_V1 = 0x2074, LE_READ_ISO_LINK_QUALITY = 0x2075, LE_ENHANCED_READ_TRANSMIT_POWER_LEVEL = 0x2076, LE_READ_REMOTE_TRANSMIT_POWER_LEVEL = 0x2077, @@ -366,6 +366,36 @@ enum OpCode : 16 { LE_SET_DATA_RELATED_ADDRESS_CHANGES = 0x207C, LE_SET_DEFAULT_SUBRATE = 0x207D, LE_SUBRATE_REQUEST = 0x207E, + LE_SET_EXTENDED_ADVERTISING_PARAMETERS_V2 = 0x207F, + LE_SET_DECISION_DATA = 0x2080, + LE_SET_DECISION_INSTRUCTIONS = 0x2081, + LE_SET_PERIODIC_ADVERTISING_SUBEVENT_DATA = 0x2082, + LE_SET_PERIODIC_ADVERTISING_RESPONSE_DATA = 0x2083, + LE_SET_PERIODIC_SYNC_SUBEVENT = 0x2084, + LE_EXTENDED_CREATE_CONNECTION_V2 = 0x2085, + LE_SET_PERIODIC_ADVERTISING_PARAMETERS_V2 = 0x2086, + LE_READ_ALL_LOCAL_SUPPORTED_FEATURES = 0x2087, + LE_READ_ALL_REMOTE_FEATURES = 0x2088, + LE_CS_READ_LOCAL_SUPPORTED_CAPABILITIES = 0x2089, + LE_CS_READ_REMOTE_SUPPORTED_CAPABILITIES = 0x208A, + LE_CS_WRITE_CACHED_REMOTE_SUPPORTED_CAPABILITIES = 0x208B, + LE_CS_SECURITY_ENABLE = 0x208C, + LE_CS_SET_DEFAULT_SETTINGS = 0x208D, + LE_CS_READ_REMOTE_FAE_TABLE = 0x208E, + LE_CS_WRITE_CACHED_REMOTE_FAE_TABLE = 0x208F, + LE_CS_CREATE_CONFIG = 0x2090, + LE_CS_REMOVE_CONFIG = 0x0291, + LE_CS_SET_CHANNEL_CLASSIFICATION = 0x2092, + LE_CS_SET_PROCEDURE_PARAMETERS = 0x2093, + LE_CS_PROCEDURE_ENABLE = 0x2094, + LE_CS_TEST = 0x2095, + LE_CS_TEST_END = 0x2096, + LE_ADD_DEVICE_TO_MONITORED_ADVERTISERS_LIST = 0x2098, + LE_REMOVE_DEVICE_FROM_MONITORED_ADVERTISERS_LIST = 0x2099, + LE_CLEAR_MONITORED_ADVERTISERS_LIST = 0x209A, + LE_READ_MONITORED_ADVERTISERS_LIST_SIZE = 0x209B, + LE_ENABLE_MONITORING_ADVERTISERS = 0x209C, + LE_FRAME_SPACE_UPDATE = 0x209D, // VENDOR_SPECIFIC // MSFT_OPCODE_xxxx below is needed for the tests. @@ -466,6 +496,8 @@ enum OpCodeIndex : 16 { READ_CURRENT_IAC_LAP = 113, WRITE_CURRENT_IAC_LAP = 114, SET_AFH_HOST_CHANNEL_CLASSIFICATION = 121, + LE_CS_READ_REMOTE_FAE_TABLE = 122, + LE_CS_WRITE_CACHED_REMOTE_FAE_TABLE = 123, READ_INQUIRY_SCAN_TYPE = 124, WRITE_INQUIRY_SCAN_TYPE = 125, READ_INQUIRY_MODE = 126, @@ -487,10 +519,12 @@ enum OpCodeIndex : 16 { READ_CLOCK = 157, READ_LOOPBACK_MODE = 160, WRITE_LOOPBACK_MODE = 161, - ENABLE_DEVICE_UNDER_TEST_MODE = 162, + ENABLE_IMPLEMENTATION_UNDER_TEST_MODE = 162, SETUP_SYNCHRONOUS_CONNECTION = 163, ACCEPT_SYNCHRONOUS_CONNECTION = 164, REJECT_SYNCHRONOUS_CONNECTION = 165, + LE_CS_CREATE_CONFIG = 166, + LE_CS_REMOVE_CONFIG = 167, READ_EXTENDED_INQUIRY_RESPONSE = 170, WRITE_EXTENDED_INQUIRY_RESPONSE = 171, REFRESH_ENCRYPTION_KEY = 172, @@ -514,16 +548,23 @@ enum OpCodeIndex : 16 { SEND_KEYPRESS_NOTIFICATION = 202, IO_CAPABILITY_REQUEST_NEGATIVE_REPLY = 203, READ_ENCRYPTION_KEY_SIZE = 204, + LE_CS_READ_LOCAL_SUPPORTED_CAPABILITIES = 205, + LE_CS_READ_REMOTE_SUPPORTED_CAPABILITIES = 206, + LE_CS_WRITE_CACHED_REMOTE_SUPPORTED_CAPABILITIES = 207, SET_EVENT_MASK_PAGE_2 = 222, READ_FLOW_CONTROL_MODE = 230, WRITE_FLOW_CONTROL_MODE = 231, READ_DATA_BLOCK_SIZE = 232, + LE_CS_TEST = 233, + LE_CS_TEST_END = 234, READ_ENHANCED_TRANSMIT_POWER_LEVEL = 240, + LE_CS_SECURITY_ENABLE = 241, READ_LE_HOST_SUPPORT = 245, WRITE_LE_HOST_SUPPORT = 246, + LE_CS_SET_DEFAULT_SETTINGS = 247, LE_SET_EVENT_MASK = 250, LE_READ_BUFFER_SIZE_V1 = 251, - LE_READ_LOCAL_SUPPORTED_FEATURES = 252, + LE_READ_LOCAL_SUPPORTED_FEATURES_PAGE_0 = 252, LE_SET_RANDOM_ADDRESS = 254, LE_SET_ADVERTISING_PARAMETERS = 255, LE_READ_ADVERTISING_PHYSICAL_CHANNEL_TX_POWER = 256, @@ -541,7 +582,7 @@ enum OpCodeIndex : 16 { LE_CONNECTION_UPDATE = 272, LE_SET_HOST_CHANNEL_CLASSIFICATION = 273, LE_READ_CHANNEL_MAP = 274, - LE_READ_REMOTE_FEATURES = 275, + LE_READ_REMOTE_FEATURES_PAGE_0 = 275, LE_ENCRYPT = 276, LE_RAND = 277, LE_START_ENCRYPTION = 280, @@ -551,6 +592,10 @@ enum OpCodeIndex : 16 { LE_RECEIVER_TEST_V1 = 284, LE_TRANSMITTER_TEST_V1 = 285, LE_TEST_END = 286, + LE_ENABLE_MONITORING_ADVERTISERS = 287, + LE_CS_SET_CHANNEL_CLASSIFICATION = 290, + LE_CS_SET_PROCEDURE_PARAMETERS = 291, + LE_CS_PROCEDURE_ENABLE = 292, ENHANCED_SETUP_SYNCHRONOUS_CONNECTION = 293, ENHANCED_ACCEPT_SYNCHRONOUS_CONNECTION = 294, READ_LOCAL_SUPPORTED_CODECS_V1 = 295, @@ -606,7 +651,7 @@ enum OpCodeIndex : 16 { LE_RECEIVER_TEST_V2 = 357, LE_TRANSMITTER_TEST_V2 = 360, LE_SET_ADVERTISING_SET_RANDOM_ADDRESS = 361, - LE_SET_EXTENDED_ADVERTISING_PARAMETERS = 362, + LE_SET_EXTENDED_ADVERTISING_PARAMETERS_V1 = 362, LE_SET_EXTENDED_ADVERTISING_DATA = 363, LE_SET_EXTENDED_SCAN_RESPONSE_DATA = 364, LE_SET_EXTENDED_ADVERTISING_ENABLE = 365, @@ -614,12 +659,12 @@ enum OpCodeIndex : 16 { LE_READ_NUMBER_OF_SUPPORTED_ADVERTISING_SETS = 367, LE_REMOVE_ADVERTISING_SET = 370, LE_CLEAR_ADVERTISING_SETS = 371, - LE_SET_PERIODIC_ADVERTISING_PARAMETERS = 372, + LE_SET_PERIODIC_ADVERTISING_PARAMETERS_V1 = 372, LE_SET_PERIODIC_ADVERTISING_DATA = 373, LE_SET_PERIODIC_ADVERTISING_ENABLE = 374, LE_SET_EXTENDED_SCAN_PARAMETERS = 375, LE_SET_EXTENDED_SCAN_ENABLE = 376, - LE_EXTENDED_CREATE_CONNECTION = 377, + LE_EXTENDED_CREATE_CONNECTION_V1 = 377, LE_PERIODIC_ADVERTISING_CREATE_SYNC = 380, LE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL = 381, LE_PERIODIC_ADVERTISING_TERMINATE_SYNC = 382, @@ -669,7 +714,7 @@ enum OpCodeIndex : 16 { LE_ISO_RECEIVE_TEST = 436, LE_ISO_READ_TEST_COUNTERS = 437, LE_ISO_TEST_END = 440, - LE_SET_HOST_FEATURE = 441, + LE_SET_HOST_FEATURE_V1 = 441, LE_READ_ISO_LINK_QUALITY = 442, LE_ENHANCED_READ_TRANSMIT_POWER_LEVEL = 443, LE_READ_REMOTE_TRANSMIT_POWER_LEVEL = 444, @@ -686,6 +731,22 @@ enum OpCodeIndex : 16 { SET_MIN_ENCRYPTION_KEY_SIZE = 457, LE_SET_DEFAULT_SUBRATE = 460, LE_SUBRATE_REQUEST = 461, + LE_SET_EXTENDED_ADVERTISING_PARAMETERS_V2 = 462, + LE_SET_DECISION_DATA = 463, + LE_SET_DECISION_INSTRUCTIONS = 464, + LE_SET_PERIODIC_ADVERTISING_SUBEVENT_DATA = 465, + LE_SET_PERIODIC_ADVERTISING_RESPONSE_DATA = 466, + LE_SET_PERIODIC_SYNC_SUBEVENT = 467, + LE_EXTENDED_CREATE_CONNECTION_V2 = 470, + LE_SET_PERIODIC_ADVERTISING_PARAMETERS_V2 = 471, + LE_READ_ALL_LOCAL_SUPPORTED_FEATURES = 472, + LE_READ_ALL_REMOTE_FEATURES = 473, + LE_SET_HOST_FEATURE_V2 = 474, + LE_ADD_DEVICE_TO_MONITORED_ADVERTISERS_LIST = 475, + LE_REMOVE_DEVICE_FROM_MONITORED_ADVERTISERS_LIST = 476, + LE_CLEAR_MONITORED_ADVERTISERS_LIST = 477, + LE_READ_MONITORED_ADVERTISERS_LIST_SIZE = 480, + LE_FRAME_SPACE_UPDATE = 481, } packet Command { @@ -756,41 +817,59 @@ enum EventCode : 8 { // LE events enum SubeventCode : 8 { - CONNECTION_COMPLETE = 0x01, - ADVERTISING_REPORT = 0x02, - CONNECTION_UPDATE_COMPLETE = 0x03, - READ_REMOTE_FEATURES_COMPLETE = 0x04, - LONG_TERM_KEY_REQUEST = 0x05, - REMOTE_CONNECTION_PARAMETER_REQUEST = 0x06, - DATA_LENGTH_CHANGE = 0x07, - READ_LOCAL_P256_PUBLIC_KEY_COMPLETE = 0x08, - GENERATE_DHKEY_COMPLETE = 0x09, - ENHANCED_CONNECTION_COMPLETE = 0x0a, - DIRECTED_ADVERTISING_REPORT = 0x0b, - PHY_UPDATE_COMPLETE = 0x0c, - EXTENDED_ADVERTISING_REPORT = 0x0D, - PERIODIC_ADVERTISING_SYNC_ESTABLISHED = 0x0E, - PERIODIC_ADVERTISING_REPORT = 0x0F, - PERIODIC_ADVERTISING_SYNC_LOST = 0x10, - SCAN_TIMEOUT = 0x11, - ADVERTISING_SET_TERMINATED = 0x12, - SCAN_REQUEST_RECEIVED = 0x13, - CHANNEL_SELECTION_ALGORITHM = 0x14, - CONNECTIONLESS_IQ_REPORT = 0x15, - CONNECTION_IQ_REPORT = 0x16, - CTE_REQUEST_FAILED = 0x17, - PERIODIC_ADVERTISING_SYNC_TRANSFER_RECEIVED = 0x18, - CIS_ESTABLISHED = 0x19, - CIS_REQUEST = 0x1A, - CREATE_BIG_COMPLETE = 0x1B, - TERMINATE_BIG_COMPLETE = 0x1C, - BIG_SYNC_ESTABLISHED = 0x1D, - BIG_SYNC_LOST = 0x1E, - REQUEST_PEER_SCA_COMPLETE = 0x1F, - PATH_LOSS_THRESHOLD = 0x20, - TRANSMIT_POWER_REPORTING = 0x21, - BIG_INFO_ADVERTISING_REPORT = 0x22, + LE_CONNECTION_COMPLETE = 0x01, + LE_ADVERTISING_REPORT = 0x02, + LE_CONNECTION_UPDATE_COMPLETE = 0x03, + LE_READ_REMOTE_FEATURES_PAGE_0_COMPLETE = 0x04, + LE_LONG_TERM_KEY_REQUEST = 0x05, + LE_REMOTE_CONNECTION_PARAMETER_REQUEST = 0x06, + LE_DATA_LENGTH_CHANGE = 0x07, + LE_READ_LOCAL_P256_PUBLIC_KEY_COMPLETE = 0x08, + LE_GENERATE_DHKEY_COMPLETE = 0x09, + LE_ENHANCED_CONNECTION_COMPLETE_V1 = 0x0a, + LE_DIRECTED_ADVERTISING_REPORT = 0x0b, + LE_PHY_UPDATE_COMPLETE = 0x0c, + LE_EXTENDED_ADVERTISING_REPORT = 0x0D, + LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHED_V1 = 0x0E, + LE_PERIODIC_ADVERTISING_REPORT_V1 = 0x0F, + LE_PERIODIC_ADVERTISING_SYNC_LOST = 0x10, + LE_SCAN_TIMEOUT = 0x11, + LE_ADVERTISING_SET_TERMINATED = 0x12, + LE_SCAN_REQUEST_RECEIVED = 0x13, + LE_CHANNEL_SELECTION_ALGORITHM = 0x14, + LE_CONNECTIONLESS_IQ_REPORT = 0x15, + LE_CONNECTION_IQ_REPORT = 0x16, + LE_CTE_REQUEST_FAILED = 0x17, + LE_PERIODIC_ADVERTISING_SYNC_TRANSFER_RECEIVED_V1 = 0x18, + LE_CIS_ESTABLISHED_V1 = 0x19, + LE_CIS_REQUEST = 0x1A, + LE_CREATE_BIG_COMPLETE = 0x1B, + LE_TERMINATE_BIG_COMPLETE = 0x1C, + LE_BIG_SYNC_ESTABLISHED = 0x1D, + LE_BIG_SYNC_LOST = 0x1E, + LE_REQUEST_PEER_SCA_COMPLETE = 0x1F, + LE_PATH_LOSS_THRESHOLD = 0x20, + LE_TRANSMIT_POWER_REPORTING = 0x21, + LE_BIG_INFO_ADVERTISING_REPORT = 0x22, LE_SUBRATE_CHANGE = 0x23, + LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHED_V2 = 0x24, + LE_PERIODIC_ADVERTISING_REPORT_V2 = 0x25, + LE_PERIODIC_ADVERTISING_SYNC_TRANSFER_RECEIVED_V2 = 0x26, + LE_PERIODIC_ADVERTISING_SUBEVENT_DATA_REQUEST = 0x27, + LE_PERIODIC_ADVERTISING_RESPONSE_REPORT = 0x28, + LE_ENHANCED_CONNECTION_COMPLETE_V2 = 0x29, + LE_CIS_ESTABLISHED_V2 = 0x2A, + LE_READ_ALL_REMOTE_FEATURES_COMPLETE = 0x2B, + LE_CS_READ_REMOTE_SUPPORTED_CAPABILITIES_COMPLETE = 0x2C, + LE_CS_READ_REMOTE_FAE_TABLE_COMPLETE = 0x2D, + LE_CS_SECURITY_ENABLE_COMPLETE = 0x2E, + LE_CS_CONFIG_COMPLETE = 0x2F, + LE_CS_PROCEDURE_ENABLE_COMPLETE = 0x30, + LE_CS_SUBEVENT_RESULT = 0x31, + LE_CS_SUBEVENT_RESULT_CONTINUE = 0x32, + LE_CS_TEST_END_COMPLETE = 0x33, + LE_MONITORED_ADVERTISERS_REPORT = 0x34, + LE_FRAME_SPACE_UPDATE_COMPLETE = 0x35, } // Vendor specific events @@ -808,6 +887,11 @@ packet Event { _payload_, } +packet LeMetaEvent : Event (event_code = LE_META_EVENT) { + subevent_code : SubeventCode, + _body_, +} + // Common definitions for commands and events enum FeatureFlag : 1 { @@ -2590,6 +2674,7 @@ enum HciVersion : 8 { V_5_2 = 0x0b, V_5_3 = 0x0c, V_5_4 = 0x0d, + V_6_0 = 0x0e, } enum LmpVersion : 8 { @@ -2607,6 +2692,7 @@ enum LmpVersion : 8 { V_5_2 = 0x0b, V_5_3 = 0x0c, V_5_4 = 0x0d, + V_6_0 = 0x0e, } struct LocalVersionInformation { @@ -3015,10 +3101,10 @@ packet WriteLoopbackModeComplete : CommandComplete (command_op_code = WRITE_LOOP status : ErrorCode, } -packet EnableDeviceUnderTestMode : Command (op_code = ENABLE_DEVICE_UNDER_TEST_MODE) { +packet EnableImplementationUnderTestMode : Command (op_code = ENABLE_IMPLEMENTATION_UNDER_TEST_MODE) { } -packet EnableDeviceUnderTestModeComplete : CommandComplete (command_op_code = ENABLE_DEVICE_UNDER_TEST_MODE) { +packet EnableImplementationUnderTestModeComplete : CommandComplete (command_op_code = ENABLE_IMPLEMENTATION_UNDER_TEST_MODE) { status : ErrorCode, } @@ -3071,66 +3157,86 @@ test LeReadBufferSizeV1Complete { "\x0e\x07\x01\x02\x20\x00\xfb\x00\x10", } +/// Core Specification Vol 6, Part B 4.6 § Feature support enum LLFeaturesBits : 64 { // Byte 0 - LE_ENCRYPTION = 0x0000000000000001, - CONNECTION_PARAMETERS_REQUEST_PROCEDURE = 0x0000000000000002, - EXTENDED_REJECT_INDICATION = 0x0000000000000004, - PERIPHERAL_INITIATED_FEATURES_EXCHANGE = 0x0000000000000008, - LE_PING = 0x0000000000000010, - LE_DATA_PACKET_LENGTH_EXTENSION = 0x0000000000000020, - LL_PRIVACY = 0x0000000000000040, - EXTENDED_SCANNER_FILTER_POLICIES = 0x0000000000000080, + LE_ENCRYPTION = 0x0000000000000001, + CONNECTION_PARAMETERS_REQUEST_PROCEDURE = 0x0000000000000002, + EXTENDED_REJECT_INDICATION = 0x0000000000000004, + PERIPHERAL_INITIATED_FEATURES_EXCHANGE = 0x0000000000000008, + LE_PING = 0x0000000000000010, + LE_DATA_PACKET_LENGTH_EXTENSION = 0x0000000000000020, + LL_PRIVACY = 0x0000000000000040, + EXTENDED_SCANNER_FILTER_POLICIES = 0x0000000000000080, // Byte 1 - LE_2M_PHY = 0x0000000000000100, - STABLE_MODULATION_INDEX_TRANSMITTER = 0x0000000000000200, - STABLE_MODULATION_INDEX_RECEIVER = 0x0000000000000400, - LE_CODED_PHY = 0x0000000000000800, - LE_EXTENDED_ADVERTISING = 0x0000000000001000, - LE_PERIODIC_ADVERTISING = 0x0000000000002000, - CHANNEL_SELECTION_ALGORITHM_2 = 0x0000000000004000, - LE_POWER_CLASS_1 = 0x0000000000008000, + LE_2M_PHY = 0x0000000000000100, + STABLE_MODULATION_INDEX_TRANSMITTER = 0x0000000000000200, + STABLE_MODULATION_INDEX_RECEIVER = 0x0000000000000400, + LE_CODED_PHY = 0x0000000000000800, + LE_EXTENDED_ADVERTISING = 0x0000000000001000, + LE_PERIODIC_ADVERTISING = 0x0000000000002000, + CHANNEL_SELECTION_ALGORITHM_2 = 0x0000000000004000, + LE_POWER_CLASS_1 = 0x0000000000008000, // Byte 2 - MINIMUM_NUMBER_OF_USED_CHANNELS_PROCEDURE = 0x0000000000010000, - CONNECTION_CTE_REQUEST = 0x0000000000020000, - CONNECTION_CTE_RESPONSE = 0x0000000000040000, - CONNECTIONLESS_CTE_TRANSMITTER = 0x0000000000080000, - CONNECTIONLESS_CTE_RECEIVER = 0x0000000000100000, - ANTENNA_SWITCHING_DURING_CTE_TRANSMISSION = 0x0000000000200000, - ANTENNA_SWITCHING_DURING_CTE_RECEPTION = 0x0000000000400000, - RECEIVING_CONSTANT_TONE_EXTENSIONS = 0x0000000000800000, + MINIMUM_NUMBER_OF_USED_CHANNELS_PROCEDURE = 0x0000000000010000, + CONNECTION_CTE_REQUEST = 0x0000000000020000, + CONNECTION_CTE_RESPONSE = 0x0000000000040000, + CONNECTIONLESS_CTE_TRANSMITTER = 0x0000000000080000, + CONNECTIONLESS_CTE_RECEIVER = 0x0000000000100000, + ANTENNA_SWITCHING_DURING_CTE_TRANSMISSION = 0x0000000000200000, + ANTENNA_SWITCHING_DURING_CTE_RECEPTION = 0x0000000000400000, + RECEIVING_CONSTANT_TONE_EXTENSIONS = 0x0000000000800000, // Byte 3 - PERIODIC_ADVERTISING_SYNC_TRANSFER_SENDER = 0x0000000001000000, - PERIODIC_ADVERTISING_SYNC_TRANSFER_RECIPIENT = 0x0000000002000000, - SLEEP_CLOCK_ACCURACY_UPDATES = 0x0000000004000000, - REMOTE_PUBLIC_KEY_VALIDATION = 0x0000000008000000, - CONNECTED_ISOCHRONOUS_STREAM_CENTRAL = 0x0000000010000000, - CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL = 0x0000000020000000, - ISOCHRONOUS_BROADCASTER = 0x0000000040000000, - SYNCHRONIZED_RECEIVER = 0x0000000080000000, + PERIODIC_ADVERTISING_SYNC_TRANSFER_SENDER = 0x0000000001000000, + PERIODIC_ADVERTISING_SYNC_TRANSFER_RECIPIENT = 0x0000000002000000, + SLEEP_CLOCK_ACCURACY_UPDATES = 0x0000000004000000, + REMOTE_PUBLIC_KEY_VALIDATION = 0x0000000008000000, + CONNECTED_ISOCHRONOUS_STREAM_CENTRAL = 0x0000000010000000, + CONNECTED_ISOCHRONOUS_STREAM_PERIPHERAL = 0x0000000020000000, + ISOCHRONOUS_BROADCASTER = 0x0000000040000000, + SYNCHRONIZED_RECEIVER = 0x0000000080000000, // Byte 4 - CONNECTED_ISOCHRONOUS_STREAM_HOST_SUPPORT = 0x0000000100000000, - LE_POWER_CONTROL_REQUEST = 0x0000000200000000, - LE_POWER_CONTROL_REQUEST_BIS = 0x0000000400000000, - LE_PATH_LOSS_MONITORING = 0x0000000800000000, - PERIODIC_ADVERTISING_ADI_SUPPORT = 0x0000001000000000, - CONNECTION_SUBRATING = 0x0000002000000000, - CONNECTION_SUBRATING_HOST_SUPPORT = 0x0000004000000000, - CHANNEL_CLASSIFICATION = 0x0000008000000000, + CONNECTED_ISOCHRONOUS_STREAM_HOST_SUPPORT = 0x0000000100000000, + LE_POWER_CONTROL_REQUEST = 0x0000000200000000, + LE_POWER_CONTROL_REQUEST_BIS = 0x0000000400000000, + LE_PATH_LOSS_MONITORING = 0x0000000800000000, + PERIODIC_ADVERTISING_ADI_SUPPORT = 0x0000001000000000, + CONNECTION_SUBRATING = 0x0000002000000000, + CONNECTION_SUBRATING_HOST_SUPPORT = 0x0000004000000000, + CHANNEL_CLASSIFICATION = 0x0000008000000000, + + // Byte 5 + ADVERTISING_CODING_SELECTION = 0x0000010000000000, + ADVERTISING_CODING_SELECTION_HOST_SUPPORT = 0x0000020000000000, + DECISION_BASED_ADVERTISING_FILTERING = 0x0000040000000000, + PERIODIC_ADVERTISING_WITH_RESPONSES_ADVERTISER = 0x0000080000000000, + PERIODIC_ADVERTISING_WITH_RESPONSES_SCANNER = 0x0000100000000000, + UNSEGMENTED_FRAMED_MODE = 0x0000200000000000, + CHANNEL_SOUNDING = 0x0000400000000000, + CHANNEL_SOUNDING_HOST_SUPPORT = 0x0000800000000000, } -packet LeReadLocalSupportedFeatures : Command (op_code = LE_READ_LOCAL_SUPPORTED_FEATURES) { +packet LeReadLocalSupportedFeaturesPage0 : Command (op_code = LE_READ_LOCAL_SUPPORTED_FEATURES_PAGE_0) { } -packet LeReadLocalSupportedFeaturesComplete : CommandComplete (command_op_code = LE_READ_LOCAL_SUPPORTED_FEATURES) { +packet LeReadLocalSupportedFeaturesPage0Complete : CommandComplete (command_op_code = LE_READ_LOCAL_SUPPORTED_FEATURES_PAGE_0) { status : ErrorCode, le_features : 64, } +packet LeReadAllLocalSupportedFeatures : Command (op_code = LE_READ_ALL_LOCAL_SUPPORTED_FEATURES) { +} + +packet LeReadAllLocalSupportedFeaturesComplete : CommandComplete (command_op_code = LE_READ_ALL_LOCAL_SUPPORTED_FEATURES) { + status : ErrorCode, + max_page : 8, + le_features : 8[248], +} + packet LeSetRandomAddress : Command (op_code = LE_SET_RANDOM_ADDRESS) { random_address : Address, } @@ -3268,7 +3374,9 @@ packet LeSetScanEnableComplete : CommandComplete (command_op_code = LE_SET_SCAN_ enum InitiatorFilterPolicy : 8 { USE_PEER_ADDRESS = 0x00, - USE_FILTER_ACCEPT_LIST = 0x01, + USE_FILTER_ACCEPT_LIST_WITH_PEER_ADDRESS = 0x01, + USE_DECISION_PDUS = 0x02, + USE_FILTER_ACCEPT_LIST_WITH_DECISION_PDUS = 0x03, } packet LeCreateConnection : Command (op_code = LE_CREATE_CONNECTION) { @@ -3375,12 +3483,37 @@ packet LeReadChannelMapComplete : CommandComplete (command_op_code = LE_READ_CHA channel_map : 8[5], } -packet LeReadRemoteFeatures : Command (op_code = LE_READ_REMOTE_FEATURES) { +packet LeReadRemoteFeaturesPage0 : Command (op_code = LE_READ_REMOTE_FEATURES_PAGE_0) { connection_handle : 12, _reserved_ : 4, } -packet LeReadRemoteFeaturesStatus : CommandStatus (command_op_code = LE_READ_REMOTE_FEATURES) { +packet LeReadRemoteFeaturesPage0Status : CommandStatus (command_op_code = LE_READ_REMOTE_FEATURES_PAGE_0) { +} + +packet LeReadRemoteFeaturesPage0Complete : LeMetaEvent (subevent_code = LE_READ_REMOTE_FEATURES_PAGE_0_COMPLETE) { + status : ErrorCode, + connection_handle : 12, + _reserved_ : 4, + le_features : 64, +} + +packet LeReadAllRemoteFeatures : Command (op_code = LE_READ_ALL_REMOTE_FEATURES) { + connection_handle : 12, + _reserved_ : 4, + pages_requested : 8, +} + +packet LeReadAllRemoteFeaturesStatus : CommandStatus (command_op_code = LE_READ_ALL_REMOTE_FEATURES) { +} + +packet LeReadAllRemoteFeaturesComplete : LeMetaEvent (subevent_code = LE_READ_ALL_REMOTE_FEATURES_COMPLETE) { + status : ErrorCode, + connection_handle : 12, + _reserved_ : 4, + max_remote_page : 8, + max_valid_page : 8, + le_features : 8[248], } packet LeEncrypt : Command (op_code = LE_ENCRYPT) { @@ -3743,6 +3876,20 @@ enum LegacyAdvertisingEventProperties : 4 { ADV_NONCONN_IND = 0, } +struct AdvertisingEventProperties { + connectable : 1, + scannable : 1, + directed : 1, + high_duty_cycle : 1, + legacy : 1, + anonymous : 1, + include_tx_power : 1, + decision : 1, + include_adva : 1, + include_adi : 1, + _reserved_ : 6, +} + enum PrimaryPhyType : 8 { LE_1M = 0x01, LE_CODED = 0x03, @@ -3755,11 +3902,17 @@ enum SecondaryPhyType : 8 { LE_CODED = 0x03, } -packet LeSetExtendedAdvertisingParametersLegacy : Command (op_code = LE_SET_EXTENDED_ADVERTISING_PARAMETERS) { +enum AdvertisingPhyOptions : 8 { + NO_PREFERENCE = 0x00, + S2_CODING_PREFERRED = 0x01, + S8_CODING_PREFERRED = 0x02, + S2_CODING_REQUIRED = 0x03, + S8_CODING_REQUIRED = 0x04, +} + +packet LeSetExtendedAdvertisingParametersV1 : Command (op_code = LE_SET_EXTENDED_ADVERTISING_PARAMETERS_V1) { advertising_handle : 8, - legacy_advertising_event_properties : LegacyAdvertisingEventProperties, - _fixed_ = 0x1 : 1, // legacy bit set - _reserved_ : 11, // advertising_event_properties reserved bits + advertising_event_properties : AdvertisingEventProperties, primary_advertising_interval_min : 24, // 0x20 - 0xFFFFFF N * 0.625 ms primary_advertising_interval_max : 24, // 0x20 - 0xFFFFFF N * 0.625 ms primary_advertising_channel_map : 3, // bit 0 - Channel 37, bit 1 - 38, bit 2 - 39 @@ -3770,30 +3923,24 @@ packet LeSetExtendedAdvertisingParametersLegacy : Command (op_code = LE_SET_EXTE advertising_filter_policy : AdvertisingFilterPolicy, _reserved_ : 6, advertising_tx_power : 8, // -127 to +20, 0x7F - no preference - _fixed_ = 0x1 : 8, // PrimaryPhyType LE_1M - _reserved_ : 8, // secondary_advertising_max_skip - _fixed_ = 0x1 : 8, // secondary_advertising_phy LE_1M + primary_advertising_phy : PrimaryPhyType, + secondary_advertising_max_skip : 8, // 1 to 255, 0x00 - AUX_ADV_IND sent before next advertising event + secondary_advertising_phy : SecondaryPhyType, advertising_sid : 8, // SID subfield from the ADI field of the PDU scan_request_notification_enable : Enable, } -test LeSetExtendedAdvertisingParametersLegacy { - "\x36\x20\x19\x00\x13\x00\x90\x01\x00\xc2\x01\x00\x07\x01\x00\x00\x00\x00\x00\x00\x00\x00\xf9\x01\x00\x01\x01\x00", - "\x36\x20\x19\x01\x13\x00\x90\x01\x00\xc2\x01\x00\x07\x01\x00\x00\x00\x00\x00\x00\x00\x00\xf9\x01\x00\x01\x01\x00", +packet LeSetExtendedAdvertisingParametersV1Complete : CommandComplete (command_op_code = LE_SET_EXTENDED_ADVERTISING_PARAMETERS_V1) { + status : ErrorCode, + selected_tx_power : 8, // -127 to +20 } -struct AdvertisingEventProperties { - connectable : 1, - scannable : 1, - directed : 1, - high_duty_cycle : 1, - legacy : 1, - anonymous : 1, - tx_power : 1, - _reserved_ : 9, +test LeSetExtendedAdvertisingParametersV1 { + "\x36\x20\x19\x00\x13\x00\x90\x01\x00\xc2\x01\x00\x07\x01\x00\x00\x00\x00\x00\x00\x00\x00\xf9\x01\x00\x01\x01\x00", + "\x36\x20\x19\x01\x13\x00\x90\x01\x00\xc2\x01\x00\x07\x01\x00\x00\x00\x00\x00\x00\x00\x00\xf9\x01\x00\x01\x01\x00", } -packet LeSetExtendedAdvertisingParameters : Command (op_code = LE_SET_EXTENDED_ADVERTISING_PARAMETERS) { +packet LeSetExtendedAdvertisingParametersV2 : Command (op_code = LE_SET_EXTENDED_ADVERTISING_PARAMETERS_V2) { advertising_handle : 8, advertising_event_properties : AdvertisingEventProperties, primary_advertising_interval_min : 24, // 0x20 - 0xFFFFFF N * 0.625 ms @@ -3811,9 +3958,11 @@ packet LeSetExtendedAdvertisingParameters : Command (op_code = LE_SET_EXTENDED_A secondary_advertising_phy : SecondaryPhyType, advertising_sid : 8, // SID subfield from the ADI field of the PDU scan_request_notification_enable : Enable, + primary_advertising_phy_options : AdvertisingPhyOptions, + secondary_advertising_phy_options : AdvertisingPhyOptions, } -packet LeSetExtendedAdvertisingParametersComplete : CommandComplete (command_op_code = LE_SET_EXTENDED_ADVERTISING_PARAMETERS) { +packet LeSetExtendedAdvertisingParametersV2Complete : CommandComplete (command_op_code = LE_SET_EXTENDED_ADVERTISING_PARAMETERS_V2) { status : ErrorCode, selected_tx_power : 8, // -127 to +20 } @@ -3951,7 +4100,7 @@ packet LeClearAdvertisingSetsComplete : CommandComplete (command_op_code = LE_CL status : ErrorCode, } -packet LeSetPeriodicAdvertisingParameters : Command (op_code = LE_SET_PERIODIC_ADVERTISING_PARAMETERS) { +packet LeSetPeriodicAdvertisingParametersV1 : Command (op_code = LE_SET_PERIODIC_ADVERTISING_PARAMETERS_V1) { advertising_handle : 8, periodic_advertising_interval_min : 16, // 0x006 to 0xFFFF (7.5 ms to 82s) periodic_advertising_interval_max : 16, // 0x006 to 0xFFFF (7.5 ms to 82s) @@ -3960,7 +4109,26 @@ packet LeSetPeriodicAdvertisingParameters : Command (op_code = LE_SET_PERIODIC_A _reserved_ : 9, } -packet LeSetPeriodicAdvertisingParametersComplete : CommandComplete (command_op_code = LE_SET_PERIODIC_ADVERTISING_PARAMETERS) { +packet LeSetPeriodicAdvertisingParametersV1Complete : CommandComplete (command_op_code = LE_SET_PERIODIC_ADVERTISING_PARAMETERS_V1) { + status : ErrorCode, +} + +packet LeSetPeriodicAdvertisingParametersV2 : Command (op_code = LE_SET_PERIODIC_ADVERTISING_PARAMETERS_V2) { + advertising_handle : 8, + periodic_advertising_interval_min : 16, // 0x006 to 0xFFFF (7.5 ms to 82s) + periodic_advertising_interval_max : 16, // 0x006 to 0xFFFF (7.5 ms to 82s) + _reserved_ : 6, + include_tx_power : 1, + _reserved_ : 9, + num_subevents : 8, // 0x00 disabled, 0x01 to 0x80 + subevent_interval : 8, // 0x06 to 0xFF × 1.25 ms + response_slot_delay : 8, // 0x01 to 0xFE × 1.25 ms + response_slot_spacing : 8, // 0x02 to 0xFF × 1.25 ms + num_response_slots : 8, +} + +packet LeSetPeriodicAdvertisingParametersV2Complete : CommandComplete (command_op_code = LE_SET_PERIODIC_ADVERTISING_PARAMETERS_V2) { + advertising_handle : 8, status : ErrorCode, } @@ -4050,7 +4218,7 @@ struct InitiatingPhyParameters { max_ce_length : 16, // 0.625ms } -packet LeExtendedCreateConnection : Command (op_code = LE_EXTENDED_CREATE_CONNECTION) { +packet LeExtendedCreateConnectionV1 : Command (op_code = LE_EXTENDED_CREATE_CONNECTION_V1) { initiator_filter_policy : InitiatorFilterPolicy, own_address_type : OwnAddressType, peer_address_type : PeerAddressType, @@ -4063,7 +4231,21 @@ test LeExtendedCreateConnection { "\x43\x20\x2a\x01\x01\x00\x00\x00\x00\x00\x00\x00\x03\x00\x08\x30\x00\x18\x00\x28\x00\x00\x00\xf4\x01\x00\x00\x00\x00\x00\x08\x30\x00\x18\x00\x28\x00\x00\x00\xf4\x01\x00\x00\x00\x00", } -packet LeExtendedCreateConnectionStatus : CommandStatus (command_op_code = LE_EXTENDED_CREATE_CONNECTION) { +packet LeExtendedCreateConnectionV1Status : CommandStatus (command_op_code = LE_EXTENDED_CREATE_CONNECTION_V1) { +} + +packet LeExtendedCreateConnectionV2 : Command (op_code = LE_EXTENDED_CREATE_CONNECTION_V2) { + advertising_handle : 8, + subevent : 8, + initiator_filter_policy : InitiatorFilterPolicy, + own_address_type : OwnAddressType, + peer_address_type : PeerAddressType, + peer_address : Address, + initiating_phys : 8, + initiating_phy_parameters : InitiatingPhyParameters[], +} + +packet LeExtendedCreateConnectionV2Status : CommandStatus (command_op_code = LE_EXTENDED_CREATE_CONNECTION_V2) { } enum PeriodicSyncCteType : 8 { @@ -4546,12 +4728,12 @@ enum LeHostFeatureBits : 8 { CONNECTION_SUBRATING_HOST_SUPPORT = 38, } -packet LeSetHostFeature : Command (op_code = LE_SET_HOST_FEATURE) { +packet LeSetHostFeatureV1 : Command (op_code = LE_SET_HOST_FEATURE_V1) { bit_number : LeHostFeatureBits, bit_value: Enable, } -packet LeSetHostFeatureComplete : CommandComplete (command_op_code = LE_SET_HOST_FEATURE) { +packet LeSetHostFeatureV1Complete : CommandComplete (command_op_code = LE_SET_HOST_FEATURE_V1) { status : ErrorCode, } @@ -4689,6 +4871,501 @@ packet LeSubrateRequest : Command (op_code = LE_SUBRATE_REQUEST) { packet LeSubrateRequestStatus : CommandStatus (command_op_code = LE_SUBRATE_REQUEST) { } +packet LeCsReadLocalSupportedCapabilities : Command (op_code = LE_CS_READ_LOCAL_SUPPORTED_CAPABILITIES) { +} + +struct CsRolesSupported { + initiator : 1, + reflector : 1, + _reserved_ : 6, +} + +struct CsModesSupported { + mode_3 : 1, + _reserved_ : 7, +} + +struct CsRttCapability { + rtt_aa_only_n : 1, + rtt_sounding_n : 1, + rtt_random_payload_n : 1, + _reserved_ : 5, +} + +struct CsNadmSoundingCapability { + normalized_attack_detector_metric : 1, + _reserved_ : 15, +} + +struct CsNadmRandomCapability { + normalized_attack_detector_metric : 1, + _reserved_ : 15, +} + +struct CsSyncPhysSupported { + le_2m_phy : 1, + le_2m_2bt_phy : 1, + _reserved_ : 6, +} + +struct CsSubfeaturesSupported { + companion_signal : 1, + frequency_actuation_error : 1, + channel_selection_algorithm : 1, + phase_based_ranging : 1, + _reserved_ : 12, +} + +struct CsTIp1TimesSupported { + support_10_microsecond : 1, + support_20_microsecond : 1, + support_30_microsecond : 1, + support_40_microsecond : 1, + support_50_microsecond : 1, + support_60_microsecond : 1, + support_80_microsecond : 1, + _reserved_ : 9, +} + +struct CsTIp2TimesSupported { + support_10_microsecond : 1, + support_20_microsecond : 1, + support_30_microsecond : 1, + support_40_microsecond : 1, + support_50_microsecond : 1, + support_60_microsecond : 1, + support_80_microsecond : 1, + _reserved_ : 9, +} + +struct CsTFcsTimesSupported { + support_15_microsecond : 1, + support_20_microsecond : 1, + support_30_microsecond : 1, + support_40_microsecond : 1, + support_50_microsecond : 1, + support_60_microsecond : 1, + support_80_microsecond : 1, + support_100_microsecond : 1, + support_120_microsecond : 1, + _reserved_ : 7, +} + +struct CsTPmTimesSupported { + support_10_microsecond : 1, + support_20_microsecond : 1, + _reserved_ : 14, +} + +struct CsTxSnrCapability { + support_18db : 1, + support_21db : 1, + support_24db : 1, + support_27db : 1, + support_30db : 1, + _reserved_ : 3, +} + +packet LeCsReadLocalSupportedCapabilitiesComplete : CommandComplete (command_op_code = LE_CS_READ_LOCAL_SUPPORTED_CAPABILITIES) { + status : ErrorCode, + num_config_supported : 8, + max_consecutive_procedures_supported : 16, + num_antennas_supported : 8, + max_antenna_paths_supported : 8, + roles_supported : CsRolesSupported, + modes_supported : CsModesSupported, + rtt_capability : CsRttCapability, + rtt_aa_only_n : 8, + rtt_sounding_n : 8, + rtt_random_payload_n : 8, + nadm_sounding_capability : CsNadmSoundingCapability, + nadm_random_capability : CsNadmRandomCapability, + cs_sync_phys_supported : CsSyncPhysSupported, + subfeatures_supported : CsSubfeaturesSupported, + t_ip1_times_supported : CsTIp1TimesSupported, + t_ip2_times_supported : CsTIp2TimesSupported, + t_fcs_times_supported : CsTFcsTimesSupported, + t_pm_times_supported : CsTPmTimesSupported, + t_sw_time_supported : 8, + tx_snr_capability : CsTxSnrCapability, +} + +packet LeCsReadRemoteSupportedCapabilities : Command (op_code = LE_CS_READ_REMOTE_SUPPORTED_CAPABILITIES) { + connection_handle: 12, + _reserved_ : 4, +} + +packet LeCsReadRemoteSupportedCapabilitiesStatus : CommandStatus (command_op_code = LE_CS_READ_REMOTE_SUPPORTED_CAPABILITIES) { +} + +packet LeCsReadRemoteSupportedCapabilitiesComplete : LeMetaEvent (subevent_code = LE_CS_READ_REMOTE_SUPPORTED_CAPABILITIES_COMPLETE) { + status : ErrorCode, + connection_handle : 12, + _reserved_ : 4, + num_config_supported : 8, + max_consecutive_procedures_supported : 16, + num_antennas_supported : 8, + max_antenna_paths_supported : 8, + roles_supported : CsRolesSupported, + modes_supported : CsModesSupported, + rtt_capability : CsRttCapability, + rtt_aa_only_n : 8, + rtt_sounding_n : 8, + rtt_random_payload_n : 8, + nadm_sounding_capability : CsNadmSoundingCapability, + nadm_random_capability : CsNadmRandomCapability, + cs_sync_phys_supported : CsSyncPhysSupported, + subfeatures_supported : CsSubfeaturesSupported, + t_ip1_times_supported : CsTIp1TimesSupported, + t_ip2_times_supported : CsTIp2TimesSupported, + t_fcs_times_supported : CsTFcsTimesSupported, + t_pm_times_supported : CsTPmTimesSupported, + t_sw_time_supported : 8, + tx_snr_capability : CsTxSnrCapability, +} + +packet LeCsWriteCachedRemoteSupportedCapabilities : Command (op_code = LE_CS_WRITE_CACHED_REMOTE_SUPPORTED_CAPABILITIES) { + connection_handle: 12, + _reserved_ : 4, + num_config_supported : 8, + max_consecutive_procedures_supported : 16, + num_antennas_supported : 8, + max_antenna_paths_supported : 8, + roles_supported : CsRolesSupported, + modes_supported : CsModesSupported, + rtt_capability : CsRttCapability, + rtt_aa_only_n : 8, + rtt_sounding_n : 8, + rtt_random_payload_n : 8, + nadm_sounding_capability : CsNadmSoundingCapability, + nadm_random_capability : CsNadmRandomCapability, + cs_sync_phys_supported : CsSyncPhysSupported, + subfeatures_supported : CsSubfeaturesSupported, + t_ip1_times_supported : CsTIp1TimesSupported, + t_ip2_times_supported : CsTIp2TimesSupported, + t_fcs_times_supported : CsTFcsTimesSupported, + t_pm_times_supported : CsTPmTimesSupported, + t_sw_time_supported : 8, + tx_snr_capability : CsTxSnrCapability, +} + +packet LeCsWriteCachedRemoteSupportedCapabilitiesComplete : CommandComplete (command_op_code = LE_CS_WRITE_CACHED_REMOTE_SUPPORTED_CAPABILITIES) { + status : ErrorCode, + connection_handle: 12, + _reserved_ : 4, +} + +packet LeCsSecurityEnable : Command (op_code = LE_CS_SECURITY_ENABLE) { + connection_handle: 12, + _reserved_ : 4, +} + +packet LeCsSecurityEnableStatus : CommandStatus (command_op_code = LE_CS_SECURITY_ENABLE) { +} + +packet LeCsSecurityEnableComplete : LeMetaEvent (subevent_code = LE_CS_SECURITY_ENABLE_COMPLETE) { + status : ErrorCode, + connection_handle : 12, + _reserved_ : 4, +} + +struct CsRoleEnable { + initiator : 1, + reflector : 1, + _reserved_ : 6, +} + +enum CsSyncAntennaSelection : 8 { + ANTENNA_1 = 0x01, + ANTENNA_2 = 0x02, + ANTENNA_3 = 0x03, + ANTENNA_4 = 0x04, + ANTENNAS_IN_ORDER = 0xFE, + NO_RECOMMENDATION = 0xFF, +} + +packet LeCsSetDefaultSettings : Command (op_code = LE_CS_SET_DEFAULT_SETTINGS) { + connection_handle: 12, + _reserved_ : 4, + role_enable : CsRoleEnable, + cs_sync_antenna_selection : CsSyncAntennaSelection, + max_tx_power : 8, +} + +packet LeCsSetDefaultSettingsComplete : CommandComplete (command_op_code = LE_CS_SET_DEFAULT_SETTINGS) { + status : ErrorCode, + connection_handle: 12, + _reserved_ : 4, +} + +packet LeCsReadRemoteFaeTable : Command (op_code = LE_CS_READ_REMOTE_FAE_TABLE) { + connection_handle: 12, + _reserved_ : 4, +} + +packet LeCsReadRemoteFaeTableStatus : CommandStatus (command_op_code = LE_CS_READ_REMOTE_FAE_TABLE) { +} + +packet LeCsReadRemoteFaeTableComplete : LeMetaEvent (subevent_code = LE_CS_READ_REMOTE_FAE_TABLE_COMPLETE) { + status : ErrorCode, + connection_handle : 12, + _reserved_ : 4, + remote_fae_table : 8[72], +} + +packet LeCsWriteCachedRemoteFaeTable : Command (op_code = LE_CS_WRITE_CACHED_REMOTE_FAE_TABLE) { + connection_handle: 12, + _reserved_ : 4, + remote_fae_table : 8[72], +} + +packet LeCsWriteCachedRemoteFaeTableComplete : CommandComplete (command_op_code = LE_CS_WRITE_CACHED_REMOTE_FAE_TABLE) { + status : ErrorCode, + connection_handle: 12, + _reserved_ : 4, +} + +enum CsCreateContext: 8 { + LOCAL_CONTROLLER_ONLY = 0x00, + BOTH_LOCAL_AND_REMOTE_CONTROLLER = 0x01, +} + +enum CsMainModeType: 8 { + MODE_1 = 0x01, + MODE_2 = 0x02, + MODE_3 = 0x03, +} + +enum CsSubModeType: 8 { + MODE_1 = 0x01, + MODE_2 = 0x02, + MODE_3 = 0x03, + UNUSED = 0xff, +} + +enum CsRole : 8 { + INITIATOR = 0x00, + REFLECTOR = 0x01, +} + +enum CsRttType : 8 { + RTT_AA_ONLY = 0x00, + RTT_WITH_32_BIT_SOUNDING_SEQUENCE = 0x01, + RTT_WITH_96_BIT_SOUNDING_SEQUENCE = 0x02, + RTT_WITH_32_BIT_RANDOM_SEQUENCE = 0x03, + RTT_WITH_64_BIT_RANDOM_SEQUENCE = 0x04, + RTT_WITH_96_BIT_RANDOM_SEQUENCE = 0x05, + RTT_WITH_128_BIT_RANDOM_SEQUENCE = 0x06, +} + +enum CsSyncPhy : 8 { + LE_1M_PHY = 0x01, + LE_2M_PHY = 0x02, + LE_2M_2BT_PHY = 0x03, +} + +enum CsChannelSelectionType : 8 { + TYPE_3B = 0x00, + TYPE_3C = 0x01, +} + +enum CsCh3cShape : 8 { + HAT_SHAPE = 0x00, + X_SHAPE = 0x01, +} + +enum CsAction : 8 { + CONFIG_REMOVED = 0x00, + CONFIG_CREATED = 0x01, +} + +packet LeCsConfigComplete : LeMetaEvent (subevent_code = LE_CS_CONFIG_COMPLETE) { + status : ErrorCode, + connection_handle : 12, + _reserved_ : 4, + config_id : 8, + action : CsAction, + main_mode_type : CsMainModeType, + sub_mode_type : CsSubModeType, + min_main_mode_steps : 8, + max_main_mode_steps : 8, + main_mode_repetition : 8, + mode_0_steps : 8, + role : CsRole, + rtt_type : CsRttType, + cs_sync_phy : CsSyncPhy, + channel_map : 8[10], + channel_map_repetition : 8, + channel_selection_type : CsChannelSelectionType, + ch3c_shape : CsCh3cShape, + ch3c_jump : 8, + _reserved_ : 8, + t_ip1_time : 8, + t_ip2_time : 8, + t_fcs_time : 8, + t_pm_time : 8, +} + +packet LeCsCreateConfig : Command (op_code = LE_CS_CREATE_CONFIG) { + connection_handle: 12, + _reserved_ : 4, + config_id : 8, + create_context : CsCreateContext, + main_mode_type : CsMainModeType, + sub_mode_type : CsSubModeType, + min_main_mode_steps : 8, + max_main_mode_steps : 8, + main_mode_repetition : 8, + mode_0_steps : 8, + role : CsRole, + rtt_type : CsRttType, + cs_sync_phy : CsSyncPhy, + channel_map : 8[10], + channel_map_repetition : 8, + channel_selection_type : CsChannelSelectionType, + ch3c_shape : CsCh3cShape, + ch3c_jump : 8, + _reserved_ : 8, +} + +packet LeCsCreateConfigStatus : CommandStatus (command_op_code = LE_CS_CREATE_CONFIG) { +} + + +packet LeCsRemoveConfig : Command (op_code = LE_CS_REMOVE_CONFIG) { + connection_handle: 12, + _reserved_ : 4, + config_id : 8, +} + +packet LeCsRemoveConfigStatus : CommandStatus (command_op_code = LE_CS_REMOVE_CONFIG) { +} + +packet LeCsSetChannelClassification : Command (op_code = LE_CS_SET_CHANNEL_CLASSIFICATION) { + channel_classification : 8[10], +} + +packet LeCsSetChannelClassificationComplete : CommandComplete (command_op_code = LE_CS_SET_CHANNEL_CLASSIFICATION) { +} + +enum CsPhy : 8 { + LE_1M_PHY = 0x01, + LE_2M_PHY = 0x02, + LE_CODED_PHY_S2 = 0x03, + LE_CODED_PHY_S8 = 0x04, +} + +struct CsPreferredPeerAntenna { + use_first_ordered_antenna_element : 1, + use_second_ordered_antenna_element : 1, + use_third_ordered_antenna_element : 1, + use_fourth_ordered_antenna_element : 1, + _reserved_ : 4, +} + +enum CsSnrControl : 8 { + ADJUST_18_DB = 0x00, + ADJUST_21_DB = 0x01, + ADJUST_24_DB = 0x02, + ADJUST_27_DB = 0x03, + ADJUST_30_DB = 0x04, + NOT_APPLIED = 0xFF, +} + +packet LeCsSetProcedureParameters : Command (op_code = LE_CS_SET_PROCEDURE_PARAMETERS) { + connection_handle: 12, + _reserved_ : 4, + config_id : 8, + max_procedure_len : 16, + min_procedure_interval : 16, + max_procedure_interval : 16, + max_procedure_count : 16, + min_subevent_len : 24, + max_subevent_len : 24, + tone_antenna_config_selection : 8, + phy : CsPhy, + tx_power_delta : 8, + preferred_peer_antenna : CsPreferredPeerAntenna, + snr_control_initiator: CsSnrControl, + snr_control_reflector: CsSnrControl, +} + +packet LeCsSetProcedureParametersComplete : CommandComplete (command_op_code = LE_CS_SET_PROCEDURE_PARAMETERS) { + status : ErrorCode, + connection_handle: 12, + _reserved_ : 4, +} + +packet LeCsProcedureEnable : Command (op_code = LE_CS_PROCEDURE_ENABLE) { + connection_handle: 12, + _reserved_ : 4, + config_id : 8, + procedure_enable : Enable, +} + +packet LeCsProcedureEnableStatus : CommandStatus (command_op_code = LE_CS_PROCEDURE_ENABLE) { +} + +packet LeCsProcedureEnableComplete : LeMetaEvent (subevent_code = LE_CS_PROCEDURE_ENABLE_COMPLETE) { + status : ErrorCode, + connection_handle : 12, + _reserved_ : 4, + config_id : 8, + state : Enable, + tone_antenna_config_selection : 8, + selected_tx_power : 8, + subevent_len : 24, + subevents_per_event : 8, + subevent_interval : 16, + event_interval : 16, + procedure_interval : 16, + procedure_count : 16, + max_procedure_len : 16, +} + +packet LeCsTest : Command (op_code = LE_CS_TEST) { + main_mode_type : CsMainModeType, + sub_mode_type : CsSubModeType, + main_mode_repetition : 8, + mode_0_steps : 8, + role : CsRole, + rtt_type : CsRttType, + cs_sync_phy : CsSyncPhy, + cs_sync_antenna_selection : 8, + subevent_len : 24, + subevent_interval : 16, + max_num_subevents : 8, + transmit_power_level : 8, + t_ip1_time : 8, + t_ip2_time : 8, + t_fcs_time : 8, + t_pm_time : 8, + t_sw_time : 8, + tone_antenna_config_selection : 8, + _reserved_ : 8, + snr_control_initiator: CsSnrControl, + snr_control_reflector: CsSnrControl, + drbg_nonce : 16, + channel_map_repetition : 8, + override_config : 16, + _size_(override_parameters_data) : 8, + override_parameters_data : 8[], +} + +packet LeCsTestComplete : CommandComplete (command_op_code = LE_CS_TEST) { + status : ErrorCode, +} + +packet LeCsTestEnd : Command (op_code = LE_CS_TEST_END) { +} + +packet LeCsTestEndStatus : CommandStatus (command_op_code = LE_CS_TEST_END) { +} + +packet LeCsTestEndComplete : LeMetaEvent (subevent_code = LE_CS_TEST_END_COMPLETE) { + status : ErrorCode, +} + // HCI Event Packets packet InquiryComplete : Event (event_code = INQUIRY_COMPLETE) { @@ -5125,11 +5802,6 @@ packet RemoteHostSupportedFeaturesNotification : Event (event_code = REMOTE_HOST host_supported_features : 64, } -packet LeMetaEvent : Event (event_code = LE_META_EVENT) { - subevent_code : SubeventCode, - _body_, -} - packet NumberOfCompletedDataBlocks : Event (event_code = NUMBER_OF_COMPLETED_DATA_BLOCKS) { total_num_data_blocks : 16, _payload_, // placeholder (unimplemented) @@ -5141,7 +5813,7 @@ packet AuthenticatedPayloadTimeoutExpired : Event (event_code = AUTHENTICATED_PA } // LE Events -packet LeConnectionComplete : LeMetaEvent (subevent_code = CONNECTION_COMPLETE) { +packet LeConnectionComplete : LeMetaEvent (subevent_code = LE_CONNECTION_COMPLETE) { status : ErrorCode, connection_handle : 12, _reserved_ : 4, @@ -5171,12 +5843,12 @@ struct LeAdvertisingResponse { rssi : 8, } -packet LeAdvertisingReport : LeMetaEvent (subevent_code = ADVERTISING_REPORT) { +packet LeAdvertisingReport : LeMetaEvent (subevent_code = LE_ADVERTISING_REPORT) { _count_(responses) : 8, responses : LeAdvertisingResponse[], } -packet LeConnectionUpdateComplete : LeMetaEvent (subevent_code = CONNECTION_UPDATE_COMPLETE) { +packet LeConnectionUpdateComplete : LeMetaEvent (subevent_code = LE_CONNECTION_UPDATE_COMPLETE) { status : ErrorCode, connection_handle : 12, _reserved_ : 4, @@ -5185,21 +5857,14 @@ packet LeConnectionUpdateComplete : LeMetaEvent (subevent_code = CONNECTION_UPDA supervision_timeout : 16, // 0x000A to 0x0C80 (100ms to 32s) } -packet LeReadRemoteFeaturesComplete : LeMetaEvent (subevent_code = READ_REMOTE_FEATURES_COMPLETE) { - status : ErrorCode, - connection_handle : 12, - _reserved_ : 4, - le_features : 64, -} - -packet LeLongTermKeyRequest : LeMetaEvent (subevent_code = LONG_TERM_KEY_REQUEST) { +packet LeLongTermKeyRequest : LeMetaEvent (subevent_code = LE_LONG_TERM_KEY_REQUEST) { connection_handle : 12, _reserved_ : 4, random_number : 8[8], encrypted_diversifier : 16, } -packet LeRemoteConnectionParameterRequest : LeMetaEvent (subevent_code = REMOTE_CONNECTION_PARAMETER_REQUEST) { +packet LeRemoteConnectionParameterRequest : LeMetaEvent (subevent_code = LE_REMOTE_CONNECTION_PARAMETER_REQUEST) { connection_handle : 12, _reserved_ : 4, interval_min : 16, // 0x006 - 0x0C80 (7.5ms - 4s) @@ -5208,7 +5873,7 @@ packet LeRemoteConnectionParameterRequest : LeMetaEvent (subevent_code = REMOTE_ timeout : 16, // 0x000A to 0x0C80 (100ms to 32s) } -packet LeDataLengthChange : LeMetaEvent (subevent_code = DATA_LENGTH_CHANGE) { +packet LeDataLengthChange : LeMetaEvent (subevent_code = LE_DATA_LENGTH_CHANGE) { connection_handle : 12, _reserved_ : 4, max_tx_octets : 16, // 0x001B - 0x00FB @@ -5217,18 +5882,18 @@ packet LeDataLengthChange : LeMetaEvent (subevent_code = DATA_LENGTH_CHANGE) { max_rx_time : 16, // 0x0148 - 0x4290 } -packet LeReadLocalP256PublicKeyComplete : LeMetaEvent (subevent_code = READ_LOCAL_P256_PUBLIC_KEY_COMPLETE) { +packet LeReadLocalP256PublicKeyComplete : LeMetaEvent (subevent_code = LE_READ_LOCAL_P256_PUBLIC_KEY_COMPLETE) { status : ErrorCode, key_x_coordinate : 8[32], key_y_coordinate : 8[32], } -packet LeGenerateDhKeyComplete : LeMetaEvent (subevent_code = GENERATE_DHKEY_COMPLETE) { +packet LeGenerateDhKeyComplete : LeMetaEvent (subevent_code = LE_GENERATE_DHKEY_COMPLETE) { status : ErrorCode, dh_key : 8[32], } -packet LeEnhancedConnectionComplete : LeMetaEvent (subevent_code = ENHANCED_CONNECTION_COMPLETE) { +packet LeEnhancedConnectionCompleteV1 : LeMetaEvent (subevent_code = LE_ENHANCED_CONNECTION_COMPLETE_V1) { status : ErrorCode, connection_handle : 12, _reserved_ : 4, @@ -5243,6 +5908,23 @@ packet LeEnhancedConnectionComplete : LeMetaEvent (subevent_code = ENHANCED_CONN central_clock_accuracy : ClockAccuracy, } +packet LeEnhancedConnectionCompleteV2 : LeMetaEvent (subevent_code = LE_ENHANCED_CONNECTION_COMPLETE_V2) { + status : ErrorCode, + connection_handle : 12, + _reserved_ : 4, + role : Role, + peer_address_type : AddressType, + peer_address : Address, + local_resolvable_private_address : Address, + peer_resolvable_private_address : Address, + connection_interval : 16, // 0x006 - 0x0C80 (7.5ms - 4000ms) + peripheral_latency : 16, + supervision_timeout : 16, // 0x000A to 0x0C80 (100ms to 32s) + central_clock_accuracy : ClockAccuracy, + advertising_handle : 8, + sync_handle : 16, +} + enum DirectAdvertisingAddressType : 8 { PUBLIC_DEVICE_ADDRESS = 0x00, RANDOM_DEVICE_ADDRESS = 0x01, @@ -5269,12 +5951,12 @@ struct LeDirectedAdvertisingResponse { rssi : 8, } -packet LeDirectedAdvertisingReport : LeMetaEvent (subevent_code = DIRECTED_ADVERTISING_REPORT) { +packet LeDirectedAdvertisingReport : LeMetaEvent (subevent_code = LE_DIRECTED_ADVERTISING_REPORT) { _count_(responses) : 8, responses : LeDirectedAdvertisingResponse[], } -packet LePhyUpdateComplete : LeMetaEvent (subevent_code = PHY_UPDATE_COMPLETE) { +packet LePhyUpdateComplete : LeMetaEvent (subevent_code = LE_PHY_UPDATE_COMPLETE) { status : ErrorCode, connection_handle : 12, _reserved_ : 4, @@ -5311,12 +5993,24 @@ struct LeExtendedAdvertisingResponse { advertising_data: 8[], } -packet LeExtendedAdvertisingReport : LeMetaEvent (subevent_code = EXTENDED_ADVERTISING_REPORT) { +packet LeExtendedAdvertisingReport : LeMetaEvent (subevent_code = LE_EXTENDED_ADVERTISING_REPORT) { _count_(responses) : 8, responses : LeExtendedAdvertisingResponse[], } -packet LePeriodicAdvertisingSyncEstablished : LeMetaEvent (subevent_code = PERIODIC_ADVERTISING_SYNC_ESTABLISHED) { +packet LePeriodicAdvertisingSyncEstablishedV1 : LeMetaEvent (subevent_code = LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHED_V1) { + status : ErrorCode, + sync_handle : 12, + _reserved_ : 4, + advertising_sid : 8, + advertiser_address_type : AddressType, + advertiser_address : Address, + advertiser_phy : SecondaryPhyType, + periodic_advertising_interval : 16, + advertiser_clock_accuracy : ClockAccuracy, +} + +packet LePeriodicAdvertisingSyncEstablishedV2 : LeMetaEvent (subevent_code = LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHED_V2) { status : ErrorCode, sync_handle : 12, _reserved_ : 4, @@ -5326,9 +6020,13 @@ packet LePeriodicAdvertisingSyncEstablished : LeMetaEvent (subevent_code = PERIO advertiser_phy : SecondaryPhyType, periodic_advertising_interval : 16, advertiser_clock_accuracy : ClockAccuracy, + num_subevents : 8, + subevent_interval : 8, + response_slot_delay : 8, + response_slot_spacing : 8, } -packet LePeriodicAdvertisingReport : LeMetaEvent (subevent_code = PERIODIC_ADVERTISING_REPORT) { +packet LePeriodicAdvertisingReportV1 : LeMetaEvent (subevent_code = LE_PERIODIC_ADVERTISING_REPORT_V1) { sync_handle : 12, _reserved_ : 4, tx_power : 8, @@ -5340,15 +6038,29 @@ packet LePeriodicAdvertisingReport : LeMetaEvent (subevent_code = PERIODIC_ADVER data : 8[], } -packet LePeriodicAdvertisingSyncLost : LeMetaEvent (subevent_code = PERIODIC_ADVERTISING_SYNC_LOST) { +packet LePeriodicAdvertisingReportV2 : LeMetaEvent (subevent_code = LE_PERIODIC_ADVERTISING_REPORT_V2) { sync_handle : 12, _reserved_ : 4, + tx_power : 8, + rssi : 8, + cte_type : CteType, + periodic_event_counter : 16, + subevent : 8, + data_status : DataStatus, + _reserved_: 6, + _size_(data) : 8, + data : 8[], } -packet LeScanTimeout : LeMetaEvent (subevent_code = SCAN_TIMEOUT) { +packet LePeriodicAdvertisingSyncLost : LeMetaEvent (subevent_code = LE_PERIODIC_ADVERTISING_SYNC_LOST) { + sync_handle : 12, + _reserved_ : 4, } -packet LeAdvertisingSetTerminated : LeMetaEvent (subevent_code = ADVERTISING_SET_TERMINATED) { +packet LeScanTimeout : LeMetaEvent (subevent_code = LE_SCAN_TIMEOUT) { +} + +packet LeAdvertisingSetTerminated : LeMetaEvent (subevent_code = LE_ADVERTISING_SET_TERMINATED) { status : ErrorCode, advertising_handle : 8, connection_handle : 12, @@ -5356,7 +6068,7 @@ packet LeAdvertisingSetTerminated : LeMetaEvent (subevent_code = ADVERTISING_SET num_completed_extended_advertising_events : 8, } -packet LeScanRequestReceived : LeMetaEvent (subevent_code = SCAN_REQUEST_RECEIVED) { +packet LeScanRequestReceived : LeMetaEvent (subevent_code = LE_SCAN_REQUEST_RECEIVED) { advertising_handle : 8, scanner_address_type : AddressType, scanner_address : Address, @@ -5367,25 +6079,41 @@ enum ChannelSelectionAlgorithm : 8 { ALGORITHM_2 = 1, } -packet LeChannelSelectionAlgorithm : LeMetaEvent (subevent_code = CHANNEL_SELECTION_ALGORITHM) { +packet LeChannelSelectionAlgorithm : LeMetaEvent (subevent_code = LE_CHANNEL_SELECTION_ALGORITHM) { connection_handle : 12, _reserved_ : 4, channel_selection_algorithm : ChannelSelectionAlgorithm, } -packet LeConnectionlessIqReport : LeMetaEvent (subevent_code = CONNECTIONLESS_IQ_REPORT) { +packet LeConnectionlessIqReport : LeMetaEvent (subevent_code = LE_CONNECTIONLESS_IQ_REPORT) { _payload_, // placeholder (unimplemented) } -packet LeConnectionIqReport : LeMetaEvent (subevent_code = CONNECTION_IQ_REPORT) { +packet LeConnectionIqReport : LeMetaEvent (subevent_code = LE_CONNECTION_IQ_REPORT) { _payload_, // placeholder (unimplemented) } -packet LeCteRequestFailed : LeMetaEvent (subevent_code = CTE_REQUEST_FAILED) { +packet LeCteRequestFailed : LeMetaEvent (subevent_code = LE_CTE_REQUEST_FAILED) { _payload_, // placeholder (unimplemented) } -packet LePeriodicAdvertisingSyncTransferReceived : LeMetaEvent (subevent_code = PERIODIC_ADVERTISING_SYNC_TRANSFER_RECEIVED) { +packet LePeriodicAdvertisingSyncTransferReceivedV1 : LeMetaEvent (subevent_code = LE_PERIODIC_ADVERTISING_SYNC_TRANSFER_RECEIVED_V1) { + status : ErrorCode, + connection_handle : 12, + _reserved_ : 4, + service_data : 16, + sync_handle : 12, + _reserved_ : 4, + advertising_sid : 4, + _reserved_ : 4, + advertiser_address_type : AddressType, + advertiser_address : Address, + advertiser_phy : SecondaryPhyType, + periodic_advertising_interval : 16, + advertiser_clock_accuracy : ClockAccuracy, +} + +packet LePeriodicAdvertisingSyncTransferReceivedV2 : LeMetaEvent (subevent_code = LE_PERIODIC_ADVERTISING_SYNC_TRANSFER_RECEIVED_V2) { status : ErrorCode, connection_handle : 12, _reserved_ : 4, @@ -5399,9 +6127,37 @@ packet LePeriodicAdvertisingSyncTransferReceived : LeMetaEvent (subevent_code = advertiser_phy : SecondaryPhyType, periodic_advertising_interval : 16, advertiser_clock_accuracy : ClockAccuracy, + num_subevents : 8, + subevent_interval : 8, + response_slot_delay : 8, + response_slot_spacing : 8, +} + +packet LeCisEstablishedV1 : LeMetaEvent (subevent_code = LE_CIS_ESTABLISHED_V1) { + status : ErrorCode, + connection_handle : 12, + _reserved_ : 4, + cig_sync_delay : 24, + cis_sync_delay : 24, + transport_latency_c_to_p : 24, + transport_latency_p_to_c : 24, + phy_c_to_p : SecondaryPhyType, + phy_p_to_c : SecondaryPhyType, + nse : 8, + bn_c_to_p : 4, + _reserved_ : 4, + bn_p_to_c : 4, + _reserved_ : 4, + ft_c_to_p : 8, + ft_p_to_c : 8, + max_pdu_c_to_p : 8, + _reserved_ : 8, + max_pdu_p_to_c : 8, + _reserved_ : 8, + iso_interval : 16, } -packet LeCisEstablished : LeMetaEvent (subevent_code = CIS_ESTABLISHED) { +packet LeCisEstablishedV2 : LeMetaEvent (subevent_code = LE_CIS_ESTABLISHED_V2) { status : ErrorCode, connection_handle : 12, _reserved_ : 4, @@ -5423,9 +6179,15 @@ packet LeCisEstablished : LeMetaEvent (subevent_code = CIS_ESTABLISHED) { max_pdu_p_to_c : 8, _reserved_ : 8, iso_interval : 16, + sub_interval : 24, + max_sdu_c_to_p : 16, + max_sdu_p_to_c : 16, + sdu_interval_c_to_p : 24, + sdu_interval_p_to_c : 24, + framing : Enable, } -packet LeCisRequest : LeMetaEvent (subevent_code = CIS_REQUEST) { +packet LeCisRequest : LeMetaEvent (subevent_code = LE_CIS_REQUEST) { acl_connection_handle : 12, _reserved_ : 4, cis_connection_handle : 12, @@ -5434,7 +6196,7 @@ packet LeCisRequest : LeMetaEvent (subevent_code = CIS_REQUEST) { cis_id : 8, } -packet LeCreateBigComplete : LeMetaEvent (subevent_code = CREATE_BIG_COMPLETE) { +packet LeCreateBigComplete : LeMetaEvent (subevent_code = LE_CREATE_BIG_COMPLETE) { status : ErrorCode, big_handle : 8, big_sync_delay : 24, @@ -5450,12 +6212,12 @@ packet LeCreateBigComplete : LeMetaEvent (subevent_code = CREATE_BIG_COMPLETE) { connection_handle : 16[], } -packet LeTerminateBigComplete : LeMetaEvent (subevent_code = TERMINATE_BIG_COMPLETE) { +packet LeTerminateBigComplete : LeMetaEvent (subevent_code = LE_TERMINATE_BIG_COMPLETE) { big_handle : 8, reason : ErrorCode, } -packet LeBigSyncEstablished : LeMetaEvent (subevent_code = BIG_SYNC_ESTABLISHED) { +packet LeBigSyncEstablished : LeMetaEvent (subevent_code = LE_BIG_SYNC_ESTABLISHED) { status : ErrorCode, big_handle : 8, transport_latency_big : 24, @@ -5469,12 +6231,12 @@ packet LeBigSyncEstablished : LeMetaEvent (subevent_code = BIG_SYNC_ESTABLISHED) connection_handle : 16[], } -packet LeBigSyncLost : LeMetaEvent (subevent_code = BIG_SYNC_LOST) { +packet LeBigSyncLost : LeMetaEvent (subevent_code = LE_BIG_SYNC_LOST) { big_handle : 8, reason : ErrorCode, } -packet LeRequestPeerScaComplete : LeMetaEvent (subevent_code = REQUEST_PEER_SCA_COMPLETE) { +packet LeRequestPeerScaComplete : LeMetaEvent (subevent_code = LE_REQUEST_PEER_SCA_COMPLETE) { status : ErrorCode, connection_handle : 12, _reserved_ : 4, @@ -5487,7 +6249,7 @@ enum PathLossZone : 8 { HIGH = 2, } -packet LePathLossThreshold : LeMetaEvent (subevent_code = PATH_LOSS_THRESHOLD) { +packet LePathLossThreshold : LeMetaEvent (subevent_code = LE_PATH_LOSS_THRESHOLD) { connection_handle : 12, _reserved_ : 4, current_path_loss : 8, @@ -5500,7 +6262,7 @@ enum ReportingReason : 8 { READ_COMMAND_COMPLETE = 0x02, } -packet LeTransmitPowerReporting : LeMetaEvent (subevent_code = TRANSMIT_POWER_REPORTING) { +packet LeTransmitPowerReporting : LeMetaEvent (subevent_code = LE_TRANSMIT_POWER_REPORTING) { status : ErrorCode, connection_handle : 12, _reserved_ : 4, @@ -5511,7 +6273,7 @@ packet LeTransmitPowerReporting : LeMetaEvent (subevent_code = TRANSMIT_POWER_RE delta : 8, } -packet LeBigInfoAdvertisingReport : LeMetaEvent (subevent_code = BIG_INFO_ADVERTISING_REPORT) { +packet LeBigInfoAdvertisingReport : LeMetaEvent (subevent_code = LE_BIG_INFO_ADVERTISING_REPORT) { sync_handle : 12, _reserved_ : 4, num_bis : 8, diff --git a/tools/rootcanal/py/controller.py b/tools/rootcanal/py/controller.py index 80e83072b4..cec909d122 100644 --- a/tools/rootcanal/py/controller.py +++ b/tools/rootcanal/py/controller.py @@ -260,8 +260,8 @@ class ControllerTest(unittest.IsolatedAsyncioTestCase): # Load the local supported features to be able to disable tests # that rely on unsupported features. - controller.send_cmd(hci.LeReadLocalSupportedFeatures()) - evt = await self.expect_cmd_complete(hci.LeReadLocalSupportedFeaturesComplete) + controller.send_cmd(hci.LeReadLocalSupportedFeaturesPage0()) + evt = await self.expect_cmd_complete(hci.LeReadLocalSupportedFeaturesPage0Complete) controller.le_features = LeFeatures(evt.le_features) async def expect_evt(self, expected_evt: typing.Union[hci.Event, type], timeout: int = 3) -> hci.Event: @@ -369,34 +369,35 @@ class ControllerTest(unittest.IsolatedAsyncioTestCase): async def enable_connected_isochronous_stream_host_support(self): """Enable Connected Isochronous Stream Host Support in the LE Feature mask.""" self.controller.send_cmd( - hci.LeSetHostFeature(bit_number=hci.LeHostFeatureBits.CONNECTED_ISO_STREAM_HOST_SUPPORT, - bit_value=hci.Enable.ENABLED)) + hci.LeSetHostFeatureV1(bit_number=hci.LeHostFeatureBits.CONNECTED_ISO_STREAM_HOST_SUPPORT, + bit_value=hci.Enable.ENABLED)) - await self.expect_evt(hci.LeSetHostFeatureComplete(status=ErrorCode.SUCCESS, num_hci_command_packets=1)) + await self.expect_evt(hci.LeSetHostFeatureV1Complete(status=ErrorCode.SUCCESS, num_hci_command_packets=1)) async def establish_le_connection_central(self, peer_address: hci.Address) -> int: """Establish a connection with the selected peer as Central. Returns the ACL connection handle for the opened link.""" self.controller.send_cmd( - hci.LeExtendedCreateConnection(initiator_filter_policy=hci.InitiatorFilterPolicy.USE_PEER_ADDRESS, - own_address_type=hci.OwnAddressType.PUBLIC_DEVICE_ADDRESS, - peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, - peer_address=peer_address, - initiating_phys=0x1, - initiating_phy_parameters=[ - hci.InitiatingPhyParameters( - scan_interval=0x200, - scan_window=0x100, - connection_interval_min=0x200, - connection_interval_max=0x200, - max_latency=0x6, - supervision_timeout=0xc80, - min_ce_length=0, - max_ce_length=0, - ) - ])) - - await self.expect_evt(hci.LeExtendedCreateConnectionStatus(status=ErrorCode.SUCCESS, num_hci_command_packets=1)) + hci.LeExtendedCreateConnectionV1(initiator_filter_policy=hci.InitiatorFilterPolicy.USE_PEER_ADDRESS, + own_address_type=hci.OwnAddressType.PUBLIC_DEVICE_ADDRESS, + peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, + peer_address=peer_address, + initiating_phys=0x1, + initiating_phy_parameters=[ + hci.InitiatingPhyParameters( + scan_interval=0x200, + scan_window=0x100, + connection_interval_min=0x200, + connection_interval_max=0x200, + max_latency=0x6, + supervision_timeout=0xc80, + min_ce_length=0, + max_ce_length=0, + ) + ])) + + await self.expect_evt( + hci.LeExtendedCreateConnectionV1Status(status=ErrorCode.SUCCESS, num_hci_command_packets=1)) self.controller.send_ll(ll.LeLegacyAdvertisingPdu(source_address=peer_address, advertising_address_type=ll.AddressType.PUBLIC, @@ -423,15 +424,15 @@ class ControllerTest(unittest.IsolatedAsyncioTestCase): conn_supervision_timeout=0xc80)) connection_complete = await self.expect_evt( - hci.LeEnhancedConnectionComplete(status=ErrorCode.SUCCESS, - connection_handle=self.Any, - role=hci.Role.CENTRAL, - peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, - peer_address=peer_address, - connection_interval=0x200, - peripheral_latency=0x6, - supervision_timeout=0xc80, - central_clock_accuracy=hci.ClockAccuracy.PPM_500)) + hci.LeEnhancedConnectionCompleteV1(status=ErrorCode.SUCCESS, + connection_handle=self.Any, + role=hci.Role.CENTRAL, + peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, + peer_address=peer_address, + connection_interval=0x200, + peripheral_latency=0x6, + supervision_timeout=0xc80, + central_clock_accuracy=hci.ClockAccuracy.PPM_500)) acl_connection_handle = connection_complete.connection_handle await self.expect_evt( @@ -475,15 +476,15 @@ class ControllerTest(unittest.IsolatedAsyncioTestCase): conn_supervision_timeout=0x200)) connection_complete = await self.expect_evt( - hci.LeEnhancedConnectionComplete(status=ErrorCode.SUCCESS, - connection_handle=self.Any, - role=hci.Role.PERIPHERAL, - peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, - peer_address=peer_address, - connection_interval=0x200, - peripheral_latency=0x200, - supervision_timeout=0x200, - central_clock_accuracy=hci.ClockAccuracy.PPM_500)) + hci.LeEnhancedConnectionCompleteV1(status=ErrorCode.SUCCESS, + connection_handle=self.Any, + role=hci.Role.PERIPHERAL, + peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, + peer_address=peer_address, + connection_interval=0x200, + peripheral_latency=0x200, + supervision_timeout=0x200, + central_clock_accuracy=hci.ClockAccuracy.PPM_500)) return connection_complete.connection_handle diff --git a/tools/rootcanal/rust/src/llcp/iso.rs b/tools/rootcanal/rust/src/llcp/iso.rs index 6d9997d5ba..1f6b11adc7 100644 --- a/tools/rootcanal/rust/src/llcp/iso.rs +++ b/tools/rootcanal/rust/src/llcp/iso.rs @@ -1283,7 +1283,7 @@ impl IsoManager { conn_event_count: 0, }, ); - self.send_hci_event(hci::LeCisEstablishedBuilder { + self.send_hci_event(hci::LeCisEstablishedV1Builder { status: hci::ErrorCode::Success, connection_handle: cis_connection_handle, cig_sync_delay: parameters.cig_sync_delay, @@ -1323,7 +1323,7 @@ impl IsoManager { let cis = self.cis_connections.get_mut(&cis_connection_handle).unwrap(); cis.state = CisState::Configuration; cis.parameters = None; - self.send_hci_event(hci::LeCisEstablishedBuilder { + self.send_hci_event(hci::LeCisEstablishedV1Builder { status: hci::ErrorCode::RemoteUserTerminatedConnection, connection_handle: cis_connection_handle, cig_sync_delay: 0, @@ -1364,7 +1364,7 @@ impl IsoManager { }); let cis = self.cis_connections.get(&cis_connection_handle).unwrap(); let parameters = cis.parameters.as_ref().unwrap(); - self.send_hci_event(hci::LeCisEstablishedBuilder { + self.send_hci_event(hci::LeCisEstablishedV1Builder { status: hci::ErrorCode::Success, connection_handle: cis_connection_handle, cig_sync_delay: parameters.cig_sync_delay, diff --git a/tools/rootcanal/test/LL/CIS/CEN/BV_01_C.py b/tools/rootcanal/test/LL/CIS/CEN/BV_01_C.py index 67184f2555..9b302336f0 100644 --- a/tools/rootcanal/test/LL/CIS/CEN/BV_01_C.py +++ b/tools/rootcanal/test/LL/CIS/CEN/BV_01_C.py @@ -165,22 +165,22 @@ class Test(ControllerTest): # The Connection_Handle parameter is set to the value provided in the HCI_LE_Create_CIS # command. await self.expect_evt( - hci.LeCisEstablished(status=ErrorCode.SUCCESS, - connection_handle=cis_connection_handle, - cig_sync_delay=cis_ind.cig_sync_delay, - cis_sync_delay=cis_ind.cis_sync_delay, - transport_latency_c_to_p=self.Any, - transport_latency_p_to_c=self.Any, - phy_c_to_p=hci.SecondaryPhyType.LE_1M, - phy_p_to_c=hci.SecondaryPhyType.LE_1M, - nse=self.NSE, - bn_c_to_p=self.BN_C_TO_P, - bn_p_to_c=self.BN_P_TO_C, - ft_c_to_p=self.FT_C_TO_P, - ft_p_to_c=self.FT_P_TO_C, - max_pdu_c_to_p=self.Max_PDU_C_TO_P, - max_pdu_p_to_c=self.Max_PDU_P_TO_C, - iso_interval=self.ISO_Interval)) + hci.LeCisEstablishedV1(status=ErrorCode.SUCCESS, + connection_handle=cis_connection_handle, + cig_sync_delay=cis_ind.cig_sync_delay, + cis_sync_delay=cis_ind.cis_sync_delay, + transport_latency_c_to_p=self.Any, + transport_latency_p_to_c=self.Any, + phy_c_to_p=hci.SecondaryPhyType.LE_1M, + phy_p_to_c=hci.SecondaryPhyType.LE_1M, + nse=self.NSE, + bn_c_to_p=self.BN_C_TO_P, + bn_p_to_c=self.BN_P_TO_C, + ft_c_to_p=self.FT_C_TO_P, + ft_p_to_c=self.FT_P_TO_C, + max_pdu_c_to_p=self.Max_PDU_C_TO_P, + max_pdu_p_to_c=self.Max_PDU_P_TO_C, + iso_interval=self.ISO_Interval)) # 8. The Upper Tester orders the IUT to send data packets to the Lower Tester. iso_sdu = [random.randint(1, 251) for n in range(self.Max_SDU_C_TO_P)] diff --git a/tools/rootcanal/test/LL/CIS/CEN/BV_03_C.py b/tools/rootcanal/test/LL/CIS/CEN/BV_03_C.py index c3b0e11e43..21263c666b 100644 --- a/tools/rootcanal/test/LL/CIS/CEN/BV_03_C.py +++ b/tools/rootcanal/test/LL/CIS/CEN/BV_03_C.py @@ -136,5 +136,5 @@ class Test(ControllerTest): # 5. The Upper Tester receives an HCI_LE_CIS_Established event from the IUT with a status failure. # The Status field has the same value as the LL_REJECT_EXT_IND PDU in step 4. await self.expect_evt( - hci.LeCisEstablished(status=ErrorCode.REMOTE_USER_TERMINATED_CONNECTION, - connection_handle=cis_connection_handle)) + hci.LeCisEstablishedV1(status=ErrorCode.REMOTE_USER_TERMINATED_CONNECTION, + connection_handle=cis_connection_handle)) diff --git a/tools/rootcanal/test/LL/CIS/CEN/BV_10_C.py b/tools/rootcanal/test/LL/CIS/CEN/BV_10_C.py index cb30823647..6b2020bb08 100644 --- a/tools/rootcanal/test/LL/CIS/CEN/BV_10_C.py +++ b/tools/rootcanal/test/LL/CIS/CEN/BV_10_C.py @@ -154,22 +154,22 @@ class Test(ControllerTest): conn_event_count=0)) await self.expect_evt( - hci.LeCisEstablished(status=ErrorCode.SUCCESS, - connection_handle=cis_connection_handle_1, - cig_sync_delay=cis_ind_1.cig_sync_delay, - cis_sync_delay=cis_ind_1.cis_sync_delay, - transport_latency_c_to_p=self.Any, - transport_latency_p_to_c=self.Any, - phy_c_to_p=hci.SecondaryPhyType.LE_1M, - phy_p_to_c=hci.SecondaryPhyType.LE_1M, - nse=self.NSE, - bn_c_to_p=self.BN_C_TO_P, - bn_p_to_c=self.BN_P_TO_C, - ft_c_to_p=self.FT_C_TO_P, - ft_p_to_c=self.FT_P_TO_C, - max_pdu_c_to_p=self.Max_PDU_C_TO_P, - max_pdu_p_to_c=self.Max_PDU_P_TO_C, - iso_interval=self.ISO_Interval)) + hci.LeCisEstablishedV1(status=ErrorCode.SUCCESS, + connection_handle=cis_connection_handle_1, + cig_sync_delay=cis_ind_1.cig_sync_delay, + cis_sync_delay=cis_ind_1.cis_sync_delay, + transport_latency_c_to_p=self.Any, + transport_latency_p_to_c=self.Any, + phy_c_to_p=hci.SecondaryPhyType.LE_1M, + phy_p_to_c=hci.SecondaryPhyType.LE_1M, + nse=self.NSE, + bn_c_to_p=self.BN_C_TO_P, + bn_p_to_c=self.BN_P_TO_C, + ft_c_to_p=self.FT_C_TO_P, + ft_p_to_c=self.FT_P_TO_C, + max_pdu_c_to_p=self.Max_PDU_C_TO_P, + max_pdu_p_to_c=self.Max_PDU_P_TO_C, + iso_interval=self.ISO_Interval)) cis_req_2 = await self.expect_llcp(source_address=controller.address, destination_address=peer_address_2, @@ -210,22 +210,22 @@ class Test(ControllerTest): conn_event_count=0)) await self.expect_evt( - hci.LeCisEstablished(status=ErrorCode.SUCCESS, - connection_handle=cis_connection_handle_2, - cig_sync_delay=cis_ind_2.cig_sync_delay, - cis_sync_delay=cis_ind_2.cis_sync_delay, - transport_latency_c_to_p=self.Any, - transport_latency_p_to_c=self.Any, - phy_c_to_p=hci.SecondaryPhyType.LE_1M, - phy_p_to_c=hci.SecondaryPhyType.LE_1M, - nse=self.NSE, - bn_c_to_p=self.BN_C_TO_P, - bn_p_to_c=self.BN_P_TO_C, - ft_c_to_p=self.FT_C_TO_P, - ft_p_to_c=self.FT_P_TO_C, - max_pdu_c_to_p=self.Max_PDU_C_TO_P, - max_pdu_p_to_c=self.Max_PDU_P_TO_C, - iso_interval=self.ISO_Interval)) + hci.LeCisEstablishedV1(status=ErrorCode.SUCCESS, + connection_handle=cis_connection_handle_2, + cig_sync_delay=cis_ind_2.cig_sync_delay, + cis_sync_delay=cis_ind_2.cis_sync_delay, + transport_latency_c_to_p=self.Any, + transport_latency_p_to_c=self.Any, + phy_c_to_p=hci.SecondaryPhyType.LE_1M, + phy_p_to_c=hci.SecondaryPhyType.LE_1M, + nse=self.NSE, + bn_c_to_p=self.BN_C_TO_P, + bn_p_to_c=self.BN_P_TO_C, + ft_c_to_p=self.FT_C_TO_P, + ft_p_to_c=self.FT_P_TO_C, + max_pdu_c_to_p=self.Max_PDU_C_TO_P, + max_pdu_p_to_c=self.Max_PDU_P_TO_C, + iso_interval=self.ISO_Interval)) # 1. The Upper Tester orders the IUT to send a payload of the specified length to the Lower Testers. iso_sdu = [random.randint(1, 251) for n in range(self.Max_SDU_C_TO_P)] diff --git a/tools/rootcanal/test/LL/CIS/CEN/BV_26_C.py b/tools/rootcanal/test/LL/CIS/CEN/BV_26_C.py index 010ee283d3..d882211a04 100644 --- a/tools/rootcanal/test/LL/CIS/CEN/BV_26_C.py +++ b/tools/rootcanal/test/LL/CIS/CEN/BV_26_C.py @@ -146,22 +146,22 @@ class Test(ControllerTest): # CIS packet sent by the Lower Tester. The Connection_Handle parameter is set to the value # provided in the HCI_LE_Create_CIS command. await self.expect_evt( - hci.LeCisEstablished(status=ErrorCode.SUCCESS, - connection_handle=cis_connection_handle, - cig_sync_delay=cis_ind.cig_sync_delay, - cis_sync_delay=cis_ind.cis_sync_delay, - transport_latency_c_to_p=self.Any, - transport_latency_p_to_c=self.Any, - phy_c_to_p=hci.SecondaryPhyType.LE_1M, - phy_p_to_c=hci.SecondaryPhyType.LE_1M, - nse=cis_req.nse, - bn_c_to_p=cis_req.bn_c_to_p, - bn_p_to_c=cis_req.bn_p_to_c, - ft_c_to_p=cis_req.ft_c_to_p, - ft_p_to_c=cis_req.ft_p_to_c, - max_pdu_c_to_p=cis_req.max_pdu_c_to_p, - max_pdu_p_to_c=cis_req.max_pdu_p_to_c, - iso_interval=cis_req.iso_interval)) + hci.LeCisEstablishedV1(status=ErrorCode.SUCCESS, + connection_handle=cis_connection_handle, + cig_sync_delay=cis_ind.cig_sync_delay, + cis_sync_delay=cis_ind.cis_sync_delay, + transport_latency_c_to_p=self.Any, + transport_latency_p_to_c=self.Any, + phy_c_to_p=hci.SecondaryPhyType.LE_1M, + phy_p_to_c=hci.SecondaryPhyType.LE_1M, + nse=cis_req.nse, + bn_c_to_p=cis_req.bn_c_to_p, + bn_p_to_c=cis_req.bn_p_to_c, + ft_c_to_p=cis_req.ft_c_to_p, + ft_p_to_c=cis_req.ft_p_to_c, + max_pdu_c_to_p=cis_req.max_pdu_c_to_p, + max_pdu_p_to_c=cis_req.max_pdu_p_to_c, + iso_interval=cis_req.iso_interval)) # 7. The Upper Tester sends an HCI_LE_Setup_ISO_Data_Path command and receives a success # response from the IUT. @@ -318,22 +318,22 @@ class Test(ControllerTest): # 23. The IUT sends an HCI_LE_CIS_Established event to the Upper Tester. The Connection_Handle # parameter is set to the value provided in step 16. await self.expect_evt( - hci.LeCisEstablished(status=ErrorCode.SUCCESS, - connection_handle=cis_connection_handle, - cig_sync_delay=cis_ind.cig_sync_delay, - cis_sync_delay=cis_ind.cis_sync_delay, - transport_latency_c_to_p=self.Any, - transport_latency_p_to_c=self.Any, - phy_c_to_p=hci.SecondaryPhyType.LE_1M, - phy_p_to_c=hci.SecondaryPhyType.LE_1M, - nse=cis_req.nse, - bn_c_to_p=cis_req.bn_c_to_p, - bn_p_to_c=cis_req.bn_p_to_c, - ft_c_to_p=cis_req.ft_c_to_p, - ft_p_to_c=cis_req.ft_p_to_c, - max_pdu_c_to_p=cis_req.max_pdu_c_to_p, - max_pdu_p_to_c=cis_req.max_pdu_p_to_c, - iso_interval=cis_req.iso_interval)) + hci.LeCisEstablishedV1(status=ErrorCode.SUCCESS, + connection_handle=cis_connection_handle, + cig_sync_delay=cis_ind.cig_sync_delay, + cis_sync_delay=cis_ind.cis_sync_delay, + transport_latency_c_to_p=self.Any, + transport_latency_p_to_c=self.Any, + phy_c_to_p=hci.SecondaryPhyType.LE_1M, + phy_p_to_c=hci.SecondaryPhyType.LE_1M, + nse=cis_req.nse, + bn_c_to_p=cis_req.bn_c_to_p, + bn_p_to_c=cis_req.bn_p_to_c, + ft_c_to_p=cis_req.ft_c_to_p, + ft_p_to_c=cis_req.ft_p_to_c, + max_pdu_c_to_p=cis_req.max_pdu_c_to_p, + max_pdu_p_to_c=cis_req.max_pdu_p_to_c, + iso_interval=cis_req.iso_interval)) # 24. The Upper Tester sends an HCI_LE_Setup_ISO_Data_Path command to the IUT with # Connection_Handle set to the value provided in step 16 and Data_Path_Direction set to Output. diff --git a/tools/rootcanal/test/LL/CIS/PER/BV_01_C.py b/tools/rootcanal/test/LL/CIS/PER/BV_01_C.py index 63e3be15d1..358df99777 100644 --- a/tools/rootcanal/test/LL/CIS/PER/BV_01_C.py +++ b/tools/rootcanal/test/LL/CIS/PER/BV_01_C.py @@ -138,22 +138,22 @@ class Test(ControllerTest): # CIS packet sent by the Lower Tester. The Connection_Handle parameter is the # CIS_Connection_Handle value provided in the HCI_LE_CIS_Request event. await self.expect_evt( - hci.LeCisEstablished(status=ErrorCode.SUCCESS, - connection_handle=cis_connection_handle, - cig_sync_delay=self.CIG_Sync_Delay, - cis_sync_delay=self.CIS_Sync_Delay, - transport_latency_c_to_p=self.Any, - transport_latency_p_to_c=self.Any, - phy_c_to_p=hci.SecondaryPhyType.LE_1M, - phy_p_to_c=hci.SecondaryPhyType.LE_1M, - nse=self.NSE, - bn_c_to_p=self.BN_C_TO_P, - bn_p_to_c=self.BN_P_TO_C, - ft_c_to_p=self.FT_C_TO_P, - ft_p_to_c=self.FT_P_TO_C, - max_pdu_c_to_p=self.Max_PDU_C_TO_P, - max_pdu_p_to_c=self.Max_PDU_P_TO_C, - iso_interval=self.ISO_Interval)) + hci.LeCisEstablishedV1(status=ErrorCode.SUCCESS, + connection_handle=cis_connection_handle, + cig_sync_delay=self.CIG_Sync_Delay, + cis_sync_delay=self.CIS_Sync_Delay, + transport_latency_c_to_p=self.Any, + transport_latency_p_to_c=self.Any, + phy_c_to_p=hci.SecondaryPhyType.LE_1M, + phy_p_to_c=hci.SecondaryPhyType.LE_1M, + nse=self.NSE, + bn_c_to_p=self.BN_C_TO_P, + bn_p_to_c=self.BN_P_TO_C, + ft_c_to_p=self.FT_C_TO_P, + ft_p_to_c=self.FT_P_TO_C, + max_pdu_c_to_p=self.Max_PDU_C_TO_P, + max_pdu_p_to_c=self.Max_PDU_P_TO_C, + iso_interval=self.ISO_Interval)) # 9. The Upper Tester sends an HCI_LE_Setup_ISO_Data_Path command to the IUT with the output # path enabled and receives a successful HCI_Command_Complete in response. diff --git a/tools/rootcanal/test/LL/CON_/CEN/BV_41_C.py b/tools/rootcanal/test/LL/CON_/CEN/BV_41_C.py index 9d377ef54a..f8711d5c29 100644 --- a/tools/rootcanal/test/LL/CON_/CEN/BV_41_C.py +++ b/tools/rootcanal/test/LL/CON_/CEN/BV_41_C.py @@ -41,25 +41,26 @@ class Test(ControllerTest): # Prelude: Establish an ACL connection as central with the IUT. controller.send_cmd( - hci.LeExtendedCreateConnection(initiator_filter_policy=hci.InitiatorFilterPolicy.USE_PEER_ADDRESS, - own_address_type=hci.OwnAddressType.PUBLIC_DEVICE_ADDRESS, - peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, - peer_address=peer_address, - initiating_phys=0x1, - initiating_phy_parameters=[ - hci.InitiatingPhyParameters( - scan_interval=0x200, - scan_window=0x100, - connection_interval_min=0x200, - connection_interval_max=0x200, - max_latency=0x6, - supervision_timeout=0xc80, - min_ce_length=0, - max_ce_length=0, - ) - ])) - - await self.expect_evt(hci.LeExtendedCreateConnectionStatus(status=ErrorCode.SUCCESS, num_hci_command_packets=1)) + hci.LeExtendedCreateConnectionV1(initiator_filter_policy=hci.InitiatorFilterPolicy.USE_PEER_ADDRESS, + own_address_type=hci.OwnAddressType.PUBLIC_DEVICE_ADDRESS, + peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, + peer_address=peer_address, + initiating_phys=0x1, + initiating_phy_parameters=[ + hci.InitiatingPhyParameters( + scan_interval=0x200, + scan_window=0x100, + connection_interval_min=0x200, + connection_interval_max=0x200, + max_latency=0x6, + supervision_timeout=0xc80, + min_ce_length=0, + max_ce_length=0, + ) + ])) + + await self.expect_evt( + hci.LeExtendedCreateConnectionV1Status(status=ErrorCode.SUCCESS, num_hci_command_packets=1)) controller.send_ll(ll.LeLegacyAdvertisingPdu(source_address=peer_address, advertising_address_type=ll.AddressType.PUBLIC, @@ -86,15 +87,15 @@ class Test(ControllerTest): conn_supervision_timeout=0xc80)) await self.expect_evt( - hci.LeEnhancedConnectionComplete(status=ErrorCode.SUCCESS, - connection_handle=acl_connection_handle, - role=hci.Role.CENTRAL, - peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, - peer_address=peer_address, - connection_interval=0x200, - peripheral_latency=0x6, - supervision_timeout=0xc80, - central_clock_accuracy=hci.ClockAccuracy.PPM_500)) + hci.LeEnhancedConnectionCompleteV1(status=ErrorCode.SUCCESS, + connection_handle=acl_connection_handle, + role=hci.Role.CENTRAL, + peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, + peer_address=peer_address, + connection_interval=0x200, + peripheral_latency=0x6, + supervision_timeout=0xc80, + central_clock_accuracy=hci.ClockAccuracy.PPM_500)) await self.expect_evt( hci.LeChannelSelectionAlgorithm(connection_handle=acl_connection_handle, diff --git a/tools/rootcanal/test/LL/CON_/CEN/BV_43_C.py b/tools/rootcanal/test/LL/CON_/CEN/BV_43_C.py index 914df4cfe9..8d147c9cdb 100644 --- a/tools/rootcanal/test/LL/CON_/CEN/BV_43_C.py +++ b/tools/rootcanal/test/LL/CON_/CEN/BV_43_C.py @@ -38,25 +38,26 @@ class Test(ControllerTest): # Prelude: Establish an ACL connection as central with the IUT. controller.send_cmd( - hci.LeExtendedCreateConnection(initiator_filter_policy=hci.InitiatorFilterPolicy.USE_PEER_ADDRESS, - own_address_type=hci.OwnAddressType.PUBLIC_DEVICE_ADDRESS, - peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, - peer_address=peer_address, - initiating_phys=0x1, - initiating_phy_parameters=[ - hci.InitiatingPhyParameters( - scan_interval=0x200, - scan_window=0x100, - connection_interval_min=0x200, - connection_interval_max=0x200, - max_latency=0x6, - supervision_timeout=0xc80, - min_ce_length=0, - max_ce_length=0, - ) - ])) - - await self.expect_evt(hci.LeExtendedCreateConnectionStatus(status=ErrorCode.SUCCESS, num_hci_command_packets=1)) + hci.LeExtendedCreateConnectionV1(initiator_filter_policy=hci.InitiatorFilterPolicy.USE_PEER_ADDRESS, + own_address_type=hci.OwnAddressType.PUBLIC_DEVICE_ADDRESS, + peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, + peer_address=peer_address, + initiating_phys=0x1, + initiating_phy_parameters=[ + hci.InitiatingPhyParameters( + scan_interval=0x200, + scan_window=0x100, + connection_interval_min=0x200, + connection_interval_max=0x200, + max_latency=0x6, + supervision_timeout=0xc80, + min_ce_length=0, + max_ce_length=0, + ) + ])) + + await self.expect_evt( + hci.LeExtendedCreateConnectionV1Status(status=ErrorCode.SUCCESS, num_hci_command_packets=1)) controller.send_ll(ll.LeLegacyAdvertisingPdu(source_address=peer_address, advertising_address_type=ll.AddressType.PUBLIC, @@ -83,15 +84,15 @@ class Test(ControllerTest): conn_supervision_timeout=0xc80)) await self.expect_evt( - hci.LeEnhancedConnectionComplete(status=ErrorCode.SUCCESS, - connection_handle=acl_connection_handle, - role=hci.Role.CENTRAL, - peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, - peer_address=peer_address, - connection_interval=0x200, - peripheral_latency=0x6, - supervision_timeout=0xc80, - central_clock_accuracy=hci.ClockAccuracy.PPM_500)) + hci.LeEnhancedConnectionCompleteV1(status=ErrorCode.SUCCESS, + connection_handle=acl_connection_handle, + role=hci.Role.CENTRAL, + peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, + peer_address=peer_address, + connection_interval=0x200, + peripheral_latency=0x6, + supervision_timeout=0xc80, + central_clock_accuracy=hci.ClockAccuracy.PPM_500)) await self.expect_evt( hci.LeChannelSelectionAlgorithm(connection_handle=acl_connection_handle, diff --git a/tools/rootcanal/test/LL/CON_/INI/BV_08_C.py b/tools/rootcanal/test/LL/CON_/INI/BV_08_C.py index bfc23e8a9c..81eaded5df 100644 --- a/tools/rootcanal/test/LL/CON_/INI/BV_08_C.py +++ b/tools/rootcanal/test/LL/CON_/INI/BV_08_C.py @@ -116,16 +116,16 @@ class Test(ControllerTest): # 6. Upper Tester receives an HCI_LE_Enhanced_Connection_Complete event from the IUT # including the Lower Tester address and connection interval selected. connect_complete = await self.expect_evt( - hci.LeEnhancedConnectionComplete(status=ErrorCode.SUCCESS, - connection_handle=self.Any, - role=hci.Role.CENTRAL, - peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, - peer_address=peer_address, - connection_interval=0x200, - peripheral_latency=0x6, - supervision_timeout=0xc80, - local_resolvable_private_address=connect_ind.source_address, - central_clock_accuracy=hci.ClockAccuracy.PPM_500)) + hci.LeEnhancedConnectionCompleteV1(status=ErrorCode.SUCCESS, + connection_handle=self.Any, + role=hci.Role.CENTRAL, + peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, + peer_address=peer_address, + connection_interval=0x200, + peripheral_latency=0x6, + supervision_timeout=0xc80, + local_resolvable_private_address=connect_ind.source_address, + central_clock_accuracy=hci.ClockAccuracy.PPM_500)) # 7. After the CONNECT_IND has been received, the Lower Tester receives the first correctly # formatted LL Data Channel PDU on the data channel. diff --git a/tools/rootcanal/test/LL/CON_/INI/BV_09_C.py b/tools/rootcanal/test/LL/CON_/INI/BV_09_C.py index 782c25ec33..1107924c12 100644 --- a/tools/rootcanal/test/LL/CON_/INI/BV_09_C.py +++ b/tools/rootcanal/test/LL/CON_/INI/BV_09_C.py @@ -144,17 +144,17 @@ class Test(ControllerTest): # 10. Upper Tester receives an HCI_LE_Enhanced_Connection_Complete event from the IUT # including the Lower Tester’s RPA and Identity address and connection interval selected. connect_complete = await self.expect_evt( - hci.LeEnhancedConnectionComplete(status=ErrorCode.SUCCESS, - connection_handle=self.Any, - role=hci.Role.CENTRAL, - peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, - peer_address=peer_address, - peer_resolvable_private_address=peer_resolvable_address, - local_resolvable_private_address=connect_ind.source_address, - connection_interval=0x200, - peripheral_latency=0x6, - supervision_timeout=0xc80, - central_clock_accuracy=hci.ClockAccuracy.PPM_500)) + hci.LeEnhancedConnectionCompleteV1(status=ErrorCode.SUCCESS, + connection_handle=self.Any, + role=hci.Role.CENTRAL, + peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, + peer_address=peer_address, + peer_resolvable_private_address=peer_resolvable_address, + local_resolvable_private_address=connect_ind.source_address, + connection_interval=0x200, + peripheral_latency=0x6, + supervision_timeout=0xc80, + central_clock_accuracy=hci.ClockAccuracy.PPM_500)) # 11. After the CONNECT_IND has been received, the Lower Tester receives the first correctly # formatted LL Data Channel PDU on the data channel. diff --git a/tools/rootcanal/test/LL/CON_/INI/BV_10_C.py b/tools/rootcanal/test/LL/CON_/INI/BV_10_C.py index faa3d90b4b..705e83ebd2 100644 --- a/tools/rootcanal/test/LL/CON_/INI/BV_10_C.py +++ b/tools/rootcanal/test/LL/CON_/INI/BV_10_C.py @@ -144,16 +144,16 @@ class Test(ControllerTest): # 10. Upper Tester receives an HCI_LE_Enhanced_Connection_Complete event from the IUT # including the Lower Tester address and connection interval selected. connect_complete = await self.expect_evt( - hci.LeEnhancedConnectionComplete(status=ErrorCode.SUCCESS, - connection_handle=self.Any, - role=hci.Role.CENTRAL, - peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, - peer_address=peer_address, - peer_resolvable_private_address=peer_resolvable_address, - connection_interval=0x200, - peripheral_latency=0x6, - supervision_timeout=0xc80, - central_clock_accuracy=hci.ClockAccuracy.PPM_500)) + hci.LeEnhancedConnectionCompleteV1(status=ErrorCode.SUCCESS, + connection_handle=self.Any, + role=hci.Role.CENTRAL, + peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, + peer_address=peer_address, + peer_resolvable_private_address=peer_resolvable_address, + connection_interval=0x200, + peripheral_latency=0x6, + supervision_timeout=0xc80, + central_clock_accuracy=hci.ClockAccuracy.PPM_500)) # 11. After the CONNECT_IND has been received, the Lower Tester receives the first correctly # formatted LL Data Channel PDU on the data channel. diff --git a/tools/rootcanal/test/LL/CON_/INI/BV_11_C.py b/tools/rootcanal/test/LL/CON_/INI/BV_11_C.py index bb5341268e..301c7addac 100644 --- a/tools/rootcanal/test/LL/CON_/INI/BV_11_C.py +++ b/tools/rootcanal/test/LL/CON_/INI/BV_11_C.py @@ -152,17 +152,17 @@ class Test(ControllerTest): # 10. Upper Tester receives an HCI_LE_Enhanced_Connection_Complete event from the IUT # including the Lower Tester address and connection interval selected. connect_complete = await self.expect_evt( - hci.LeEnhancedConnectionComplete(status=ErrorCode.SUCCESS, - connection_handle=self.Any, - role=hci.Role.CENTRAL, - peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, - peer_address=peer_address, - peer_resolvable_private_address=peer_resolvable_address, - local_resolvable_private_address=connect_ind.source_address, - connection_interval=0x200, - peripheral_latency=0x6, - supervision_timeout=0xc80, - central_clock_accuracy=hci.ClockAccuracy.PPM_500)) + hci.LeEnhancedConnectionCompleteV1(status=ErrorCode.SUCCESS, + connection_handle=self.Any, + role=hci.Role.CENTRAL, + peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, + peer_address=peer_address, + peer_resolvable_private_address=peer_resolvable_address, + local_resolvable_private_address=connect_ind.source_address, + connection_interval=0x200, + peripheral_latency=0x6, + supervision_timeout=0xc80, + central_clock_accuracy=hci.ClockAccuracy.PPM_500)) # 11. After the CONNECT_IND has been received, the Lower Tester receives the first correctly # formatted LL Data Channel PDU on the data channel. diff --git a/tools/rootcanal/test/LL/CON_/PER/BV_40_C.py b/tools/rootcanal/test/LL/CON_/PER/BV_40_C.py index 045bca32a3..f3f2eaedc0 100644 --- a/tools/rootcanal/test/LL/CON_/PER/BV_40_C.py +++ b/tools/rootcanal/test/LL/CON_/PER/BV_40_C.py @@ -72,15 +72,15 @@ class Test(ControllerTest): conn_supervision_timeout=0x200)) await self.expect_evt( - hci.LeEnhancedConnectionComplete(status=ErrorCode.SUCCESS, - connection_handle=acl_connection_handle, - role=hci.Role.PERIPHERAL, - peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, - peer_address=peer_address, - connection_interval=0x200, - peripheral_latency=0x200, - supervision_timeout=0x200, - central_clock_accuracy=hci.ClockAccuracy.PPM_500)) + hci.LeEnhancedConnectionCompleteV1(status=ErrorCode.SUCCESS, + connection_handle=acl_connection_handle, + role=hci.Role.PERIPHERAL, + peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, + peer_address=peer_address, + connection_interval=0x200, + peripheral_latency=0x200, + supervision_timeout=0x200, + central_clock_accuracy=hci.ClockAccuracy.PPM_500)) test_rounds = [ TestRound(0x00, 0x01, 0x03, 0x02, 0x00), diff --git a/tools/rootcanal/test/LL/CON_/PER/BV_42_C.py b/tools/rootcanal/test/LL/CON_/PER/BV_42_C.py index ae067c2269..3c7545dceb 100644 --- a/tools/rootcanal/test/LL/CON_/PER/BV_42_C.py +++ b/tools/rootcanal/test/LL/CON_/PER/BV_42_C.py @@ -72,15 +72,15 @@ class Test(ControllerTest): conn_supervision_timeout=0x200)) await self.expect_evt( - hci.LeEnhancedConnectionComplete(status=ErrorCode.SUCCESS, - connection_handle=acl_connection_handle, - role=hci.Role.PERIPHERAL, - peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, - peer_address=peer_address, - connection_interval=0x200, - peripheral_latency=0x200, - supervision_timeout=0x200, - central_clock_accuracy=hci.ClockAccuracy.PPM_500)) + hci.LeEnhancedConnectionCompleteV1(status=ErrorCode.SUCCESS, + connection_handle=acl_connection_handle, + role=hci.Role.PERIPHERAL, + peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, + peer_address=peer_address, + connection_interval=0x200, + peripheral_latency=0x200, + supervision_timeout=0x200, + central_clock_accuracy=hci.ClockAccuracy.PPM_500)) # 1. Upper Tester sends an HCI_LE_Set_PHY command to the IUT with the ALL_PHYS fields set to a # value of 0x03. Upper Tester receives an HCI_Command_Status event indicating success in diff --git a/tools/rootcanal/test/LL/DDI/ADV/BV_06_C.py b/tools/rootcanal/test/LL/DDI/ADV/BV_06_C.py index f52edd3deb..f7ed090fa9 100644 --- a/tools/rootcanal/test/LL/DDI/ADV/BV_06_C.py +++ b/tools/rootcanal/test/LL/DDI/ADV/BV_06_C.py @@ -90,15 +90,15 @@ class Test(ControllerTest): # 6. Upper Tester receives an HCI_LE_Connection_Complete event from the IUT including the # parameters sent to the IUT in step 4. await self.expect_evt( - hci.LeEnhancedConnectionComplete(status=ErrorCode.SUCCESS, - connection_handle=connection_handle, - role=hci.Role.PERIPHERAL, - peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, - peer_address=peer_address, - connection_interval=LL_initiator_connInterval, - peripheral_latency=LL_initiator_connPeripheralLatency, - supervision_timeout=LL_initiator_connSupervisionTimeout, - central_clock_accuracy=hci.ClockAccuracy.PPM_500)) + hci.LeEnhancedConnectionCompleteV1(status=ErrorCode.SUCCESS, + connection_handle=connection_handle, + role=hci.Role.PERIPHERAL, + peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, + peer_address=peer_address, + connection_interval=LL_initiator_connInterval, + peripheral_latency=LL_initiator_connPeripheralLatency, + supervision_timeout=LL_initiator_connSupervisionTimeout, + central_clock_accuracy=hci.ClockAccuracy.PPM_500)) # 7. The Upper Tester sends an HCI_Disconnect command to the IUT with the Connection_Handle # and receives a successful HCI_Command_Status event in return. diff --git a/tools/rootcanal/test/LL/DDI/ADV/BV_07_C.py b/tools/rootcanal/test/LL/DDI/ADV/BV_07_C.py index 271a4fc564..afc834fd00 100644 --- a/tools/rootcanal/test/LL/DDI/ADV/BV_07_C.py +++ b/tools/rootcanal/test/LL/DDI/ADV/BV_07_C.py @@ -120,15 +120,15 @@ class Test(ControllerTest): # 9. Upper Tester receives an HCI_LE_Connection_Complete event from the IUT including the # parameters sent to the IUT. await self.expect_evt( - hci.LeEnhancedConnectionComplete(status=ErrorCode.SUCCESS, - connection_handle=connection_handle, - role=hci.Role.PERIPHERAL, - peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, - peer_address=peer_address, - connection_interval=LL_initiator_connInterval, - peripheral_latency=LL_initiator_connPeripheralLatency, - supervision_timeout=LL_initiator_connSupervisionTimeout, - central_clock_accuracy=hci.ClockAccuracy.PPM_500)) + hci.LeEnhancedConnectionCompleteV1(status=ErrorCode.SUCCESS, + connection_handle=connection_handle, + role=hci.Role.PERIPHERAL, + peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, + peer_address=peer_address, + connection_interval=LL_initiator_connInterval, + peripheral_latency=LL_initiator_connPeripheralLatency, + supervision_timeout=LL_initiator_connSupervisionTimeout, + central_clock_accuracy=hci.ClockAccuracy.PPM_500)) # 10. Peripheral Connection Terminated (connection interval, Peripheral latency, timeout, channel map, # un-encrypted, connection handle from step 9). diff --git a/tools/rootcanal/test/LL/DDI/ADV/BV_09_C.py b/tools/rootcanal/test/LL/DDI/ADV/BV_09_C.py index 719ddc76e3..d5e1c16602 100644 --- a/tools/rootcanal/test/LL/DDI/ADV/BV_09_C.py +++ b/tools/rootcanal/test/LL/DDI/ADV/BV_09_C.py @@ -303,7 +303,7 @@ class Test(ControllerTest): # 13. Upper Tester receives an HCI_LE_Connection_Complete event from the IUT including the # parameters sent to the IUT. await self.expect_evt( - hci.LeEnhancedConnectionComplete( + hci.LeEnhancedConnectionCompleteV1( status=ErrorCode.SUCCESS, connection_handle=connection_handle, role=hci.Role.PERIPHERAL, @@ -373,7 +373,7 @@ class Test(ControllerTest): # parameters sent to the IUT in step 25 and as postamble: Peripheral Connection Terminated # (connection interval, Peripheral latency, timeout, channel map, un-encrypted, connection handle). await self.expect_evt( - hci.LeEnhancedConnectionComplete( + hci.LeEnhancedConnectionCompleteV1( status=ErrorCode.SUCCESS, connection_handle=connection_handle, role=hci.Role.PERIPHERAL, diff --git a/tools/rootcanal/test/LL/DDI/ADV/BV_11_C.py b/tools/rootcanal/test/LL/DDI/ADV/BV_11_C.py index 0a01918f7d..a322a17519 100644 --- a/tools/rootcanal/test/LL/DDI/ADV/BV_11_C.py +++ b/tools/rootcanal/test/LL/DDI/ADV/BV_11_C.py @@ -116,28 +116,27 @@ class Test(ControllerTest): rssi=-16) # Note: Link layer sends LeConnectComplete here. - await self.expect_ll( - ll.LeConnectComplete(source_address=controller.address, - destination_address=peer_address, - initiating_address_type=ll.AddressType.PUBLIC, - advertising_address_type=ll.AddressType.PUBLIC, - conn_interval=self.LL_initiator_connInterval, - conn_peripheral_latency=self.LL_initiator_connPeripheralLatency, - conn_supervision_timeout=self.LL_initiator_connSupervisionTimeout), - ignored_pdus=[ll.LeLegacyAdvertisingPdu]) + await self.expect_ll(ll.LeConnectComplete(source_address=controller.address, + destination_address=peer_address, + initiating_address_type=ll.AddressType.PUBLIC, + advertising_address_type=ll.AddressType.PUBLIC, + conn_interval=self.LL_initiator_connInterval, + conn_peripheral_latency=self.LL_initiator_connPeripheralLatency, + conn_supervision_timeout=self.LL_initiator_connSupervisionTimeout), + ignored_pdus=[ll.LeLegacyAdvertisingPdu]) # 11. Upper Tester receives an HCI_LE_Connection_Complete event from the IUT including the # parameters sent to the IUT in step 8. await self.expect_evt( - hci.LeEnhancedConnectionComplete(status=ErrorCode.SUCCESS, - connection_handle=connection_handle, - role=hci.Role.PERIPHERAL, - peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, - peer_address=peer_address, - connection_interval=self.LL_initiator_connInterval, - peripheral_latency=self.LL_initiator_connPeripheralLatency, - supervision_timeout=self.LL_initiator_connSupervisionTimeout, - central_clock_accuracy=hci.ClockAccuracy.PPM_500)) + hci.LeEnhancedConnectionCompleteV1(status=ErrorCode.SUCCESS, + connection_handle=connection_handle, + role=hci.Role.PERIPHERAL, + peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, + peer_address=peer_address, + connection_interval=self.LL_initiator_connInterval, + peripheral_latency=self.LL_initiator_connPeripheralLatency, + supervision_timeout=self.LL_initiator_connSupervisionTimeout, + central_clock_accuracy=hci.ClockAccuracy.PPM_500)) # 12. Upper Tester receives an HCI_LE_Disconnection_Complete event from the IUT with the reason # parameter indicating ‘connection failed to be established’, with the connection handle parameter diff --git a/tools/rootcanal/test/LL/DDI/ADV/BV_19_C.py b/tools/rootcanal/test/LL/DDI/ADV/BV_19_C.py index 9247324a4f..80a8de4065 100644 --- a/tools/rootcanal/test/LL/DDI/ADV/BV_19_C.py +++ b/tools/rootcanal/test/LL/DDI/ADV/BV_19_C.py @@ -107,15 +107,15 @@ class Test(ControllerTest): # 10. Upper Tester receives an HCI_LE_Connection_Complete event from the IUT including the # parameters sent to the IUT in step 7. await self.expect_evt( - hci.LeEnhancedConnectionComplete(status=ErrorCode.SUCCESS, - connection_handle=connection_handle, - role=hci.Role.PERIPHERAL, - peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, - peer_address=public_peer_address, - connection_interval=self.LL_initiator_connInterval, - peripheral_latency=self.LL_initiator_connPeripheralLatency, - supervision_timeout=self.LL_initiator_connSupervisionTimeout, - central_clock_accuracy=hci.ClockAccuracy.PPM_500)) + hci.LeEnhancedConnectionCompleteV1(status=ErrorCode.SUCCESS, + connection_handle=connection_handle, + role=hci.Role.PERIPHERAL, + peer_address_type=hci.AddressType.PUBLIC_DEVICE_ADDRESS, + peer_address=public_peer_address, + connection_interval=self.LL_initiator_connInterval, + peripheral_latency=self.LL_initiator_connPeripheralLatency, + supervision_timeout=self.LL_initiator_connSupervisionTimeout, + central_clock_accuracy=hci.ClockAccuracy.PPM_500)) # 11. Upper Tester receives an HCI_Disconnection_Complete event from the IUT once the # Establishment Timeout has expired. diff --git a/tools/rootcanal/test/LL/DDI/ADV/BV_21_C.py b/tools/rootcanal/test/LL/DDI/ADV/BV_21_C.py index 064194cf38..56ac692fa2 100644 --- a/tools/rootcanal/test/LL/DDI/ADV/BV_21_C.py +++ b/tools/rootcanal/test/LL/DDI/ADV/BV_21_C.py @@ -27,6 +27,14 @@ class Test(ControllerTest): LL_advertiser_advInterval_MAX = 0x200 LL_advertiser_Adv_Channel_Map = 0x7 + ADV_NONCONN_IND = hci.AdvertisingEventProperties( + connectable=0, + scannable=0, + directed=0, + high_duty_cycle=0, + legacy=1, + ) + # LL/DDI/ADV/BV-21-C [Extended Advertising, Legacy PDUs, Non-Connectable] async def test(self): controller = self.controller @@ -37,9 +45,9 @@ class Test(ControllerTest): # Advertising_Event_Properties parameter shall be set to 00010000b (ADV_NONCONN_IND # legacy PDU). controller.send_cmd( - hci.LeSetExtendedAdvertisingParametersLegacy( + hci.LeSetExtendedAdvertisingParametersV1( advertising_handle=0, - legacy_advertising_event_properties=hci.LegacyAdvertisingEventProperties.ADV_NONCONN_IND, + advertising_event_properties=self.ADV_NONCONN_IND, primary_advertising_interval_min=self.LL_advertiser_advInterval_MIN, primary_advertising_interval_max=self.LL_advertiser_advInterval_MAX, primary_advertising_channel_map=self.LL_advertiser_Adv_Channel_Map, @@ -47,7 +55,7 @@ class Test(ControllerTest): advertising_filter_policy=hci.AdvertisingFilterPolicy.ALL_DEVICES)) await self.expect_evt( - hci.LeSetExtendedAdvertisingParametersComplete(status=ErrorCode.SUCCESS, num_hci_command_packets=1)) + hci.LeSetExtendedAdvertisingParametersV1Complete(status=ErrorCode.SUCCESS, num_hci_command_packets=1)) # For each round from 1–3 based on Table 4.2: await self.steps_3_8(advertising_data=[1]) diff --git a/tools/rootcanal/test/LL/DDI/ADV/BV_22_C.py b/tools/rootcanal/test/LL/DDI/ADV/BV_22_C.py index dd8b5b19cc..0585800caa 100644 --- a/tools/rootcanal/test/LL/DDI/ADV/BV_22_C.py +++ b/tools/rootcanal/test/LL/DDI/ADV/BV_22_C.py @@ -27,6 +27,14 @@ class Test(ControllerTest): LL_advertiser_advInterval_MAX = 0x200 LL_advertiser_Adv_Channel_Map = 0x7 + ADV_IND = hci.AdvertisingEventProperties( + connectable=1, + scannable=1, + directed=0, + high_duty_cycle=0, + legacy=1, + ) + # LL/DDI/ADV/BV-22-C [Extended Advertising, Legacy PDUs, Undirected, CSA #2] async def test(self): controller = self.controller @@ -36,9 +44,9 @@ class Test(ControllerTest): # IUT using all supported advertising channels and minimum advertising interval. The # Advertising_Event_Properties parameter shall be set to 00010011b (ADV_IND legacy PDU). controller.send_cmd( - hci.LeSetExtendedAdvertisingParametersLegacy( + hci.LeSetExtendedAdvertisingParametersV1( advertising_handle=0, - legacy_advertising_event_properties=hci.LegacyAdvertisingEventProperties.ADV_IND, + advertising_event_properties=self.ADV_IND, primary_advertising_interval_min=self.LL_advertiser_advInterval_MIN, primary_advertising_interval_max=self.LL_advertiser_advInterval_MAX, primary_advertising_channel_map=self.LL_advertiser_Adv_Channel_Map, @@ -46,7 +54,7 @@ class Test(ControllerTest): advertising_filter_policy=hci.AdvertisingFilterPolicy.ALL_DEVICES)) await self.expect_evt( - hci.LeSetExtendedAdvertisingParametersComplete(status=ErrorCode.SUCCESS, num_hci_command_packets=1)) + hci.LeSetExtendedAdvertisingParametersV1Complete(status=ErrorCode.SUCCESS, num_hci_command_packets=1)) # 8. Repeat steps 3–7 for each Round shown in Table 4.4. await self.steps_3_7(advertising_data=[1]) diff --git a/tools/rootcanal/test/LL/DDI/ADV/BV_26_C.py b/tools/rootcanal/test/LL/DDI/ADV/BV_26_C.py index 24bc1d16f8..745ead263b 100644 --- a/tools/rootcanal/test/LL/DDI/ADV/BV_26_C.py +++ b/tools/rootcanal/test/LL/DDI/ADV/BV_26_C.py @@ -83,29 +83,30 @@ class Test(ControllerTest): # shall be set to 0x0000. The Primary_Advertising_PHY and Secondary_Advertising_PHY shall be # set to the values specified in Table 4.9. controller.send_cmd( - hci.LeSetExtendedAdvertisingParameters(advertising_handle=0, - advertising_event_properties=hci.AdvertisingEventProperties(), - primary_advertising_interval_min=self.LL_advertiser_advInterval_MIN, - primary_advertising_interval_max=self.LL_advertiser_advInterval_MAX, - primary_advertising_channel_map=self.LL_advertiser_Adv_Channel_Map, - own_address_type=hci.OwnAddressType.PUBLIC_DEVICE_ADDRESS, - advertising_filter_policy=hci.AdvertisingFilterPolicy.ALL_DEVICES, - primary_advertising_phy=hci.PrimaryPhyType.LE_1M)) + hci.LeSetExtendedAdvertisingParametersV1( + advertising_handle=0, + advertising_event_properties=hci.AdvertisingEventProperties(), + primary_advertising_interval_min=self.LL_advertiser_advInterval_MIN, + primary_advertising_interval_max=self.LL_advertiser_advInterval_MAX, + primary_advertising_channel_map=self.LL_advertiser_Adv_Channel_Map, + own_address_type=hci.OwnAddressType.PUBLIC_DEVICE_ADDRESS, + advertising_filter_policy=hci.AdvertisingFilterPolicy.ALL_DEVICES, + primary_advertising_phy=hci.PrimaryPhyType.LE_1M)) await self.expect_evt( - hci.LeSetExtendedAdvertisingParametersComplete(status=ErrorCode.SUCCESS, num_hci_command_packets=1)) + hci.LeSetExtendedAdvertisingParametersV1Complete(status=ErrorCode.SUCCESS, num_hci_command_packets=1)) # 4. The Upper Tester sends an HCI_LE_Set_Periodic_Advertising_Parameters command to the IUT # using all supported advertising channels and selected periodic interval. # Periodic_Advertising_Properties parameter shall be set to 0x0000. controller.send_cmd( - hci.LeSetPeriodicAdvertisingParameters(advertising_handle=0, - periodic_advertising_interval_min=0x100, - periodic_advertising_interval_max=0x100, - include_tx_power=False)) + hci.LeSetPeriodicAdvertisingParametersV1(advertising_handle=0, + periodic_advertising_interval_min=0x100, + periodic_advertising_interval_max=0x100, + include_tx_power=False)) await self.expect_evt( - hci.LeSetPeriodicAdvertisingParametersComplete(status=ErrorCode.SUCCESS, num_hci_command_packets=1)) + hci.LeSetPeriodicAdvertisingParametersV1Complete(status=ErrorCode.SUCCESS, num_hci_command_packets=1)) # 5. The Upper Tester sends one or more HCI_LE_Set_Periodic_Advertising_Data commands to the # IUT with values according to Table 4.10 and using random octets from 1 to 254 as the payload. If diff --git a/tools/rootcanal/test/LL/DDI/ADV/BV_47_C.py b/tools/rootcanal/test/LL/DDI/ADV/BV_47_C.py index 64b471805d..7549daaccd 100644 --- a/tools/rootcanal/test/LL/DDI/ADV/BV_47_C.py +++ b/tools/rootcanal/test/LL/DDI/ADV/BV_47_C.py @@ -32,7 +32,7 @@ def make_advertising_event_properties(properties: int) -> hci.AdvertisingEventPr high_duty_cycle=(properties & 0x8) != 0, legacy=(properties & 0x10) != 0, anonymous=(properties & 0x20) != 0, - tx_power=(properties & 0x40) != 0) + include_tx_power=(properties & 0x40) != 0) @dataclass @@ -107,17 +107,18 @@ class Test(ControllerTest): # Peer_Address_Type shall be set to 0x00 (Public Device Address), and the Peer_Address shall be # set to the Lower Tester’s address. controller.send_cmd( - hci.LeSetExtendedAdvertisingParameters(advertising_handle=0, - advertising_event_properties=advertising_event_properties, - primary_advertising_interval_min=self.LL_advertiser_advInterval_MIN, - primary_advertising_interval_max=self.LL_advertiser_advInterval_MAX, - primary_advertising_channel_map=self.LL_advertiser_Adv_Channel_Map, - own_address_type=hci.OwnAddressType.PUBLIC_DEVICE_ADDRESS, - advertising_filter_policy=hci.AdvertisingFilterPolicy.ALL_DEVICES, - primary_advertising_phy=hci.PrimaryPhyType.LE_1M)) + hci.LeSetExtendedAdvertisingParametersV1( + advertising_handle=0, + advertising_event_properties=advertising_event_properties, + primary_advertising_interval_min=self.LL_advertiser_advInterval_MIN, + primary_advertising_interval_max=self.LL_advertiser_advInterval_MAX, + primary_advertising_channel_map=self.LL_advertiser_Adv_Channel_Map, + own_address_type=hci.OwnAddressType.PUBLIC_DEVICE_ADDRESS, + advertising_filter_policy=hci.AdvertisingFilterPolicy.ALL_DEVICES, + primary_advertising_phy=hci.PrimaryPhyType.LE_1M)) await self.expect_evt( - hci.LeSetExtendedAdvertisingParametersComplete(status=ErrorCode.SUCCESS, num_hci_command_packets=1)) + hci.LeSetExtendedAdvertisingParametersV1Complete(status=ErrorCode.SUCCESS, num_hci_command_packets=1)) # 4. The Upper Tester sends one or more HCI_LE_Set_Extended_Advertising_Data commands to the # IUT with values according to Table 4.6 and using random octets from 1 to 254 as the payload. If diff --git a/tools/rootcanal/test/LL/DDI/SCN/BV_79_C.py b/tools/rootcanal/test/LL/DDI/SCN/BV_79_C.py index c58b7e9029..c85f74067e 100644 --- a/tools/rootcanal/test/LL/DDI/SCN/BV_79_C.py +++ b/tools/rootcanal/test/LL/DDI/SCN/BV_79_C.py @@ -153,7 +153,7 @@ class Test(ControllerTest): # Tester containing a Status of 0x00 (Success), Sync_Handle set to a valid value, and the # Advertising_SID received in step 3. await self.expect_evt( - hci.LePeriodicAdvertisingSyncEstablished( + hci.LePeriodicAdvertisingSyncEstablishedV1( status=ErrorCode.SUCCESS, sync_handle=0, advertising_sid=advertising_sid, @@ -193,10 +193,10 @@ class Test(ControllerTest): fragment_length = min(max_fragment_length, remaining_length) data_status = hci.DataStatus.CONTINUING if remaining_length > max_fragment_length else hci.DataStatus.COMPLETE await self.expect_evt( - hci.LePeriodicAdvertisingReport(sync_handle=0, - tx_power=tx_power, - rssi=0x10, - cte_type=hci.CteType.NO_CONSTANT_TONE_EXTENSION, - data_status=data_status, - data=advertising_data[offset:offset + fragment_length])) + hci.LePeriodicAdvertisingReportV1(sync_handle=0, + tx_power=tx_power, + rssi=0x10, + cte_type=hci.CteType.NO_CONSTANT_TONE_EXTENSION, + data_status=data_status, + data=advertising_data[offset:offset + fragment_length])) offset += fragment_length diff --git a/tools/rootcanal/test/LL/SEC/ADV/BV_11_C.py b/tools/rootcanal/test/LL/SEC/ADV/BV_11_C.py index ff100c5234..d250619eaa 100644 --- a/tools/rootcanal/test/LL/SEC/ADV/BV_11_C.py +++ b/tools/rootcanal/test/LL/SEC/ADV/BV_11_C.py @@ -144,7 +144,7 @@ class Test(ControllerTest): conn_supervision_timeout=0xc80)) connection_complete_evt = await self.expect_evt( - hci.LeEnhancedConnectionComplete( + hci.LeEnhancedConnectionCompleteV1( status=hci.ErrorCode.SUCCESS, connection_handle=self.Any, role=hci.Role.PERIPHERAL, diff --git a/tools/rootcanal/test/controller/le/le_scanning_filter_duplicates_test.cc b/tools/rootcanal/test/controller/le/le_scanning_filter_duplicates_test.cc index 6a817ce6bf..0c4fbab669 100644 --- a/tools/rootcanal/test/controller/le/le_scanning_filter_duplicates_test.cc +++ b/tools/rootcanal/test/controller/le/le_scanning_filter_duplicates_test.cc @@ -49,9 +49,9 @@ public: // Set event mask to receive (extended) Advertising Reports controller_.SetEventMask(to_mask(EventCode::LE_META_EVENT)); - controller_.SetLeEventMask(to_mask(SubeventCode::ADVERTISING_REPORT) | - to_mask(SubeventCode::EXTENDED_ADVERTISING_REPORT) | - to_mask(SubeventCode::DIRECTED_ADVERTISING_REPORT)); + controller_.SetLeEventMask(to_mask(SubeventCode::LE_ADVERTISING_REPORT) | + to_mask(SubeventCode::LE_EXTENDED_ADVERTISING_REPORT) | + to_mask(SubeventCode::LE_DIRECTED_ADVERTISING_REPORT)); } void StartScan(FilterDuplicates filter_duplicates) { diff --git a/tools/rootcanal/test/controller/le/test_helpers.h b/tools/rootcanal/test/controller/le/test_helpers.h index 45d3257496..78978f7b42 100644 --- a/tools/rootcanal/test/controller/le/test_helpers.h +++ b/tools/rootcanal/test/controller/le/test_helpers.h @@ -35,7 +35,7 @@ enum : unsigned { properties.high_duty_cycle_ = (mask & HIGH_DUTY_CYCLE) != 0; properties.legacy_ = (mask & LEGACY) != 0; properties.anonymous_ = (mask & ANONYMOUS) != 0; - properties.tx_power_ = (mask & TX_POWER) != 0; + properties.include_tx_power_ = (mask & TX_POWER) != 0; return properties; } |