Merge "Floss: fix |A2dpCodecConfig| parameters" into main
diff --git a/Android.bp b/Android.bp
index d585c6c..2066ba6 100644
--- a/Android.bp
+++ b/Android.bp
@@ -70,5 +70,5 @@
"-Werror=reorder-init-list",
],
c_std: "c99",
- cpp_std: "c++17",
+ cpp_std: "c++20",
}
diff --git a/android/app/Android.bp b/android/app/Android.bp
index e97384e..76f2bed 100644
--- a/android/app/Android.bp
+++ b/android/app/Android.bp
@@ -148,6 +148,7 @@
"server_configurable_flags",
],
shared_libs: [
+ "libPlatformProperties",
"libaaudio",
"libbinder_ndk",
"libcrypto",
diff --git a/android/app/AndroidManifest.xml b/android/app/AndroidManifest.xml
index c87c771..c0548dd 100644
--- a/android/app/AndroidManifest.xml
+++ b/android/app/AndroidManifest.xml
@@ -110,6 +110,7 @@
android:permission="android.permission.BLUETOOTH_PRIVILEGED">
<intent-filter>
<action android:name="android.bluetooth.notification.action.SEND_TOGGLE_NOTIFICATION"/>
+ <action android:name="android.bluetooth.notification.action.AUTO_ON_USER_ACTION"/>
</intent-filter>
</service>
diff --git a/android/app/aidl/android/bluetooth/IBluetoothHidHost.aidl b/android/app/aidl/android/bluetooth/IBluetoothHidHost.aidl
index 421e1ad..1753700 100644
--- a/android/app/aidl/android/bluetooth/IBluetoothHidHost.aidl
+++ b/android/app/aidl/android/bluetooth/IBluetoothHidHost.aidl
@@ -42,6 +42,10 @@
void setConnectionPolicy(in BluetoothDevice device, int connectionPolicy, in AttributionSource attributionSource, in SynchronousResultReceiver receiver);
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})")
void getConnectionPolicy(in BluetoothDevice device, in AttributionSource attributionSource, in SynchronousResultReceiver receiver);
+ @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})")
+ void setPreferredTransport(in BluetoothDevice device, int transport, in AttributionSource attributionSource, in SynchronousResultReceiver receiver);
+ @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})")
+ void getPreferredTransport(in BluetoothDevice device, in AttributionSource attributionSource, in SynchronousResultReceiver receiver);
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)")
void getProtocolMode(in BluetoothDevice device, in AttributionSource attributionSource, in SynchronousResultReceiver receiver);
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)")
diff --git a/android/app/aidl/android/bluetooth/IBluetoothLeAudioCallback.aidl b/android/app/aidl/android/bluetooth/IBluetoothLeAudioCallback.aidl
index 547b3cb..92ecfe8 100644
--- a/android/app/aidl/android/bluetooth/IBluetoothLeAudioCallback.aidl
+++ b/android/app/aidl/android/bluetooth/IBluetoothLeAudioCallback.aidl
@@ -31,4 +31,5 @@
void onGroupNodeAdded(in BluetoothDevice device, int groupId);
void onGroupNodeRemoved(in BluetoothDevice device, int groupId);
void onGroupStatusChanged(int groupId, int groupStatus);
+ void onGroupStreamStatusChanged(int groupId, int groupStreamStatus);
}
diff --git a/android/app/aidl/android/bluetooth/IBluetoothVolumeControl.aidl b/android/app/aidl/android/bluetooth/IBluetoothVolumeControl.aidl
index 7d7616a..b269181 100644
--- a/android/app/aidl/android/bluetooth/IBluetoothVolumeControl.aidl
+++ b/android/app/aidl/android/bluetooth/IBluetoothVolumeControl.aidl
@@ -51,7 +51,9 @@
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})")
void isVolumeOffsetAvailable(in BluetoothDevice device, in AttributionSource attributionSource, in SynchronousResultReceiver receiver);
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})")
- void setVolumeOffset(in BluetoothDevice device, int volumeOffset, in AttributionSource attributionSource, in SynchronousResultReceiver receiver);
+ void getNumberOfVolumeOffsetInstances(in BluetoothDevice device, in AttributionSource attributionSource, in SynchronousResultReceiver receiver);
+ @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})")
+ void setVolumeOffset(in BluetoothDevice device, int instanceId, int volumeOffset, in AttributionSource attributionSource, in SynchronousResultReceiver receiver);
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)")
void setGroupVolume(int group_id, int volume, in AttributionSource attributionSource, in SynchronousResultReceiver receiver);
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)")
diff --git a/android/app/aidl/android/bluetooth/IBluetoothVolumeControlCallback.aidl b/android/app/aidl/android/bluetooth/IBluetoothVolumeControlCallback.aidl
index 4467be1..e067989 100644
--- a/android/app/aidl/android/bluetooth/IBluetoothVolumeControlCallback.aidl
+++ b/android/app/aidl/android/bluetooth/IBluetoothVolumeControlCallback.aidl
@@ -26,6 +26,8 @@
* @hide
*/
oneway interface IBluetoothVolumeControlCallback {
- void onVolumeOffsetChanged(in BluetoothDevice device, in int volumeOffset);
+ void onVolumeOffsetChanged(in BluetoothDevice device, in int instanceId, in int volumeOffset);
+ void onVolumeOffsetAudioLocationChanged(in BluetoothDevice device, in int instanceId, in int audioLocation);
+ void onVolumeOffsetAudioDescriptionChanged(in BluetoothDevice device, in int instanceId, in String audioDescription);
void onDeviceVolumeChanged(in BluetoothDevice device, in int volume);
}
diff --git a/android/app/jni/com_android_bluetooth.h b/android/app/jni/com_android_bluetooth.h
index 502e695..45b4e74 100644
--- a/android/app/jni/com_android_bluetooth.h
+++ b/android/app/jni/com_android_bluetooth.h
@@ -15,15 +15,16 @@
* limitations under the License.
*/
-#ifndef COM_ANDROID_BLUETOOTH_H
-#define COM_ANDROID_BLUETOOTH_H
+#pragma once
+
+#include <bluetooth/log.h>
#include "hardware/bluetooth.h"
#include "hardware/hardware.h"
#include "jni.h"
-#include "jni_logging.h"
#include "nativehelper/ScopedLocalRef.h"
-#include "utils/Log.h"
+
+namespace log = bluetooth::log;
namespace android {
@@ -38,15 +39,15 @@
~CallbackEnv() {
if (mCallbackEnv && mCallbackEnv->ExceptionCheck()) {
- ALOGE("An exception was thrown by callback '%s'.", mName);
- LOGE_EX(mCallbackEnv);
- mCallbackEnv->ExceptionClear();
+ log::error("An exception was thrown by callback '{}'.", mName);
+ jniLogException(mCallbackEnv, ANDROID_LOG_ERROR, LOG_TAG);
+ mCallbackEnv->ExceptionClear();
}
}
bool valid() const {
if (!mCallbackEnv || !isCallbackThread()) {
- ALOGE("%s: Callback env fail", mName);
+ log::error("{}: Callback env fail", mName);
return false;
}
return true;
@@ -184,5 +185,3 @@
jniGetMethodsOrDie(env, classname, methodsArray, NELEM(methodsArray))
} // namespace android
-
-#endif /* COM_ANDROID_BLUETOOTH_H */
diff --git a/android/app/jni/com_android_bluetooth_BluetoothQualityReport.cpp b/android/app/jni/com_android_bluetooth_BluetoothQualityReport.cpp
index 1451d8e..747e25f 100644
--- a/android/app/jni/com_android_bluetooth_BluetoothQualityReport.cpp
+++ b/android/app/jni/com_android_bluetooth_BluetoothQualityReport.cpp
@@ -46,7 +46,7 @@
void bqr_delivery_callback(const RawAddress bd_addr, uint8_t lmp_ver,
uint16_t lmp_subver, uint16_t manufacturer_id,
std::vector<uint8_t> bqr_raw_data) override {
- ALOGI("%s", __func__);
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -57,7 +57,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("Error while allocation byte array for addr in %s", __func__);
+ log::error("Error while allocation byte array for addr");
return;
}
@@ -67,8 +67,7 @@
ScopedLocalRef<jbyteArray> raw_data(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(bqr_raw_data.size()));
if (!raw_data.get()) {
- ALOGE("Error while allocation byte array for bqr raw data in %s",
- __func__);
+ log::error("Error while allocation byte array for bqr raw data");
return;
}
sCallbackEnv->SetByteArrayRegion(raw_data.get(), 0, bqr_raw_data.size(),
@@ -93,32 +92,32 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == nullptr) {
- LOG(ERROR) << "Bluetooth module is not loaded";
+ log::error("Bluetooth module is not loaded");
return;
}
if (sBluetoothQualityReportInterface != nullptr) {
- LOG(INFO) << "Cleaning up BluetoothQualityReport Interface before "
- "initializing...";
+ log::info(
+ "Cleaning up BluetoothQualityReport Interface before initializing...");
sBluetoothQualityReportInterface = nullptr;
}
if (mCallbacksObj != nullptr) {
- LOG(INFO) << "Cleaning up BluetoothQualityReport callback object";
+ log::info("Cleaning up BluetoothQualityReport callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = nullptr;
}
if ((mCallbacksObj = env->NewGlobalRef(object)) == nullptr) {
- LOG(ERROR)
- << "Failed to allocate Global Ref for BluetoothQualityReport Callbacks";
+ log::error(
+ "Failed to allocate Global Ref for BluetoothQualityReport Callbacks");
return;
}
sBluetoothQualityReportInterface =
(BluetoothQualityReportInterface*)btInf->get_profile_interface(BT_BQR_ID);
if (sBluetoothQualityReportInterface == nullptr) {
- LOG(ERROR) << "Failed to get BluetoothQualityReport Interface";
+ log::error("Failed to get BluetoothQualityReport Interface");
return;
}
@@ -131,7 +130,7 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == nullptr) {
- LOG(ERROR) << "Bluetooth module is not loaded";
+ log::error("Bluetooth module is not loaded");
return;
}
diff --git a/android/app/jni/com_android_bluetooth_a2dp.cpp b/android/app/jni/com_android_bluetooth_a2dp.cpp
index fea06c3..7486ccb 100644
--- a/android/app/jni/com_android_bluetooth_a2dp.cpp
+++ b/android/app/jni/com_android_bluetooth_a2dp.cpp
@@ -53,7 +53,7 @@
static void bta2dp_connection_state_callback(const RawAddress& bd_addr,
btav_connection_state_t state,
const btav_error_t& /* error */) {
- ALOGI("%s", __func__);
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -62,7 +62,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("%s: Fail to new jbyteArray bd addr", __func__);
+ log::error("Fail to new jbyteArray bd addr");
return;
}
@@ -75,7 +75,7 @@
static void bta2dp_audio_state_callback(const RawAddress& bd_addr,
btav_audio_state_t state) {
- ALOGI("%s", __func__);
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -84,7 +84,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("%s: Fail to new jbyteArray bd addr", __func__);
+ log::error("Fail to new jbyteArray bd addr");
return;
}
@@ -99,7 +99,7 @@
const RawAddress& bd_addr, btav_a2dp_codec_config_t codec_config,
std::vector<btav_a2dp_codec_config_t> codecs_local_capabilities,
std::vector<btav_a2dp_codec_config_t> codecs_selectable_capabilities) {
- ALOGI("%s", __func__);
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -151,7 +151,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(RawAddress::kLength));
if (!addr.get()) {
- ALOGE("%s: Fail to new jbyteArray bd addr", __func__);
+ log::error("Fail to new jbyteArray bd addr");
return;
}
sCallbackEnv->SetByteArrayRegion(
@@ -165,7 +165,7 @@
static bool bta2dp_mandatory_codec_preferred_callback(
const RawAddress& bd_addr) {
- ALOGI("%s", __func__);
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -174,7 +174,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(RawAddress::kLength));
if (!addr.get()) {
- ALOGE("%s: Fail to new jbyteArray bd addr", __func__);
+ log::error("Fail to new jbyteArray bd addr");
return false;
}
sCallbackEnv->SetByteArrayRegion(
@@ -202,7 +202,7 @@
if (jcodecConfig == nullptr) continue;
if (!env->IsInstanceOf(jcodecConfig,
android_bluetooth_BluetoothCodecConfig.clazz)) {
- ALOGE("%s: Invalid BluetoothCodecConfig instance", __func__);
+ log::error("Invalid BluetoothCodecConfig instance");
continue;
}
jint codecType = env->CallIntMethod(
@@ -252,32 +252,31 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == nullptr) {
- ALOGE("%s: Bluetooth module is not loaded", __func__);
+ log::error("Bluetooth module is not loaded");
return;
}
if (sBluetoothA2dpInterface != nullptr) {
- ALOGW("%s: Cleaning up A2DP Interface before initializing...", __func__);
+ log::warn("Cleaning up A2DP Interface before initializing...");
sBluetoothA2dpInterface->cleanup();
sBluetoothA2dpInterface = nullptr;
}
if (mCallbacksObj != nullptr) {
- ALOGW("%s: Cleaning up A2DP callback object", __func__);
+ log::warn("Cleaning up A2DP callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = nullptr;
}
if ((mCallbacksObj = env->NewGlobalRef(object)) == nullptr) {
- ALOGE("%s: Failed to allocate Global Ref for A2DP Callbacks", __func__);
+ log::error("Failed to allocate Global Ref for A2DP Callbacks");
return;
}
android_bluetooth_BluetoothCodecConfig.clazz = (jclass)env->NewGlobalRef(
env->FindClass("android/bluetooth/BluetoothCodecConfig"));
if (android_bluetooth_BluetoothCodecConfig.clazz == nullptr) {
- ALOGE("%s: Failed to allocate Global Ref for BluetoothCodecConfig class",
- __func__);
+ log::error("Failed to allocate Global Ref for BluetoothCodecConfig class");
return;
}
@@ -285,7 +284,7 @@
(btav_source_interface_t*)btInf->get_profile_interface(
BT_PROFILE_ADVANCED_AUDIO_ID);
if (sBluetoothA2dpInterface == nullptr) {
- ALOGE("%s: Failed to get Bluetooth A2DP Interface", __func__);
+ log::error("Failed to get Bluetooth A2DP Interface");
return;
}
@@ -299,8 +298,8 @@
&sBluetoothA2dpCallbacks, maxConnectedAudioDevices, codec_priorities,
codec_offloading, &supported_codecs);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("%s: Failed to initialize Bluetooth A2DP, status: %d", __func__,
- status);
+ log::error("Failed to initialize Bluetooth A2DP, status: {}",
+ bt_status_text(status));
sBluetoothA2dpInterface = nullptr;
return;
}
@@ -312,7 +311,7 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == nullptr) {
- ALOGE("%s: Bluetooth module is not loaded", __func__);
+ log::error("Bluetooth module is not loaded");
return;
}
@@ -331,13 +330,12 @@
}
static jobjectArray getSupportedCodecTypesNative(JNIEnv* env) {
- ALOGI("%s: %p", __func__, sBluetoothA2dpInterface);
+ log::info("{}", fmt::ptr(sBluetoothA2dpInterface));
jclass android_bluetooth_BluetoothCodecType_clazz = (jclass)env->NewGlobalRef(
env->FindClass("android/bluetooth/BluetoothCodecType"));
if (android_bluetooth_BluetoothCodecType_clazz == nullptr) {
- ALOGE("%s: Failed to allocate Global Ref for BluetoothCodecType class",
- __func__);
+ log::error("Failed to allocate Global Ref for BluetoothCodecType class");
return nullptr;
}
@@ -345,8 +343,7 @@
"<init>", "(IJLjava/lang/String;)V");
if (init == nullptr) {
- ALOGE("%s: Failed to find method <init> of BluetoothCodecType class",
- __func__);
+ log::error("Failed to find method <init> of BluetoothCodecType class");
return nullptr;
}
@@ -355,8 +352,7 @@
android_bluetooth_BluetoothCodecType_clazz, nullptr);
if (result == nullptr) {
- ALOGE("%s: Failed to allocate result array of BluetoothCodecType",
- __func__);
+ log::error("Failed to allocate result array of BluetoothCodecType");
return nullptr;
}
@@ -374,10 +370,10 @@
static jboolean connectA2dpNative(JNIEnv* env, jobject /* object */,
jbyteArray address) {
- ALOGI("%s: sBluetoothA2dpInterface: %p", __func__, sBluetoothA2dpInterface);
+ log::info("sBluetoothA2dpInterface: {}", fmt::ptr(sBluetoothA2dpInterface));
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothA2dpInterface) {
- ALOGE("%s: Failed to get the Bluetooth A2DP Interface", __func__);
+ log::error("Failed to get the Bluetooth A2DP Interface");
return JNI_FALSE;
}
@@ -391,7 +387,7 @@
bd_addr.FromOctets(reinterpret_cast<const uint8_t*>(addr));
bt_status_t status = sBluetoothA2dpInterface->connect(bd_addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("%s: Failed A2DP connection, status: %d", __func__, status);
+ log::error("Failed A2DP connection, status: {}", bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -399,10 +395,10 @@
static jboolean disconnectA2dpNative(JNIEnv* env, jobject /* object */,
jbyteArray address) {
- ALOGI("%s: sBluetoothA2dpInterface: %p", __func__, sBluetoothA2dpInterface);
+ log::info("sBluetoothA2dpInterface: {}", fmt::ptr(sBluetoothA2dpInterface));
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothA2dpInterface) {
- ALOGE("%s: Failed to get the Bluetooth A2DP Interface", __func__);
+ log::error("Failed to get the Bluetooth A2DP Interface");
return JNI_FALSE;
}
@@ -416,7 +412,7 @@
bd_addr.FromOctets(reinterpret_cast<const uint8_t*>(addr));
bt_status_t status = sBluetoothA2dpInterface->disconnect(bd_addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("%s: Failed A2DP disconnection, status: %d", __func__, status);
+ log::error("Failed A2DP disconnection, status: {}", bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -424,10 +420,10 @@
static jboolean setSilenceDeviceNative(JNIEnv* env, jobject /* object */,
jbyteArray address, jboolean silence) {
- ALOGI("%s: sBluetoothA2dpInterface: %p", __func__, sBluetoothA2dpInterface);
+ log::info("sBluetoothA2dpInterface: {}", fmt::ptr(sBluetoothA2dpInterface));
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothA2dpInterface) {
- ALOGE("%s: Failed to get the Bluetooth A2DP Interface", __func__);
+ log::error("Failed to get the Bluetooth A2DP Interface");
return JNI_FALSE;
}
@@ -443,7 +439,8 @@
bt_status_t status =
sBluetoothA2dpInterface->set_silence_device(bd_addr, silence);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("%s: Failed A2DP set_silence_device, status: %d", __func__, status);
+ log::error("Failed A2DP set_silence_device, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -451,10 +448,10 @@
static jboolean setActiveDeviceNative(JNIEnv* env, jobject /* object */,
jbyteArray address) {
- ALOGI("%s: sBluetoothA2dpInterface: %p", __func__, sBluetoothA2dpInterface);
+ log::info("sBluetoothA2dpInterface: {}", fmt::ptr(sBluetoothA2dpInterface));
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothA2dpInterface) {
- ALOGE("%s: Failed to get the Bluetooth A2DP Interface", __func__);
+ log::error("Failed to get the Bluetooth A2DP Interface");
return JNI_FALSE;
}
@@ -466,7 +463,8 @@
}
bt_status_t status = sBluetoothA2dpInterface->set_active_device(bd_addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("%s: Failed A2DP set_active_device, status: %d", __func__, status);
+ log::error("Failed A2DP set_active_device, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -475,10 +473,10 @@
static jboolean setCodecConfigPreferenceNative(JNIEnv* env, jobject object,
jbyteArray address,
jobjectArray codecConfigArray) {
- ALOGI("%s: sBluetoothA2dpInterface: %p", __func__, sBluetoothA2dpInterface);
+ log::info("sBluetoothA2dpInterface: {}", fmt::ptr(sBluetoothA2dpInterface));
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothA2dpInterface) {
- ALOGE("%s: Failed to get the Bluetooth A2DP Interface", __func__);
+ log::error("Failed to get the Bluetooth A2DP Interface");
return JNI_FALSE;
}
@@ -496,7 +494,8 @@
bt_status_t status =
sBluetoothA2dpInterface->config_codec(bd_addr, codec_preferences);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("%s: Failed codec configuration, status: %d", __func__, status);
+ log::error("Failed codec configuration, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
diff --git a/android/app/jni/com_android_bluetooth_a2dp_sink.cpp b/android/app/jni/com_android_bluetooth_a2dp_sink.cpp
index d2abfb6..c4ffb2e 100644
--- a/android/app/jni/com_android_bluetooth_a2dp_sink.cpp
+++ b/android/app/jni/com_android_bluetooth_a2dp_sink.cpp
@@ -37,7 +37,7 @@
static void a2dp_sink_connection_state_callback(
const RawAddress& bd_addr, btav_connection_state_t state,
const btav_error_t& /* error */) {
- ALOGI("%s", __func__);
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
if (!mCallbacksObj) return;
@@ -47,7 +47,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for connection state");
+ log::error("Fail to new jbyteArray bd addr for connection state");
return;
}
@@ -59,7 +59,7 @@
static void a2dp_sink_audio_state_callback(const RawAddress& bd_addr,
btav_audio_state_t state) {
- ALOGI("%s", __func__);
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
if (!mCallbacksObj) return;
@@ -69,7 +69,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for connection state");
+ log::error("Fail to new jbyteArray bd addr for connection state");
return;
}
@@ -82,7 +82,7 @@
static void a2dp_sink_audio_config_callback(const RawAddress& bd_addr,
uint32_t sample_rate,
uint8_t channel_count) {
- ALOGI("%s", __func__);
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
if (!mCallbacksObj) return;
@@ -92,7 +92,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for connection state");
+ log::error("Fail to new jbyteArray bd addr for connection state");
return;
}
@@ -116,18 +116,18 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == NULL) {
- ALOGE("Bluetooth module is not loaded");
+ log::error("Bluetooth module is not loaded");
return;
}
if (sBluetoothA2dpInterface != NULL) {
- ALOGW("Cleaning up A2DP Interface before initializing...");
+ log::warn("Cleaning up A2DP Interface before initializing...");
sBluetoothA2dpInterface->cleanup();
sBluetoothA2dpInterface = NULL;
}
if (mCallbacksObj != NULL) {
- ALOGW("Cleaning up A2DP callback object");
+ log::warn("Cleaning up A2DP callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = NULL;
}
@@ -136,14 +136,15 @@
(btav_sink_interface_t*)btInf->get_profile_interface(
BT_PROFILE_ADVANCED_AUDIO_SINK_ID);
if (sBluetoothA2dpInterface == NULL) {
- ALOGE("Failed to get Bluetooth A2DP Sink Interface");
+ log::error("Failed to get Bluetooth A2DP Sink Interface");
return;
}
bt_status_t status = sBluetoothA2dpInterface->init(&sBluetoothA2dpCallbacks,
maxConnectedAudioDevices);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed to initialize Bluetooth A2DP Sink, status: %d", status);
+ log::error("Failed to initialize Bluetooth A2DP Sink, status: {}",
+ bt_status_text(status));
sBluetoothA2dpInterface = NULL;
return;
}
@@ -156,7 +157,7 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == NULL) {
- ALOGE("Bluetooth module is not loaded");
+ log::error("Bluetooth module is not loaded");
return;
}
@@ -173,7 +174,7 @@
static jboolean connectA2dpNative(JNIEnv* env, jobject /* object */,
jbyteArray address) {
- ALOGI("%s: sBluetoothA2dpInterface: %p", __func__, sBluetoothA2dpInterface);
+ log::info("sBluetoothA2dpInterface: {}", fmt::ptr(sBluetoothA2dpInterface));
if (!sBluetoothA2dpInterface) return JNI_FALSE;
jbyte* addr = env->GetByteArrayElements(address, NULL);
@@ -186,7 +187,7 @@
bd_addr.FromOctets(reinterpret_cast<const uint8_t*>(addr));
bt_status_t status = sBluetoothA2dpInterface->connect(bd_addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed HF connection, status: %d", status);
+ log::error("Failed HF connection, status: {}", bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -206,7 +207,7 @@
bd_addr.FromOctets(reinterpret_cast<const uint8_t*>(addr));
bt_status_t status = sBluetoothA2dpInterface->disconnect(bd_addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed HF disconnection, status: %d", status);
+ log::error("Failed HF disconnection, status: {}", bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -228,7 +229,7 @@
jbyteArray address) {
if (!sBluetoothA2dpInterface) return JNI_FALSE;
- ALOGI("%s: sBluetoothA2dpInterface: %p", __func__, sBluetoothA2dpInterface);
+ log::info("sBluetoothA2dpInterface: {}", fmt::ptr(sBluetoothA2dpInterface));
jbyte* addr = env->GetByteArrayElements(address, NULL);
if (!addr) {
@@ -240,7 +241,8 @@
rawAddress.FromOctets((uint8_t*)addr);
bt_status_t status = sBluetoothA2dpInterface->set_active_device(rawAddress);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed sending passthru command, status: %d", status);
+ log::error("Failed sending passthru command, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
diff --git a/android/app/jni/com_android_bluetooth_avrcp_controller.cpp b/android/app/jni/com_android_bluetooth_avrcp_controller.cpp
index 6382f46..13c26c1 100644
--- a/android/app/jni/com_android_bluetooth_avrcp_controller.cpp
+++ b/android/app/jni/com_android_bluetooth_avrcp_controller.cpp
@@ -55,28 +55,28 @@
static void btavrcp_passthrough_response_callback(
const RawAddress& /* bd_addr */, int id, int pressed) {
- ALOGV("%s: id: %d, pressed: %d --- Not implemented", __func__, id, pressed);
+ log::verbose("id: {}, pressed: {} --- Not implemented", id, pressed);
}
static void btavrcp_groupnavigation_response_callback(int id, int pressed) {
- ALOGV("%s: id: %d, pressed: %d --- Not implemented", __func__, id, pressed);
+ log::verbose("id: {}, pressed: {} --- Not implemented", id, pressed);
}
static void btavrcp_connection_state_callback(bool rc_connect, bool br_connect,
const RawAddress& bd_addr) {
- ALOGI("%s: conn state: rc: %d br: %d", __func__, rc_connect, br_connect);
+ log::info("conn state: rc: {} br: {}", rc_connect, br_connect);
std::shared_lock<std::shared_timed_mutex> lock(sCallbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!sCallbacksObj) {
- ALOGE("%s: sCallbacksObj is null", __func__);
+ log::error("sCallbacksObj is null");
return;
}
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("%s: Failed to allocate a new byte array", __func__);
+ log::error("Failed to allocate a new byte array");
return;
}
@@ -89,30 +89,30 @@
static void btavrcp_get_rcfeatures_callback(const RawAddress& /* bd_addr */,
int /* features */) {
- ALOGV("%s --- Not implemented", __func__);
+ log::verbose("--- Not implemented");
}
static void btavrcp_setplayerapplicationsetting_rsp_callback(
const RawAddress& /* bd_addr */, uint8_t /* accepted */) {
- ALOGV("%s --- Not implemented", __func__);
+ log::verbose("--- Not implemented");
}
static void btavrcp_playerapplicationsetting_callback(
const RawAddress& bd_addr, uint8_t num_attr,
btrc_player_app_attr_t* app_attrs, uint8_t /* num_ext_attr */,
btrc_player_app_ext_attr_t* /* ext_attrs */) {
- ALOGI("%s", __func__);
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(sCallbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!sCallbacksObj) {
- ALOGE("%s: sCallbacksObj is null", __func__);
+ log::error("sCallbacksObj is null");
return;
}
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("%s: Failed to allocate a new byte array", __func__);
+ log::error("Failed to allocate a new byte array");
return;
}
sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress),
@@ -125,12 +125,12 @@
/*2 bytes for id and num */
arraylen += 2 + app_attrs[i].num_val;
}
- ALOGV(" arraylen %d", arraylen);
+ log::verbose(" arraylen {}", arraylen);
ScopedLocalRef<jbyteArray> playerattribs(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(arraylen));
if (!playerattribs.get()) {
- ALOGE("%s: Failed to allocate a new byte array", __func__);
+ log::error("Failed to allocate a new byte array");
return;
}
@@ -152,19 +152,19 @@
static void btavrcp_playerapplicationsetting_changed_callback(
const RawAddress& bd_addr, const btrc_player_settings_t& vals) {
- ALOGI("%s", __func__);
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(sCallbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!sCallbacksObj) {
- ALOGE("%s: sCallbacksObj is null", __func__);
+ log::error("sCallbacksObj is null");
return;
}
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("%s: Failed to allocate a new byte array", __func__);
+ log::error("Failed to allocate a new byte array");
return;
}
sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress),
@@ -174,7 +174,7 @@
ScopedLocalRef<jbyteArray> playerattribs(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(arraylen));
if (!playerattribs.get()) {
- ALOGE("Fail to new jbyteArray playerattribs ");
+ log::error("Fail to new jbyteArray playerattribs ");
return;
}
/*
@@ -195,19 +195,19 @@
static void btavrcp_set_abs_vol_cmd_callback(const RawAddress& bd_addr,
uint8_t abs_vol, uint8_t label) {
- ALOGI("%s", __func__);
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(sCallbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!sCallbacksObj) {
- ALOGE("%s: sCallbacksObj is null", __func__);
+ log::error("sCallbacksObj is null");
return;
}
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("%s: Failed to allocate a new byte array", __func__);
+ log::error("Failed to allocate a new byte array");
return;
}
@@ -219,19 +219,19 @@
static void btavrcp_register_notification_absvol_callback(
const RawAddress& bd_addr, uint8_t label) {
- ALOGI("%s", __func__);
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(sCallbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!sCallbacksObj) {
- ALOGE("%s: sCallbacksObj is null", __func__);
+ log::error("sCallbacksObj is null");
return;
}
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("%s: Failed to allocate a new byte array", __func__);
+ log::error("Failed to allocate a new byte array");
return;
}
@@ -249,26 +249,26 @@
* byteArray will be formatted like this: id,len,string
* Assuming text feild to be null terminated.
*/
- ALOGI("%s", __func__);
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(sCallbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!sCallbacksObj) {
- ALOGE("%s: sCallbacksObj is null", __func__);
+ log::error("sCallbacksObj is null");
return;
}
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("%s: Failed to allocate a new byte array", __func__);
+ log::error("Failed to allocate a new byte array");
return;
}
ScopedLocalRef<jintArray> attribIds(sCallbackEnv.get(),
sCallbackEnv->NewIntArray(num_attr));
if (!attribIds.get()) {
- ALOGE(" failed to set new array for attribIds");
+ log::error(" failed to set new array for attribIds");
return;
}
sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress),
@@ -279,7 +279,7 @@
sCallbackEnv.get(),
sCallbackEnv->NewObjectArray((jint)num_attr, strclazz, 0));
if (!stringArray.get()) {
- ALOGE(" failed to get String array");
+ log::error(" failed to get String array");
return;
}
@@ -288,7 +288,7 @@
sCallbackEnv.get(),
sCallbackEnv->NewStringUTF((char*)(p_attrs[i].text)));
if (!str.get()) {
- ALOGE("Unable to get str");
+ log::error("Unable to get str");
return;
}
sCallbackEnv->SetIntArrayRegion(attribIds.get(), i, 1,
@@ -304,19 +304,19 @@
static void btavrcp_play_position_changed_callback(const RawAddress& bd_addr,
uint32_t song_len,
uint32_t song_pos) {
- ALOGI("%s", __func__);
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(sCallbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!sCallbacksObj) {
- ALOGE("%s: sCallbacksObj is null", __func__);
+ log::error("sCallbacksObj is null");
return;
}
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("%s: Failed to allocate a new byte array", __func__);
+ log::error("Failed to allocate a new byte array");
return;
}
sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress),
@@ -327,19 +327,19 @@
static void btavrcp_play_status_changed_callback(
const RawAddress& bd_addr, btrc_play_status_t play_status) {
- ALOGI("%s", __func__);
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(sCallbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!sCallbacksObj) {
- ALOGE("%s: sCallbacksObj is null", __func__);
+ log::error("sCallbacksObj is null");
return;
}
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("%s: Failed to allocate a new byte array", __func__);
+ log::error("Failed to allocate a new byte array");
return;
}
sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress),
@@ -355,19 +355,19 @@
* BTRC_ITEM_MEDIA, BTRC_ITEM_FOLDER. Here we translate them to their java
* counterparts by calling the java constructor for each of the items.
*/
- ALOGV("%s count %d", __func__, count);
+ log::verbose("count {}", count);
std::shared_lock<std::shared_timed_mutex> lock(sCallbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!sCallbacksObj) {
- ALOGE("%s: sCallbacksObj is null", __func__);
+ log::error("sCallbacksObj is null");
return;
}
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("%s: Failed to allocate a new byte array", __func__);
+ log::error("Failed to allocate a new byte array");
return;
}
@@ -389,12 +389,12 @@
(jint)count, class_AvrcpItem, 0));
}
if (!itemArray.get()) {
- ALOGE("%s itemArray allocation failed.", __func__);
+ log::error("itemArray allocation failed.");
return;
}
for (int i = 0; i < count; i++) {
const btrc_folder_items_t* item = &(folder_items[i]);
- ALOGV("%s item type %d", __func__, item->item_type);
+ log::verbose("item type {}", item->item_type);
switch (item->item_type) {
case BTRC_ITEM_MEDIA: {
// Parse name
@@ -402,7 +402,7 @@
sCallbackEnv.get(),
sCallbackEnv->NewStringUTF((const char*)item->media.name));
if (!mediaName.get()) {
- ALOGE("%s can't allocate media name string!", __func__);
+ log::error("can't allocate media name string!");
return;
}
// Parse UID
@@ -412,7 +412,7 @@
sCallbackEnv.get(),
sCallbackEnv->NewIntArray(item->media.num_attrs));
if (!attrIdArray.get()) {
- ALOGE("%s can't allocate attr id array!", __func__);
+ log::error("can't allocate attr id array!");
return;
}
ScopedLocalRef<jobjectArray> attrValArray(
@@ -421,7 +421,7 @@
item->media.num_attrs,
sCallbackEnv->FindClass("java/lang/String"), 0));
if (!attrValArray.get()) {
- ALOGE("%s can't allocate attr val array!", __func__);
+ log::error("can't allocate attr val array!");
return;
}
@@ -444,7 +444,7 @@
(jint)item->media.type, mediaName.get(), attrIdArray.get(),
attrValArray.get()));
if (!mediaObj.get()) {
- ALOGE("%s failed to create AvrcpItem for type ITEM_MEDIA", __func__);
+ log::error("failed to create AvrcpItem for type ITEM_MEDIA");
return;
}
sCallbackEnv->SetObjectArrayElement(itemArray.get(), i, mediaObj.get());
@@ -457,7 +457,7 @@
sCallbackEnv.get(),
sCallbackEnv->NewStringUTF((const char*)item->folder.name));
if (!folderName.get()) {
- ALOGE("%s can't allocate folder name string!", __func__);
+ log::error("can't allocate folder name string!");
return;
}
// Parse UID
@@ -470,7 +470,7 @@
(jint)item->folder.type, folderName.get(),
(jint)item->folder.playable));
if (!folderObj.get()) {
- ALOGE("%s failed to create AvrcpItem for type ITEM_FOLDER", __func__);
+ log::error("failed to create AvrcpItem for type ITEM_FOLDER");
return;
}
sCallbackEnv->SetObjectArrayElement(itemArray.get(), i,
@@ -489,7 +489,7 @@
sCallbackEnv->NewByteArray(BTRC_FEATURE_BIT_MASK_SIZE *
sizeof(uint8_t)));
if (!featureBitArray.get()) {
- ALOGE("%s failed to allocate featureBitArray", __func__);
+ log::error("failed to allocate featureBitArray");
return;
}
sCallbackEnv->SetByteArrayRegion(
@@ -500,7 +500,7 @@
sCallbackEnv.get(),
sCallbackEnv->NewStringUTF((const char*)item->player.name));
if (!playerName.get()) {
- ALOGE("%s can't allocate player name string!", __func__);
+ log::error("can't allocate player name string!");
return;
}
ScopedLocalRef<jobject> playerObj(
@@ -511,7 +511,7 @@
playerName.get(), featureBitArray.get(), playStatus,
playerType));
if (!playerObj.get()) {
- ALOGE("%s failed to create AvrcpPlayer from ITEM_PLAYER", __func__);
+ log::error("failed to create AvrcpPlayer from ITEM_PLAYER");
return;
}
sCallbackEnv->SetObjectArrayElement(itemArray.get(), i,
@@ -520,7 +520,7 @@
}
default:
- ALOGE("%s cannot understand type %d", __func__, item->item_type);
+ log::error("cannot understand type {}", item->item_type);
}
}
@@ -535,18 +535,18 @@
static void btavrcp_change_path_callback(const RawAddress& bd_addr,
uint32_t count) {
- ALOGI("%s count %d", __func__, count);
+ log::info("count {}", count);
std::shared_lock<std::shared_timed_mutex> lock(sCallbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!sCallbacksObj) {
- ALOGE("%s: sCallbacksObj is null", __func__);
+ log::error("sCallbacksObj is null");
return;
}
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("%s: Failed to allocate a new byte array", __func__);
+ log::error("Failed to allocate a new byte array");
return;
}
@@ -560,18 +560,18 @@
static void btavrcp_set_browsed_player_callback(const RawAddress& bd_addr,
uint8_t num_items,
uint8_t depth) {
- ALOGI("%s items %d depth %d", __func__, num_items, depth);
+ log::info("items {} depth {}", num_items, depth);
std::shared_lock<std::shared_timed_mutex> lock(sCallbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!sCallbacksObj) {
- ALOGE("%s: sCallbacksObj is null", __func__);
+ log::error("sCallbacksObj is null");
return;
}
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("%s: Failed to allocate a new byte array", __func__);
+ log::error("Failed to allocate a new byte array");
return;
}
@@ -584,18 +584,18 @@
static void btavrcp_set_addressed_player_callback(const RawAddress& bd_addr,
uint8_t status) {
- ALOGI("%s status %d", __func__, status);
+ log::info("status {}", status);
std::shared_lock<std::shared_timed_mutex> lock(sCallbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!sCallbacksObj) {
- ALOGE("%s: sCallbacksObj is null", __func__);
+ log::error("sCallbacksObj is null");
return;
}
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("%s: Failed to allocate a new byte array", __func__);
+ log::error("Failed to allocate a new byte array");
return;
}
@@ -609,18 +609,18 @@
static void btavrcp_addressed_player_changed_callback(const RawAddress& bd_addr,
uint16_t id) {
- ALOGI("%s status %d", __func__, id);
+ log::info("status {}", id);
std::shared_lock<std::shared_timed_mutex> lock(sCallbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!sCallbacksObj) {
- ALOGE("%s: sCallbacksObj is null", __func__);
+ log::error("sCallbacksObj is null");
return;
}
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("%s: Failed to allocate a new byte array", __func__);
+ log::error("Failed to allocate a new byte array");
return;
}
@@ -633,14 +633,14 @@
static void btavrcp_now_playing_content_changed_callback(
const RawAddress& bd_addr) {
- ALOGI("%s", __func__);
+ log::info("");
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("%s: Failed to allocate a new byte array", __func__);
+ log::error("Failed to allocate a new byte array");
return;
}
@@ -653,19 +653,19 @@
static void btavrcp_available_player_changed_callback (
const RawAddress& bd_addr) {
- ALOGI("%s", __func__);
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(sCallbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbacksObj) {
- ALOGE("%s: sCallbacksObj is null", __func__);
- return;
+ log::error("sCallbacksObj is null");
+ return;
}
if (!sCallbackEnv.valid()) return;
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("%s: Failed to allocate a new byte array", __func__);
+ log::error("Failed to allocate a new byte array");
return;
}
@@ -677,11 +677,11 @@
static void btavrcp_get_rcpsm_callback(const RawAddress& bd_addr,
uint16_t psm) {
- ALOGE("%s -> psm received of %d", __func__, psm);
+ log::error("-> psm received of {}", psm);
std::shared_lock<std::shared_timed_mutex> lock(sCallbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbacksObj) {
- ALOGE("%s: sCallbacksObj is null", __func__);
+ log::error("sCallbacksObj is null");
return;
}
if (!sCallbackEnv.valid()) return;
@@ -689,7 +689,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("%s: Failed to allocate a new byte array", __func__);
+ log::error("Failed to allocate a new byte array");
return;
}
@@ -741,18 +741,18 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == NULL) {
- ALOGE("Bluetooth module is not loaded");
+ log::error("Bluetooth module is not loaded");
return;
}
if (sBluetoothAvrcpInterface != NULL) {
- ALOGW("Cleaning up Avrcp Interface before initializing...");
+ log::warn("Cleaning up Avrcp Interface before initializing...");
sBluetoothAvrcpInterface->cleanup();
sBluetoothAvrcpInterface = NULL;
}
if (sCallbacksObj != NULL) {
- ALOGW("Cleaning up Avrcp callback object");
+ log::warn("Cleaning up Avrcp callback object");
env->DeleteGlobalRef(sCallbacksObj);
sCallbacksObj = NULL;
}
@@ -761,15 +761,15 @@
(btrc_ctrl_interface_t*)btInf->get_profile_interface(
BT_PROFILE_AV_RC_CTRL_ID);
if (sBluetoothAvrcpInterface == NULL) {
- ALOGE("Failed to get Bluetooth Avrcp Controller Interface");
+ log::error("Failed to get Bluetooth Avrcp Controller Interface");
return;
}
bt_status_t status =
sBluetoothAvrcpInterface->init(&sBluetoothAvrcpCallbacks);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed to initialize Bluetooth Avrcp Controller, status: %d",
- status);
+ log::error("Failed to initialize Bluetooth Avrcp Controller, status: {}",
+ bt_status_text(status));
sBluetoothAvrcpInterface = NULL;
return;
}
@@ -782,7 +782,7 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == NULL) {
- ALOGE("Bluetooth module is not loaded");
+ log::error("Bluetooth module is not loaded");
return;
}
@@ -802,9 +802,9 @@
jint key_state) {
if (!sBluetoothAvrcpInterface) return JNI_FALSE;
- ALOGI("%s: sBluetoothAvrcpInterface: %p", __func__, sBluetoothAvrcpInterface);
+ log::info("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface));
- ALOGI("key_code: %d, key_state: %d", key_code, key_state);
+ log::info("key_code: {}, key_state: {}", key_code, key_state);
jbyte* addr = env->GetByteArrayElements(address, NULL);
if (!addr) {
@@ -817,7 +817,8 @@
bt_status_t status = sBluetoothAvrcpInterface->send_pass_through_cmd(
rawAddress, (uint8_t)key_code, (uint8_t)key_state);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed sending passthru command, status: %d", status);
+ log::error("Failed sending passthru command, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
@@ -831,9 +832,9 @@
jint key_state) {
if (!sBluetoothAvrcpInterface) return JNI_FALSE;
- ALOGI("%s: sBluetoothAvrcpInterface: %p", __func__, sBluetoothAvrcpInterface);
+ log::info("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface));
- ALOGI("key_code: %d, key_state: %d", key_code, key_state);
+ log::info("key_code: {}, key_state: {}", key_code, key_state);
jbyte* addr = env->GetByteArrayElements(address, NULL);
if (!addr) {
@@ -846,7 +847,8 @@
bt_status_t status = sBluetoothAvrcpInterface->send_group_navigation_cmd(
rawAddress, (uint8_t)key_code, (uint8_t)key_state);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed sending Grp Navigation command, status: %d", status);
+ log::error("Failed sending Grp Navigation command, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
@@ -856,7 +858,7 @@
static void setPlayerApplicationSettingValuesNative(
JNIEnv* env, jobject /* object */, jbyteArray address, jbyte num_attrib,
jbyteArray attrib_ids, jbyteArray attrib_val) {
- ALOGI("%s: sBluetoothAvrcpInterface: %p", __func__, sBluetoothAvrcpInterface);
+ log::info("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface));
if (!sBluetoothAvrcpInterface) return;
jbyte* addr = env->GetByteArrayElements(address, NULL);
@@ -869,7 +871,8 @@
uint8_t* pAttrsVal = new uint8_t[num_attrib];
if ((!pAttrs) || (!pAttrsVal)) {
delete[] pAttrs;
- ALOGE("setPlayerApplicationSettingValuesNative: not have enough memeory");
+ log::error(
+ "setPlayerApplicationSettingValuesNative: not have enough memory");
return;
}
@@ -893,7 +896,8 @@
bt_status_t status = sBluetoothAvrcpInterface->set_player_app_setting_cmd(
rawAddress, (uint8_t)num_attrib, pAttrs, pAttrsVal);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed sending setPlAppSettValNative command, status: %d", status);
+ log::error("Failed sending setPlAppSettValNative command, status: {}",
+ bt_status_text(status));
}
delete[] pAttrs;
delete[] pAttrsVal;
@@ -912,14 +916,15 @@
return;
}
- ALOGI("%s: sBluetoothAvrcpInterface: %p", __func__, sBluetoothAvrcpInterface);
+ log::info("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface));
RawAddress rawAddress;
rawAddress.FromOctets((uint8_t*)addr);
bt_status_t status = sBluetoothAvrcpInterface->set_volume_rsp(
rawAddress, (uint8_t)abs_vol, (uint8_t)label);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed sending sendAbsVolRspNative command, status: %d", status);
+ log::error("Failed sending sendAbsVolRspNative command, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
}
@@ -934,7 +939,7 @@
jniThrowIOException(env, EINVAL);
return;
}
- ALOGI("%s: sBluetoothAvrcpInterface: %p", __func__, sBluetoothAvrcpInterface);
+ log::info("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface));
RawAddress rawAddress;
rawAddress.FromOctets((uint8_t*)addr);
@@ -942,8 +947,8 @@
rawAddress, (btrc_notification_type_t)rsp_type, (uint8_t)abs_vol,
(uint8_t)label);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed sending sendRegisterAbsVolRspNative command, status: %d",
- status);
+ log::error("Failed sending sendRegisterAbsVolRspNative command, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
}
@@ -957,14 +962,16 @@
jniThrowIOException(env, EINVAL);
return;
}
- ALOGV("%s: sBluetoothAvrcpInterface: %p", __func__, sBluetoothAvrcpInterface);
+ log::verbose("sBluetoothAvrcpInterface: {}",
+ fmt::ptr(sBluetoothAvrcpInterface));
RawAddress rawAddress;
rawAddress.FromOctets((uint8_t*)addr);
bt_status_t status =
sBluetoothAvrcpInterface->get_current_metadata_cmd(rawAddress);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed sending getCurrentMetadataNative command, status: %d", status);
+ log::error("Failed sending getCurrentMetadataNative command, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
}
@@ -978,14 +985,16 @@
jniThrowIOException(env, EINVAL);
return;
}
- ALOGV("%s: sBluetoothAvrcpInterface: %p", __func__, sBluetoothAvrcpInterface);
+ log::verbose("sBluetoothAvrcpInterface: {}",
+ fmt::ptr(sBluetoothAvrcpInterface));
RawAddress rawAddress;
rawAddress.FromOctets((uint8_t*)addr);
bt_status_t status =
sBluetoothAvrcpInterface->get_playback_state_cmd(rawAddress);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed sending getPlaybackStateNative command, status: %d", status);
+ log::error("Failed sending getPlaybackStateNative command, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
}
@@ -998,14 +1007,16 @@
jniThrowIOException(env, EINVAL);
return;
}
- ALOGV("%s: sBluetoothAvrcpInterface: %p", __func__, sBluetoothAvrcpInterface);
+ log::verbose("sBluetoothAvrcpInterface: {}",
+ fmt::ptr(sBluetoothAvrcpInterface));
RawAddress rawAddress;
rawAddress.FromOctets((uint8_t*)addr);
bt_status_t status = sBluetoothAvrcpInterface->get_now_playing_list_cmd(
rawAddress, start, end);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed sending getNowPlayingListNative command, status: %d", status);
+ log::error("Failed sending getNowPlayingListNative command, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
}
@@ -1018,14 +1029,16 @@
jniThrowIOException(env, EINVAL);
return;
}
- ALOGV("%s: sBluetoothAvrcpInterface: %p", __func__, sBluetoothAvrcpInterface);
+ log::verbose("sBluetoothAvrcpInterface: {}",
+ fmt::ptr(sBluetoothAvrcpInterface));
RawAddress rawAddress;
rawAddress.FromOctets((uint8_t*)addr);
bt_status_t status =
sBluetoothAvrcpInterface->get_folder_list_cmd(rawAddress, start, end);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed sending getFolderListNative command, status: %d", status);
+ log::error("Failed sending getFolderListNative command, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
}
@@ -1038,14 +1051,15 @@
jniThrowIOException(env, EINVAL);
return;
}
- ALOGI("%s: sBluetoothAvrcpInterface: %p", __func__, sBluetoothAvrcpInterface);
+ log::info("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface));
RawAddress rawAddress;
rawAddress.FromOctets((uint8_t*)addr);
bt_status_t status =
sBluetoothAvrcpInterface->get_player_list_cmd(rawAddress, start, end);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed sending getPlayerListNative command, status: %d", status);
+ log::error("Failed sending getPlayerListNative command, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
}
@@ -1066,14 +1080,15 @@
// return;
//}
- ALOGI("%s: sBluetoothAvrcpInterface: %p", __func__, sBluetoothAvrcpInterface);
+ log::info("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface));
RawAddress rawAddress;
rawAddress.FromOctets((uint8_t*)addr);
bt_status_t status = sBluetoothAvrcpInterface->change_folder_path_cmd(
rawAddress, (uint8_t)direction, (uint8_t*)&uid);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed sending changeFolderPathNative command, status: %d", status);
+ log::error("Failed sending changeFolderPathNative command, status: {}",
+ bt_status_text(status));
}
// env->ReleaseByteArrayElements(address, addr, 0);
}
@@ -1089,11 +1104,12 @@
RawAddress rawAddress;
rawAddress.FromOctets((uint8_t*)addr);
- ALOGI("%s: sBluetoothAvrcpInterface: %p", __func__, sBluetoothAvrcpInterface);
+ log::info("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface));
bt_status_t status = sBluetoothAvrcpInterface->set_browsed_player_cmd(
rawAddress, (uint16_t)id);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed sending setBrowsedPlayerNative command, status: %d", status);
+ log::error("Failed sending setBrowsedPlayerNative command, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
}
@@ -1109,12 +1125,12 @@
RawAddress rawAddress;
rawAddress.FromOctets((uint8_t*)addr);
- ALOGI("%s: sBluetoothAvrcpInterface: %p", __func__, sBluetoothAvrcpInterface);
+ log::info("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface));
bt_status_t status = sBluetoothAvrcpInterface->set_addressed_player_cmd(
rawAddress, (uint16_t)id);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed sending setAddressedPlayerNative command, status: %d",
- status);
+ log::error("Failed sending setAddressedPlayerNative command, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
}
@@ -1137,11 +1153,12 @@
RawAddress rawAddress;
rawAddress.FromOctets((uint8_t*)addr);
- ALOGI("%s: sBluetoothAvrcpInterface: %p", __func__, sBluetoothAvrcpInterface);
+ log::info("sBluetoothAvrcpInterface: {}", fmt::ptr(sBluetoothAvrcpInterface));
bt_status_t status = sBluetoothAvrcpInterface->play_item_cmd(
rawAddress, (uint8_t)scope, (uint8_t*)&uid, (uint16_t)uidCounter);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed sending playItemNative command, status: %d", status);
+ log::error("Failed sending playItemNative command, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
}
diff --git a/android/app/jni/com_android_bluetooth_avrcp_target.cpp b/android/app/jni/com_android_bluetooth_avrcp_target.cpp
index a5e4949..1e9678c 100644
--- a/android/app/jni/com_android_bluetooth_avrcp_target.cpp
+++ b/android/app/jni/com_android_bluetooth_avrcp_target.cpp
@@ -233,7 +233,7 @@
static jmethodID method_setPlayerSettings;
static void initNative(JNIEnv* env, jobject object) {
- ALOGD("%s", __func__);
+ log::debug("");
std::unique_lock<std::shared_timed_mutex> interface_lock(interface_mutex);
std::unique_lock<std::shared_timed_mutex> callbacks_lock(callbacks_mutex);
mJavaInterface = env->NewGlobalRef(object);
@@ -245,20 +245,20 @@
static void registerBipServerNative(JNIEnv* /* env */, jobject /* object */,
jint l2cap_psm) {
- ALOGD("%s: l2cap_psm=%d", __func__, (int)l2cap_psm);
+ log::debug("l2cap_psm={}", (int)l2cap_psm);
std::unique_lock<std::shared_timed_mutex> interface_lock(interface_mutex);
if (sServiceInterface == nullptr) {
- ALOGW("%s: Service not loaded.", __func__);
+ log::warn("Service not loaded.");
return;
}
sServiceInterface->RegisterBipServer((int)l2cap_psm);
}
static void unregisterBipServerNative(JNIEnv* /* env */, jobject /* object */) {
- ALOGD("%s", __func__);
+ log::debug("");
std::unique_lock<std::shared_timed_mutex> interface_lock(interface_mutex);
if (sServiceInterface == nullptr) {
- ALOGW("%s: Service not loaded.", __func__);
+ log::warn("Service not loaded.");
return;
}
sServiceInterface->UnregisterBipServer();
@@ -267,10 +267,10 @@
static void sendMediaUpdateNative(JNIEnv* /* env */, jobject /* object */,
jboolean metadata, jboolean state,
jboolean queue) {
- ALOGD("%s", __func__);
+ log::debug("");
std::unique_lock<std::shared_timed_mutex> interface_lock(interface_mutex);
if (mServiceCallbacks == nullptr) {
- ALOGW("%s: Service not loaded.", __func__);
+ log::warn("Service not loaded.");
return;
}
@@ -281,10 +281,10 @@
static void sendFolderUpdateNative(JNIEnv* /* env */, jobject /* object */,
jboolean available_players,
jboolean addressed_player, jboolean uids) {
- ALOGD("%s", __func__);
+ log::debug("");
std::unique_lock<std::shared_timed_mutex> interface_lock(interface_mutex);
if (mServiceCallbacks == nullptr) {
- ALOGW("%s: Service not loaded.", __func__);
+ log::warn("Service not loaded.");
return;
}
@@ -309,10 +309,10 @@
jboolean connectDeviceNative(JNIEnv* env, jobject /* object */,
jstring address) {
- ALOGD("%s", __func__);
+ log::debug("");
std::unique_lock<std::shared_timed_mutex> interface_lock(interface_mutex);
if (mServiceCallbacks == nullptr) {
- ALOGW("%s: Service not loaded.", __func__);
+ log::warn("Service not loaded.");
return JNI_FALSE;
}
@@ -329,10 +329,10 @@
jboolean disconnectDeviceNative(JNIEnv* env, jobject /* object */,
jstring address) {
- ALOGD("%s", __func__);
+ log::debug("");
std::unique_lock<std::shared_timed_mutex> interface_lock(interface_mutex);
if (mServiceCallbacks == nullptr) {
- ALOGW("%s: Service not loaded.", __func__);
+ log::warn("Service not loaded.");
return JNI_FALSE;
}
@@ -348,7 +348,7 @@
}
static void sendMediaKeyEvent(int key, KeyState state) {
- ALOGD("%s", __func__);
+ log::debug("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mJavaInterface) return;
@@ -519,7 +519,7 @@
}
static SongInfo getSongInfo() {
- ALOGD("%s", __func__);
+ log::debug("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mJavaInterface) return SongInfo();
@@ -532,7 +532,7 @@
}
static PlayStatus getCurrentPlayStatus() {
- ALOGD("%s", __func__);
+ log::debug("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mJavaInterface) return PlayStatus();
@@ -542,7 +542,7 @@
sCallbackEnv->CallObjectMethod(mJavaInterface, method_getPlaybackStatus);
if (playStatus == nullptr) {
- ALOGE("%s: Got a null play status", __func__);
+ log::error("Got a null play status");
return status;
}
@@ -564,7 +564,7 @@
}
static std::string getCurrentMediaId() {
- ALOGD("%s", __func__);
+ log::debug("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mJavaInterface) return "";
@@ -572,7 +572,7 @@
jstring media_id = (jstring)sCallbackEnv->CallObjectMethod(
mJavaInterface, method_getCurrentMediaId);
if (media_id == nullptr) {
- ALOGE("%s: Got a null media ID", __func__);
+ log::error("Got a null media ID");
return "";
}
@@ -584,7 +584,7 @@
}
static std::vector<SongInfo> getNowPlayingList() {
- ALOGD("%s", __func__);
+ log::debug("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mJavaInterface) return std::vector<SongInfo>();
@@ -592,7 +592,7 @@
jobject song_list =
sCallbackEnv->CallObjectMethod(mJavaInterface, method_getNowPlayingList);
if (song_list == nullptr) {
- ALOGE("%s: Got a null now playing list", __func__);
+ log::error("Got a null now playing list");
return std::vector<SongInfo>();
}
@@ -619,7 +619,7 @@
}
static uint16_t getCurrentPlayerId() {
- ALOGD("%s", __func__);
+ log::debug("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mJavaInterface) return 0u;
@@ -631,7 +631,7 @@
}
static std::vector<MediaPlayerInfo> getMediaPlayerList() {
- ALOGD("%s", __func__);
+ log::debug("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mJavaInterface)
@@ -641,7 +641,7 @@
mJavaInterface, method_getMediaPlayerList);
if (player_list == nullptr) {
- ALOGE("%s: Got a null media player list", __func__);
+ log::error("Got a null media player list");
return std::vector<MediaPlayerInfo>();
}
@@ -697,7 +697,7 @@
}
static void setBrowsedPlayer(uint16_t player_id, SetBrowsedPlayerCb cb) {
- ALOGD("%s", __func__);
+ log::debug("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mJavaInterface) return;
@@ -711,7 +711,7 @@
jint /* player_id */,
jboolean success, jstring root_id,
jint num_items) {
- ALOGD("%s", __func__);
+ log::debug("");
std::string root;
if (root_id != nullptr) {
@@ -725,7 +725,7 @@
static void getFolderItemsResponseNative(JNIEnv* env, jobject /* object */,
jstring parent_id, jobject list) {
- ALOGD("%s", __func__);
+ log::debug("");
std::string id;
if (parent_id != nullptr) {
@@ -739,8 +739,8 @@
// that both callbacks can be handled with one lookup if a request comes
// for a folder that is already trying to be looked at.
if (get_folder_items_cb_map.find(id) == get_folder_items_cb_map.end()) {
- ALOGE("Could not find response callback for the request of \"%s\"",
- id.c_str());
+ log::error("Could not find response callback for the request of \"{}\"",
+ id);
return;
}
@@ -748,7 +748,7 @@
get_folder_items_cb_map.erase(id);
if (list == nullptr) {
- ALOGE("%s: Got a null get folder items response list", __func__);
+ log::error("Got a null get folder items response list");
callback.Run(std::vector<ListItem>());
return;
}
@@ -802,7 +802,7 @@
static void getFolderItems(uint16_t player_id, std::string media_id,
GetFolderItemsCb cb) {
- ALOGD("%s", __func__);
+ log::debug("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mJavaInterface) return;
@@ -818,7 +818,7 @@
static void playItem(uint16_t player_id, bool now_playing,
std::string media_id) {
- ALOGD("%s", __func__);
+ log::debug("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mJavaInterface) return;
@@ -829,7 +829,7 @@
}
static void setActiveDevice(const RawAddress& address) {
- ALOGD("%s", __func__);
+ log::debug("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mJavaInterface) return;
@@ -840,7 +840,7 @@
}
static void volumeDeviceConnected(const RawAddress& address) {
- ALOGD("%s", __func__);
+ log::debug("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mJavaInterface) return;
@@ -853,7 +853,7 @@
static void volumeDeviceConnected(
const RawAddress& address,
::bluetooth::avrcp::VolumeInterface::VolumeChangedCb cb) {
- ALOGD("%s", __func__);
+ log::debug("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mJavaInterface) return;
@@ -866,7 +866,7 @@
}
static void volumeDeviceDisconnected(const RawAddress& address) {
- ALOGD("%s", __func__);
+ log::debug("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mJavaInterface) return;
@@ -887,14 +887,14 @@
if (!success) return;
- ALOGD("%s", __func__);
+ log::debug("");
if (volumeCallbackMap.find(bdaddr) != volumeCallbackMap.end()) {
volumeCallbackMap.find(bdaddr)->second.Run(volume & 0x7F);
}
}
static void setVolume(int8_t volume) {
- ALOGD("%s", __func__);
+ log::debug("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mJavaInterface) return;
@@ -906,7 +906,7 @@
jstring address, jboolean connected) {
std::unique_lock<std::shared_timed_mutex> interface_lock(interface_mutex);
if (mServiceCallbacks == nullptr) {
- ALOGW("%s: Service not loaded.", __func__);
+ log::warn("Service not loaded.");
return;
}
@@ -923,7 +923,7 @@
// Called from native to list available player settings
static void listPlayerSettings(ListPlayerSettingsCb cb) {
- ALOGD("%s", __func__);
+ log::debug("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mJavaInterface) return;
@@ -934,7 +934,7 @@
static void listPlayerSettingsResponseNative(JNIEnv* env, jobject /* object */,
jbyteArray attributes) {
- ALOGD("%s", __func__);
+ log::debug("");
std::vector<PlayerAttribute> attributes_vector;
copyJavaArraytoCppVector(env, attributes, attributes_vector);
@@ -945,7 +945,7 @@
// Called from native to list available values for player setting
static void listPlayerSettingValues(PlayerAttribute attribute,
ListPlayerSettingValuesCb cb) {
- ALOGD("%s", __func__);
+ log::debug("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mJavaInterface) return;
@@ -959,7 +959,7 @@
jobject /* object */,
jbyte attribute,
jbyteArray values) {
- ALOGD("%s", __func__);
+ log::debug("");
PlayerAttribute player_attribute = static_cast<PlayerAttribute>(attribute);
std::vector<uint8_t> values_vector;
copyJavaArraytoCppVector(env, values, values_vector);
@@ -969,7 +969,7 @@
// Called from native to get current player settings
static void getPlayerSettings(std::vector<PlayerAttribute> attributes,
GetCurrentPlayerSettingValueCb cb) {
- ALOGD("%s", __func__);
+ log::debug("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mJavaInterface) return;
@@ -987,7 +987,7 @@
static void getPlayerSettingsResponseNative(JNIEnv* env, jobject /* object */,
jbyteArray attributes,
jbyteArray values) {
- ALOGD("%s", __func__);
+ log::debug("");
std::vector<PlayerAttribute> attributes_vector;
std::vector<uint8_t> values_vector;
copyJavaArraytoCppVector(env, attributes, attributes_vector);
@@ -1000,7 +1000,7 @@
static void setPlayerSettings(std::vector<PlayerAttribute> attributes,
std::vector<uint8_t> values,
SetPlayerSettingValueCb cb) {
- ALOGD("%s", __func__);
+ log::debug("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mJavaInterface) return;
@@ -1024,16 +1024,16 @@
static void setPlayerSettingsResponseNative(JNIEnv* /* env */,
jobject /* object */,
jboolean success) {
- ALOGD("%s", __func__);
+ log::debug("");
set_player_setting_value_cb.Run(success);
}
static void sendPlayerSettingsNative(JNIEnv* env, jobject /* object */,
jbyteArray attributes, jbyteArray values) {
- ALOGD("%s", __func__);
+ log::debug("");
std::unique_lock<std::shared_timed_mutex> interface_lock(interface_mutex);
if (mServiceCallbacks == nullptr) {
- ALOGW("%s: Service not loaded.", __func__);
+ log::warn("Service not loaded.");
return;
}
std::vector<PlayerAttribute> attributes_vector;
diff --git a/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp b/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp
index 40a8aff..b49597d 100644
--- a/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp
+++ b/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp
@@ -16,6 +16,7 @@
*/
#define LOG_TAG "BluetoothServiceJni"
+
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
@@ -30,7 +31,7 @@
#include "com_android_bluetooth.h"
#include "hardware/bt_sock.h"
-#include "os/logging/log_redaction.h"
+#include "os/logging/log_adapter.h"
#include "utils/Log.h"
#include "utils/misc.h"
@@ -39,6 +40,14 @@
extern bt_interface_t bluetoothInterface;
#endif
+namespace fmt {
+template <>
+struct formatter<bt_state_t> : enum_formatter<bt_state_t> {};
+template <>
+struct formatter<bt_discovery_state_t> : enum_formatter<bt_discovery_state_t> {
+};
+} // namespace fmt
+
namespace android {
// Both
@@ -99,13 +108,13 @@
static void adapter_state_change_callback(bt_state_t status) {
std::shared_lock<std::shared_timed_mutex> lock(jniObjMutex);
if (!sJniCallbacksObj) {
- ALOGE("%s, JNI obj is null. Failed to call JNI callback", __func__);
+ log::error("JNI obj is null. Failed to call JNI callback");
return;
}
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
- ALOGV("%s: Status is: %d", __func__, status);
+ log::verbose("Status is: {}", status);
sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_stateChangeCallback,
(jint)status);
@@ -117,7 +126,7 @@
ScopedLocalRef<jbyteArray> propVal(
callbackEnv, callbackEnv->NewByteArray(properties[i].len));
if (!propVal.get()) {
- ALOGE("Error while allocation of array in %s", __func__);
+ log::error("Error while allocation of array");
return -1;
}
@@ -133,17 +142,18 @@
bt_property_t* properties) {
std::shared_lock<std::shared_timed_mutex> lock(jniObjMutex);
if (!sJniCallbacksObj) {
- ALOGE("%s, JNI obj is null. Failed to call JNI callback", __func__);
+ log::error("JNI obj is null. Failed to call JNI callback");
return;
}
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
- ALOGV("%s: Status is: %d, Properties: %d", __func__, status, num_properties);
+ log::verbose("Status is: {}, Properties: {}", bt_status_text(status),
+ num_properties);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("%s: Status %d is incorrect", __func__, status);
+ log::error("Status {} is incorrect", bt_status_text(status));
return;
}
@@ -151,7 +161,7 @@
sCallbackEnv.get(),
(jbyteArray)sCallbackEnv->NewByteArray(num_properties));
if (!val.get()) {
- ALOGE("%s: Error allocating byteArray", __func__);
+ log::error("Error allocating byteArray");
return;
}
@@ -165,14 +175,14 @@
sCallbackEnv.get(),
sCallbackEnv->NewObjectArray(num_properties, mclass.get(), NULL));
if (!props.get()) {
- ALOGE("%s: Error allocating object Array for properties", __func__);
+ log::error("Error allocating object Array for properties");
return;
}
ScopedLocalRef<jintArray> types(
sCallbackEnv.get(), (jintArray)sCallbackEnv->NewIntArray(num_properties));
if (!types.get()) {
- ALOGE("%s: Error allocating int Array for values", __func__);
+ log::error("Error allocating int Array for values");
return;
}
@@ -193,17 +203,18 @@
bt_property_t* properties) {
std::shared_lock<std::shared_timed_mutex> lock(jniObjMutex);
if (!sJniCallbacksObj) {
- ALOGE("%s, JNI obj is null. Failed to call JNI callback", __func__);
+ log::error("JNI obj is null. Failed to call JNI callback");
return;
}
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
- ALOGV("%s: Status is: %d, Properties: %d", __func__, status, num_properties);
+ log::verbose("Status is: {}, Properties: {}", bt_status_text(status),
+ num_properties);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("%s: Status %d is incorrect", __func__, status);
+ log::error("Status {} is incorrect", bt_status_text(status));
return;
}
@@ -211,7 +222,7 @@
sCallbackEnv.get(),
(jbyteArray)sCallbackEnv->NewByteArray(num_properties));
if (!val.get()) {
- ALOGE("%s: Error allocating byteArray", __func__);
+ log::error("Error allocating byteArray");
return;
}
@@ -225,21 +236,21 @@
sCallbackEnv.get(),
sCallbackEnv->NewObjectArray(num_properties, mclass.get(), NULL));
if (!props.get()) {
- ALOGE("%s: Error allocating object Array for properties", __func__);
+ log::error("Error allocating object Array for properties");
return;
}
ScopedLocalRef<jintArray> types(
sCallbackEnv.get(), (jintArray)sCallbackEnv->NewIntArray(num_properties));
if (!types.get()) {
- ALOGE("%s: Error allocating int Array for values", __func__);
+ log::error("Error allocating int Array for values");
return;
}
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("Error while allocation byte array in %s", __func__);
+ log::error("Error while allocation byte array");
return;
}
@@ -261,7 +272,7 @@
bt_property_t* properties) {
std::shared_lock<std::shared_timed_mutex> lock(jniObjMutex);
if (!sJniCallbacksObj) {
- ALOGE("%s, JNI obj is null. Failed to call JNI callback", __func__);
+ log::error("JNI obj is null. Failed to call JNI callback");
return;
}
@@ -274,7 +285,7 @@
if (properties[i].type == BT_PROPERTY_BDADDR) {
addr.reset(sCallbackEnv->NewByteArray(properties[i].len));
if (!addr.get()) {
- ALOGE("Address is NULL (unable to allocate) in %s", __func__);
+ log::error("Address is NULL (unable to allocate)");
return;
}
sCallbackEnv->SetByteArrayRegion(addr.get(), 0, properties[i].len,
@@ -283,12 +294,13 @@
}
}
if (!addr.get()) {
- ALOGE("Address is NULL in %s", __func__);
+ log::error("Address is NULL");
return;
}
- ALOGV("%s: Properties: %d, Address: %s", __func__, num_properties,
- (const char*)properties[addr_index].val);
+ log::verbose(
+ "Properties: {}, Address: {}", num_properties,
+ ADDRESS_TO_LOGGABLE_STR(*(RawAddress*)properties[addr_index].val));
remote_device_properties_callback(BT_STATUS_SUCCESS,
(RawAddress*)properties[addr_index].val,
@@ -303,7 +315,7 @@
int fail_reason) {
std::shared_lock<std::shared_timed_mutex> lock(jniObjMutex);
if (!sJniCallbacksObj) {
- ALOGE("%s, JNI obj is null. Failed to call JNI callback", __func__);
+ log::error("JNI obj is null. Failed to call JNI callback");
return;
}
@@ -311,14 +323,14 @@
if (!sCallbackEnv.valid()) return;
if (!bd_addr) {
- ALOGE("Address is null in %s", __func__);
+ log::error("Address is null");
return;
}
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("Address allocation failed in %s", __func__);
+ log::error("Address allocation failed");
return;
}
sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress),
@@ -333,7 +345,7 @@
RawAddress* secondary_bd_addr) {
std::shared_lock<std::shared_timed_mutex> lock(jniObjMutex);
if (!sJniCallbacksObj) {
- ALOGE("%s, JNI obj is null. Failed to call JNI callback", __func__);
+ log::error("JNI obj is null. Failed to call JNI callback");
return;
}
@@ -342,7 +354,7 @@
ScopedLocalRef<jbyteArray> main_addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!main_addr.get()) {
- ALOGE("Address allocation failed in %s", __func__);
+ log::error("Address allocation failed");
return;
}
sCallbackEnv->SetByteArrayRegion(main_addr.get(), 0, sizeof(RawAddress),
@@ -351,7 +363,7 @@
ScopedLocalRef<jbyteArray> secondary_addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!secondary_addr.get()) {
- ALOGE("Address allocation failed in %s", __func__);
+ log::error("Address allocation failed");
return;
}
@@ -367,7 +379,7 @@
RawAddress* secondary_bd_addr) {
std::shared_lock<std::shared_timed_mutex> lock(jniObjMutex);
if (!sJniCallbacksObj) {
- ALOGE("%s, JNI obj is null. Failed to call JNI callback", __func__);
+ log::error("JNI obj is null. Failed to call JNI callback");
return;
}
@@ -376,7 +388,7 @@
ScopedLocalRef<jbyteArray> main_addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!main_addr.get()) {
- ALOGE("Address allocation failed in %s", __func__);
+ log::error("Address allocation failed");
return;
}
sCallbackEnv->SetByteArrayRegion(main_addr.get(), 0, sizeof(RawAddress),
@@ -385,7 +397,7 @@
ScopedLocalRef<jbyteArray> secondary_addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!secondary_addr.get()) {
- ALOGE("Address allocation failed in %s", __func__);
+ log::error("Address allocation failed");
return;
}
@@ -404,13 +416,13 @@
bt_conn_direction_t /* direction */,
uint16_t acl_handle) {
if (!bd_addr) {
- ALOGE("Address is null in %s", __func__);
+ log::error("Address is null");
return;
}
std::shared_lock<std::shared_timed_mutex> lock(jniObjMutex);
if (!sJniCallbacksObj) {
- ALOGE("%s, JNI obj is null. Failed to call JNI callback", __func__);
+ log::error("JNI obj is null. Failed to call JNI callback");
return;
}
@@ -420,7 +432,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("Address allocation failed in %s", __func__);
+ log::error("Address allocation failed");
return;
}
sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress),
@@ -435,14 +447,14 @@
static void discovery_state_changed_callback(bt_discovery_state_t state) {
std::shared_lock<std::shared_timed_mutex> lock(jniObjMutex);
if (!sJniCallbacksObj) {
- ALOGE("%s, JNI obj is null. Failed to call JNI callback", __func__);
+ log::error("JNI obj is null. Failed to call JNI callback");
return;
}
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
- ALOGV("%s: DiscoveryState:%d ", __func__, state);
+ log::verbose("DiscoveryState:{} ", state);
sCallbackEnv->CallVoidMethod(
sJniCallbacksObj, method_discoveryStateChangeCallback, (jint)state);
@@ -451,13 +463,13 @@
static void pin_request_callback(RawAddress* bd_addr, bt_bdname_t* bdname,
uint32_t cod, bool min_16_digits) {
if (!bd_addr) {
- ALOGE("Address is null in %s", __func__);
+ log::error("Address is null");
return;
}
std::shared_lock<std::shared_timed_mutex> lock(jniObjMutex);
if (!sJniCallbacksObj) {
- ALOGE("%s, JNI obj is null. Failed to call JNI callback", __func__);
+ log::error("JNI obj is null. Failed to call JNI callback");
return;
}
@@ -467,7 +479,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("Error while allocating in: %s", __func__);
+ log::error("Error while allocating");
return;
}
@@ -477,7 +489,7 @@
ScopedLocalRef<jbyteArray> devname(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(bt_bdname_t)));
if (!devname.get()) {
- ALOGE("Error while allocating in: %s", __func__);
+ log::error("Error while allocating");
return;
}
@@ -492,13 +504,13 @@
uint32_t cod, bt_ssp_variant_t pairing_variant,
uint32_t pass_key) {
if (!bd_addr) {
- ALOGE("Address is null in %s", __func__);
+ log::error("Address is null");
return;
}
std::shared_lock<std::shared_timed_mutex> lock(jniObjMutex);
if (!sJniCallbacksObj) {
- ALOGE("%s, JNI obj is null. Failed to call JNI callback", __func__);
+ log::error("JNI obj is null. Failed to call JNI callback");
return;
}
@@ -508,7 +520,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("Error while allocating in: %s", __func__);
+ log::error("Error while allocating");
return;
}
@@ -518,7 +530,7 @@
ScopedLocalRef<jbyteArray> devname(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(bt_bdname_t)));
if (!devname.get()) {
- ALOGE("Error while allocating in: %s", __func__);
+ log::error("Error while allocating");
return;
}
@@ -531,7 +543,7 @@
}
static jobject createClassicOobDataObject(JNIEnv* env, bt_oob_data_t oob_data) {
- ALOGV("%s", __func__);
+ log::verbose("");
jmethodID classicBuilderConstructor;
jmethodID setRMethod;
jmethodID setNameMethod;
@@ -595,7 +607,7 @@
}
static jobject createLeOobDataObject(JNIEnv* env, bt_oob_data_t oob_data) {
- ALOGV("%s", __func__);
+ log::verbose("");
jmethodID leBuilderConstructor;
jmethodID setRMethod;
@@ -656,11 +668,11 @@
static void generate_local_oob_data_callback(tBT_TRANSPORT transport,
bt_oob_data_t oob_data) {
- ALOGV("%s", __func__);
+ log::verbose("");
std::shared_lock<std::shared_timed_mutex> lock(jniObjMutex);
if (!sJniCallbacksObj) {
- ALOGE("%s, JNI obj is null. Failed to call JNI callback", __func__);
+ log::error("JNI obj is null. Failed to call JNI callback");
return;
}
@@ -683,7 +695,7 @@
// TRANSPORT_AUTO is a concept, however, the host stack doesn't fully
// implement it So passing it from the java layer is currently useless until
// the implementation and concept of TRANSPORT_AUTO is fleshed out.
- ALOGE("TRANSPORT: %d not implemented", transport);
+ log::error("TRANSPORT: {} not implemented", transport);
sCallbackEnv->CallVoidMethod(sJniCallbacksObj,
method_oobDataReceivedCallback,
(jint)transport, nullptr);
@@ -696,16 +708,16 @@
int negative_acknowledgement_count) {
std::shared_lock<std::shared_timed_mutex> lock(jniObjMutex);
if (!sJniCallbacksObj) {
- ALOGE("%s, JNI obj is null. Failed to call JNI callback", __func__);
+ log::error("JNI obj is null. Failed to call JNI callback");
return;
}
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
- ALOGV("%s: LinkQualityReportCallback: %d %d %d %d %d %d", __func__,
- report_id, rssi, snr, retransmission_count, packets_not_receive_count,
- negative_acknowledgement_count);
+ log::verbose("LinkQualityReportCallback: {} {} {} {} {} {}", report_id, rssi,
+ snr, retransmission_count, packets_not_receive_count,
+ negative_acknowledgement_count);
sCallbackEnv->CallVoidMethod(
sJniCallbacksObj, method_linkQualityReportCallback,
@@ -717,15 +729,15 @@
static void switch_buffer_size_callback(bool is_low_latency_buffer_size) {
std::shared_lock<std::shared_timed_mutex> lock(jniObjMutex);
if (!sJniCallbacksObj) {
- ALOGE("%s, JNI obj is null. Failed to call JNI callback", __func__);
+ log::error("JNI obj is null. Failed to call JNI callback");
return;
}
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
- ALOGV("%s: SwitchBufferSizeCallback: %s", __func__,
- is_low_latency_buffer_size ? "true" : "false");
+ log::verbose("SwitchBufferSizeCallback: {}",
+ is_low_latency_buffer_size ? "true" : "false");
sCallbackEnv->CallVoidMethod(
sJniCallbacksObj, method_switchBufferSizeCallback,
@@ -735,15 +747,15 @@
static void switch_codec_callback(bool is_low_latency_buffer_size) {
std::shared_lock<std::shared_timed_mutex> lock(jniObjMutex);
if (!sJniCallbacksObj) {
- ALOGE("%s, JNI obj is null. Failed to call JNI callback", __func__);
+ log::error("JNI obj is null. Failed to call JNI callback");
return;
}
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
- ALOGV("%s: SwitchCodecCallback: %s", __func__,
- is_low_latency_buffer_size ? "true" : "false");
+ log::verbose("SwitchCodecCallback: {}",
+ is_low_latency_buffer_size ? "true" : "false");
sCallbackEnv->CallVoidMethod(sJniCallbacksObj, method_switchCodecCallback,
(jboolean)is_low_latency_buffer_size);
@@ -756,7 +768,7 @@
static void key_missing_callback(const RawAddress bd_addr) {
std::shared_lock<std::shared_timed_mutex> lock(jniObjMutex);
if (!sJniCallbacksObj) {
- ALOGE("%s, JNI obj is null. Failed to call JNI callback", __func__);
+ log::error("JNI obj is null. Failed to call JNI callback");
return;
}
@@ -766,7 +778,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("Address allocation failed in %s", __func__);
+ log::error("Address allocation failed");
return;
}
sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress),
@@ -786,10 +798,10 @@
vm->AttachCurrentThread(&callbackEnv, &args);
sHaveCallbackThread = true;
sCallbackThread = pthread_self();
- ALOGV("Callback thread attached: %p", callbackEnv);
+ log::verbose("Callback thread attached: {}", fmt::ptr(callbackEnv));
} else if (event == DISASSOCIATE_JVM) {
if (!isCallbackThread()) {
- ALOGE("Callback: '%s' is not called on the correct thread", __func__);
+ log::error("Callback: '' is not called on the correct thread");
return;
}
vm->DetachCurrentThread();
@@ -803,14 +815,15 @@
static void le_test_mode_recv_callback(bt_status_t status,
uint16_t packet_count) {
- ALOGV("%s: status:%d packet_count:%d ", __func__, status, packet_count);
+ log::verbose("status:{} packet_count:{} ", bt_status_text(status),
+ packet_count);
}
static void energy_info_recv_callback(bt_activity_energy_info* p_energy_info,
bt_uid_traffic_t* uid_data) {
std::shared_lock<std::shared_timed_mutex> lock(jniObjMutex);
if (!sJniAdapterServiceObj) {
- ALOGE("%s, JNI obj is null. Failed to call JNI callback", __func__);
+ log::error("JNI obj is null. Failed to call JNI callback");
return;
}
@@ -871,9 +884,9 @@
status_ = vm_->GetEnv((void**)&env_, JNI_VERSION_1_6);
if (status_ != JNI_OK && status_ != JNI_EDETACHED) {
- ALOGE(
- "JNIThreadAttacher: unable to get environment for JNI CALL, "
- "status: %d",
+ log::error(
+ "JNIThreadAttacher: unable to get environment for JNI CALL, status: "
+ "{}",
status_);
env_ = nullptr;
return;
@@ -882,8 +895,8 @@
if (status_ == JNI_EDETACHED) {
char name[17] = {0};
if (prctl(PR_GET_NAME, (unsigned long)name) != 0) {
- ALOGE(
- "JNIThreadAttacher: unable to grab previous thread name, error: %s",
+ log::error(
+ "JNIThreadAttacher: unable to grab previous thread name, error: {}",
strerror(errno));
env_ = nullptr;
return;
@@ -892,7 +905,7 @@
JavaVMAttachArgs args = {
.version = JNI_VERSION_1_6, .name = name, .group = nullptr};
if (vm_->AttachCurrentThread(&env_, &args) != 0) {
- ALOGE("JNIThreadAttacher: unable to attach thread to VM");
+ log::error("JNIThreadAttacher: unable to attach thread to VM");
env_ = nullptr;
return;
}
@@ -914,7 +927,7 @@
static int acquire_wake_lock_callout(const char* lock_name) {
std::shared_lock<std::shared_timed_mutex> lock(jniObjMutex);
if (!sJniAdapterServiceObj) {
- ALOGE("%s, JNI obj is null. Failed to call JNI callback", __func__);
+ log::error("JNI obj is null. Failed to call JNI callback");
return BT_STATUS_NOT_READY;
}
@@ -922,7 +935,7 @@
JNIEnv* env = attacher.getEnv();
if (env == nullptr) {
- ALOGE("%s: Unable to get JNI Env", __func__);
+ log::error("Unable to get JNI Env");
return BT_STATUS_JNI_THREAD_ATTACH_ERROR;
}
@@ -934,7 +947,7 @@
sJniCallbacksObj, method_acquireWakeLock, lock_name_jni.get());
if (!acquired) ret = BT_STATUS_WAKELOCK_ERROR;
} else {
- ALOGE("%s unable to allocate string: %s", __func__, lock_name);
+ log::error("unable to allocate string: {}", lock_name);
ret = BT_STATUS_NOMEM;
}
}
@@ -945,7 +958,7 @@
static int release_wake_lock_callout(const char* lock_name) {
std::shared_lock<std::shared_timed_mutex> lock(jniObjMutex);
if (!sJniAdapterServiceObj) {
- ALOGE("%s, JNI obj is null. Failed to call JNI callback", __func__);
+ log::error("JNI obj is null. Failed to call JNI callback");
return BT_STATUS_NOT_READY;
}
@@ -953,7 +966,7 @@
JNIEnv* env = attacher.getEnv();
if (env == nullptr) {
- ALOGE("%s: Unable to get JNI Env", __func__);
+ log::error("Unable to get JNI Env");
return BT_STATUS_JNI_THREAD_ATTACH_ERROR;
}
@@ -965,7 +978,7 @@
sJniCallbacksObj, method_releaseWakeLock, lock_name_jni.get());
if (!released) ret = BT_STATUS_WAKELOCK_ERROR;
} else {
- ALOGE("%s unable to allocate string: %s", __func__, lock_name);
+ log::error("unable to allocate string: {}", lock_name);
ret = BT_STATUS_NOMEM;
}
}
@@ -991,20 +1004,20 @@
void* handle = dlopen("libbluetooth.so", RTLD_NOW);
if (!handle) {
const char* err_str = dlerror();
- ALOGE("%s: failed to load Bluetooth library, error=%s", __func__,
- err_str ? err_str : "error unknown");
+ log::error("failed to load Bluetooth library, error={}",
+ err_str ? err_str : "error unknown");
goto error;
}
// Get the address of the bt_interface_t.
itf = (bt_interface_t*)dlsym(handle, sym);
if (!itf) {
- ALOGE("%s: failed to load symbol from Bluetooth library %s", __func__, sym);
+ log::error("failed to load symbol from Bluetooth library {}", sym);
goto error;
}
// Success.
- ALOGI("%s: loaded Bluetooth library successfully", __func__);
+ log::info("loaded Bluetooth library successfully");
*interface = itf;
return 0;
@@ -1022,7 +1035,7 @@
jstring userDataDirectory) {
std::unique_lock<std::shared_timed_mutex> lock(jniObjMutex);
- ALOGV("%s", __func__);
+ log::verbose("");
android_bluetooth_UidTraffic.clazz =
(jclass)env->NewGlobalRef(env->FindClass("android/bluetooth/UidTraffic"));
@@ -1066,13 +1079,13 @@
delete[] flagObjs;
if (ret != BT_STATUS_SUCCESS) {
- ALOGE("Error while setting the callbacks: %d\n", ret);
+ log::error("Error while setting the callbacks: {}", ret);
sBluetoothInterface = NULL;
return JNI_FALSE;
}
ret = sBluetoothInterface->set_os_callouts(&sBluetoothOsCallouts);
if (ret != BT_STATUS_SUCCESS) {
- ALOGE("Error while setting Bluetooth callouts: %d\n", ret);
+ log::error("Error while setting Bluetooth callouts: {}", ret);
sBluetoothInterface->cleanup();
sBluetoothInterface = NULL;
return JNI_FALSE;
@@ -1082,7 +1095,7 @@
(btsock_interface_t*)sBluetoothInterface->get_profile_interface(
BT_PROFILE_SOCKETS_ID);
if (sBluetoothSocketInterface == NULL) {
- ALOGE("Error getting socket interface");
+ log::error("Error getting socket interface");
}
return JNI_TRUE;
@@ -1091,12 +1104,12 @@
static bool cleanupNative(JNIEnv* env, jobject /* obj */) {
std::unique_lock<std::shared_timed_mutex> lock(jniObjMutex);
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
sBluetoothInterface->cleanup();
- ALOGI("%s: return from cleanup", __func__);
+ log::info("return from cleanup");
if (sJniCallbacksObj) {
env->DeleteGlobalRef(sJniCallbacksObj);
@@ -1116,7 +1129,7 @@
}
static jboolean enableNative(JNIEnv* /* env */, jobject /* obj */) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
int ret = sBluetoothInterface->enable();
@@ -1125,7 +1138,7 @@
}
static jboolean disableNative(JNIEnv* /* env */, jobject /* obj */) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
@@ -1138,7 +1151,7 @@
}
static jboolean startDiscoveryNative(JNIEnv* /* env */, jobject /* obj */) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
@@ -1147,7 +1160,7 @@
}
static jboolean cancelDiscoveryNative(JNIEnv* /* env */, jobject /* obj */) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
@@ -1158,7 +1171,7 @@
static jboolean createBondNative(JNIEnv* env, jobject /* obj */,
jbyteArray address, jint addrType,
jint transport) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
@@ -1177,7 +1190,7 @@
}
if (ret != BT_STATUS_SUCCESS) {
- ALOGW("%s: Failed to initiate bonding. Status = %d", __func__, ret);
+ log::warn("Failed to initiate bonding. Status = {}", ret);
}
env->ReleaseByteArrayElements(address, addr, 0);
@@ -1205,7 +1218,7 @@
jint transport) {
// Need both arguments to be non NULL
if (oobData == NULL) {
- ALOGE("%s: oobData is null! Nothing to do.", __func__);
+ log::error("oobData is null! Nothing to do.");
return JNI_FALSE;
}
@@ -1217,8 +1230,8 @@
// Check the data
int len = env->GetArrayLength(address);
if (len != OOB_ADDRESS_SIZE) {
- ALOGE("%s: addressBytes must be 7 bytes in length (address plus type) 6+1!",
- __func__);
+ log::error(
+ "addressBytes must be 7 bytes in length (address plus type) 6+1!");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
@@ -1226,7 +1239,7 @@
// Convert the address from byte[]
jbyte* addressBytes = env->GetByteArrayElements(address, NULL);
if (addressBytes == NULL) {
- ALOGE("%s: addressBytes cannot be null!", __func__);
+ log::error("addressBytes cannot be null!");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
@@ -1243,10 +1256,10 @@
deviceNameBytes = env->GetByteArrayElements(deviceName, NULL);
int len = env->GetArrayLength(deviceName);
if (len > OOB_NAME_MAX_SIZE) {
- ALOGI(
- "%s: wrong length of deviceName, should be empty or less than or "
- "equal to %d bytes.",
- __func__, OOB_NAME_MAX_SIZE);
+ log::info(
+ "wrong length of deviceName, should be empty or less than or equal "
+ "to {} bytes.",
+ OOB_NAME_MAX_SIZE);
jniThrowIOException(env, EINVAL);
env->ReleaseByteArrayElements(deviceName, deviceNameBytes, 0);
return JNI_FALSE;
@@ -1258,7 +1271,7 @@
jbyteArray confirmation = callByteArrayGetter(
env, oobData, "android/bluetooth/OobData", "getConfirmationHash");
if (confirmation == NULL) {
- ALOGE("%s: confirmation cannot be null!", __func__);
+ log::error("confirmation cannot be null!");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
@@ -1268,10 +1281,8 @@
confirmationBytes = env->GetByteArrayElements(confirmation, NULL);
len = env->GetArrayLength(confirmation);
if (confirmationBytes == NULL || len != OOB_C_SIZE) {
- ALOGI(
- "%s: wrong length of Confirmation, should be empty or %d "
- "bytes.",
- __func__, OOB_C_SIZE);
+ log::info("wrong length of Confirmation, should be empty or {} bytes.",
+ OOB_C_SIZE);
jniThrowIOException(env, EINVAL);
env->ReleaseByteArrayElements(confirmation, confirmationBytes, 0);
return JNI_FALSE;
@@ -1287,8 +1298,8 @@
randomizerBytes = env->GetByteArrayElements(randomizer, NULL);
int len = env->GetArrayLength(randomizer);
if (randomizerBytes == NULL || len != OOB_R_SIZE) {
- ALOGI("%s: wrong length of Random, should be empty or %d bytes.",
- __func__, OOB_R_SIZE);
+ log::info("wrong length of Random, should be empty or {} bytes.",
+ OOB_R_SIZE);
jniThrowIOException(env, EINVAL);
env->ReleaseByteArrayElements(randomizer, randomizerBytes, 0);
return JNI_FALSE;
@@ -1306,8 +1317,8 @@
jbyte* oobDataLengthBytes = NULL;
if (oobDataLength == NULL ||
env->GetArrayLength(oobDataLength) != OOB_DATA_LEN_SIZE) {
- ALOGI("%s: wrong length of oobDataLength, should be empty or %d bytes.",
- __func__, OOB_DATA_LEN_SIZE);
+ log::info("wrong length of oobDataLength, should be empty or {} bytes.",
+ OOB_DATA_LEN_SIZE);
jniThrowIOException(env, EINVAL);
env->ReleaseByteArrayElements(oobDataLength, oobDataLengthBytes, 0);
return JNI_FALSE;
@@ -1325,8 +1336,8 @@
classOfDeviceBytes = env->GetByteArrayElements(classOfDevice, NULL);
int len = env->GetArrayLength(classOfDevice);
if (len != OOB_COD_SIZE) {
- ALOGI("%s: wrong length of classOfDevice, should be empty or %d bytes.",
- __func__, OOB_COD_SIZE);
+ log::info("wrong length of classOfDevice, should be empty or {} bytes.",
+ OOB_COD_SIZE);
jniThrowIOException(env, EINVAL);
env->ReleaseByteArrayElements(classOfDevice, classOfDeviceBytes, 0);
return JNI_FALSE;
@@ -1343,8 +1354,8 @@
temporaryKeyBytes = env->GetByteArrayElements(temporaryKey, NULL);
int len = env->GetArrayLength(temporaryKey);
if (len != OOB_TK_SIZE) {
- ALOGI("%s: wrong length of temporaryKey, should be empty or %d bytes.",
- __func__, OOB_TK_SIZE);
+ log::info("wrong length of temporaryKey, should be empty or {} bytes.",
+ OOB_TK_SIZE);
jniThrowIOException(env, EINVAL);
env->ReleaseByteArrayElements(temporaryKey, temporaryKeyBytes, 0);
return JNI_FALSE;
@@ -1360,8 +1371,8 @@
leAppearanceBytes = env->GetByteArrayElements(leAppearance, NULL);
int len = env->GetArrayLength(leAppearance);
if (len != OOB_LE_APPEARANCE_SIZE) {
- ALOGI("%s: wrong length of leAppearance, should be empty or %d bytes.",
- __func__, OOB_LE_APPEARANCE_SIZE);
+ log::info("wrong length of leAppearance, should be empty or {} bytes.",
+ OOB_LE_APPEARANCE_SIZE);
jniThrowIOException(env, EINVAL);
env->ReleaseByteArrayElements(leAppearance, leAppearanceBytes, 0);
return JNI_FALSE;
@@ -1388,7 +1399,7 @@
if (sBluetoothInterface->generate_local_oob_data(transport) !=
BT_STATUS_SUCCESS) {
- ALOGE("%s: Call to generate_local_oob_data failed!", __func__);
+ log::error("Call to generate_local_oob_data failed!");
bt_oob_data_t oob_data;
oob_data.is_valid = false;
generate_local_oob_data_callback(transport, oob_data);
@@ -1403,7 +1414,7 @@
// No data? Can't do anything
if (p192Data == NULL && p256Data == NULL) {
- ALOGE("%s: All OOB Data are null! Nothing to do.", __func__);
+ log::error("All OOB Data are null! Nothing to do.");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
@@ -1412,7 +1423,7 @@
// In the future we want to remove this and just reverse the address
// for the oobdata in the host stack.
if (address == NULL) {
- ALOGE("%s: Address cannot be null! Nothing to do.", __func__);
+ log::error("Address cannot be null! Nothing to do.");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
@@ -1420,8 +1431,8 @@
// Check the data
int len = env->GetArrayLength(address);
if (len != 6) {
- ALOGE("%s: addressBytes must be 6 bytes in length (address plus type) 6+1!",
- __func__);
+ log::error(
+ "addressBytes must be 6 bytes in length (address plus type) 6+1!");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
@@ -1459,7 +1470,7 @@
static jboolean removeBondNative(JNIEnv* env, jobject /* obj */,
jbyteArray address) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
@@ -1477,7 +1488,7 @@
static jboolean cancelBondNative(JNIEnv* env, jobject /* obj */,
jbyteArray address) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
@@ -1493,7 +1504,7 @@
}
static jboolean pairingIsBusyNative(JNIEnv* /*env*/, jobject /* obj */) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
@@ -1502,7 +1513,7 @@
static int getConnectionStateNative(JNIEnv* env, jobject /* obj */,
jbyteArray address) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
jbyte* addr = env->GetByteArrayElements(address, NULL);
@@ -1520,7 +1531,7 @@
static jboolean pinReplyNative(JNIEnv* env, jobject /* obj */,
jbyteArray address, jboolean accept, jint len,
jbyteArray pinArray) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
@@ -1551,7 +1562,7 @@
static jboolean sspReplyNative(JNIEnv* env, jobject /* obj */,
jbyteArray address, jint type, jboolean accept,
jint passkey) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
@@ -1570,7 +1581,7 @@
static jboolean setAdapterPropertyNative(JNIEnv* env, jobject /* obj */,
jint type, jbyteArray value) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
@@ -1588,7 +1599,7 @@
static jboolean getAdapterPropertiesNative(JNIEnv* /* env */,
jobject /* obj */) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
@@ -1598,7 +1609,7 @@
static jboolean getAdapterPropertyNative(JNIEnv* /* env */, jobject /* obj */,
jint type) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
@@ -1608,7 +1619,7 @@
static jboolean getDevicePropertyNative(JNIEnv* env, jobject /* obj */,
jbyteArray address, jint type) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
@@ -1627,7 +1638,7 @@
static jboolean setDevicePropertyNative(JNIEnv* env, jobject /* obj */,
jbyteArray address, jint type,
jbyteArray value) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
@@ -1659,7 +1670,7 @@
static jboolean getRemoteServicesNative(JNIEnv* env, jobject /* obj */,
jbyteArray address, jint transport) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
@@ -1676,7 +1687,7 @@
}
static int readEnergyInfoNative() {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
int ret = sBluetoothInterface->read_energy_info();
@@ -1685,7 +1696,7 @@
static void dumpNative(JNIEnv* env, jobject /* obj */, jobject fdObj,
jobjectArray argArray) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return;
int fd = jniGetFDFromFileDescriptor(env, fdObj);
@@ -1716,7 +1727,7 @@
}
static jbyteArray dumpMetricsNative(JNIEnv* env, jobject /* obj */) {
- ALOGI("%s", __func__);
+ log::info("");
if (!sBluetoothInterface) return env->NewByteArray(0);
std::string output;
@@ -1729,7 +1740,7 @@
}
static jboolean factoryResetNative(JNIEnv* /* env */, jobject /* obj */) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
int ret = sBluetoothInterface->config_clear();
return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -1737,7 +1748,7 @@
static jbyteArray obfuscateAddressNative(JNIEnv* env, jobject /* obj */,
jbyteArray address) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return env->NewByteArray(0);
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (addr == nullptr) {
@@ -1757,7 +1768,7 @@
static jboolean setBufferLengthMillisNative(JNIEnv* /* env */,
jobject /* obj */, jint codec,
jint size) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
@@ -1848,7 +1859,7 @@
static int getMetricIdNative(JNIEnv* env, jobject /* obj */,
jbyteArray address) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return 0; // 0 is invalid id
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (addr == nullptr) {
@@ -1863,7 +1874,7 @@
static jboolean allowLowLatencyAudioNative(JNIEnv* env, jobject /* obj */,
jboolean allowed,
jbyteArray address) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return false;
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (addr == nullptr) {
@@ -1880,7 +1891,7 @@
static void metadataChangedNative(JNIEnv* env, jobject /* obj */,
jbyteArray address, jint key,
jbyteArray value) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return;
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (addr == nullptr) {
@@ -1891,7 +1902,7 @@
addr_obj.FromOctets((uint8_t*)addr);
if (value == NULL) {
- ALOGE("metadataChangedNative() ignoring NULL array");
+ log::error("metadataChangedNative() ignoring NULL array");
return;
}
@@ -1909,22 +1920,22 @@
static jboolean isLogRedactionEnabledNative(JNIEnv* /* env */,
jobject /* obj */) {
- ALOGV("%s", __func__);
+ log::verbose("");
return bluetooth::os::should_log_be_redacted();
}
static jboolean interopMatchAddrNative(JNIEnv* env, jclass /* clazz */,
jstring feature_name, jstring address) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) {
- ALOGW("%s: sBluetoothInterface is null.", __func__);
+ log::warn("sBluetoothInterface is null.");
return JNI_FALSE;
}
const char* tmp_addr = env->GetStringUTFChars(address, NULL);
if (!tmp_addr) {
- ALOGW("%s: address is null.", __func__);
+ log::warn("address is null.");
return JNI_FALSE;
}
RawAddress bdaddr;
@@ -1933,13 +1944,13 @@
env->ReleaseStringUTFChars(address, tmp_addr);
if (!success) {
- ALOGW("%s: address is invalid.", __func__);
+ log::warn("address is invalid.");
return JNI_FALSE;
}
const char* feature_name_str = env->GetStringUTFChars(feature_name, NULL);
if (!feature_name_str) {
- ALOGW("%s: feature name is null.", __func__);
+ log::warn("feature name is null.");
return JNI_FALSE;
}
@@ -1952,22 +1963,22 @@
static jboolean interopMatchNameNative(JNIEnv* env, jclass /* clazz */,
jstring feature_name, jstring name) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) {
- ALOGW("%s: sBluetoothInterface is null.", __func__);
+ log::warn("sBluetoothInterface is null.");
return JNI_FALSE;
}
const char* feature_name_str = env->GetStringUTFChars(feature_name, NULL);
if (!feature_name_str) {
- ALOGW("%s: feature name is null.", __func__);
+ log::warn("feature name is null.");
return JNI_FALSE;
}
const char* name_str = env->GetStringUTFChars(name, NULL);
if (!name_str) {
- ALOGW("%s: name is null.", __func__);
+ log::warn("name is null.");
env->ReleaseStringUTFChars(feature_name, feature_name_str);
return JNI_FALSE;
}
@@ -1983,16 +1994,16 @@
static jboolean interopMatchAddrOrNameNative(JNIEnv* env, jclass /* clazz */,
jstring feature_name,
jstring address) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) {
- ALOGW("%s: sBluetoothInterface is null.", __func__);
+ log::warn("sBluetoothInterface is null.");
return JNI_FALSE;
}
const char* tmp_addr = env->GetStringUTFChars(address, NULL);
if (!tmp_addr) {
- ALOGW("%s: address is null.", __func__);
+ log::warn("address is null.");
return JNI_FALSE;
}
RawAddress bdaddr;
@@ -2001,13 +2012,13 @@
env->ReleaseStringUTFChars(address, tmp_addr);
if (!success) {
- ALOGW("%s: address is invalid.", __func__);
+ log::warn("address is invalid.");
return JNI_FALSE;
}
const char* feature_name_str = env->GetStringUTFChars(feature_name, NULL);
if (!feature_name_str) {
- ALOGW("%s: feature name is null.", __func__);
+ log::warn("feature name is null.");
return JNI_FALSE;
}
@@ -2022,22 +2033,21 @@
jboolean do_add,
jstring feature_name,
jstring address, jint length) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) {
- ALOGW("%s: sBluetoothInterface is null.", __func__);
+ log::warn("sBluetoothInterface is null.");
return;
}
if ((do_add == JNI_TRUE) && (length <= 0 || length > 6)) {
- ALOGE("%s: address length %d is invalid, valid length is [1,6]", __func__,
- length);
+ log::error("address length {} is invalid, valid length is [1,6]", length);
return;
}
const char* tmp_addr = env->GetStringUTFChars(address, NULL);
if (!tmp_addr) {
- ALOGW("%s: address is null.", __func__);
+ log::warn("address is null.");
return;
}
RawAddress bdaddr;
@@ -2046,13 +2056,13 @@
env->ReleaseStringUTFChars(address, tmp_addr);
if (!success) {
- ALOGW("%s: address is invalid.", __func__);
+ log::warn("address is invalid.");
return;
}
const char* feature_name_str = env->GetStringUTFChars(feature_name, NULL);
if (!feature_name_str) {
- ALOGW("%s: feature name is null.", __func__);
+ log::warn("feature name is null.");
return;
}
@@ -2066,22 +2076,22 @@
jboolean do_add,
jstring feature_name,
jstring name) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) {
- ALOGW("%s: sBluetoothInterface is null.", __func__);
+ log::warn("sBluetoothInterface is null.");
return;
}
const char* feature_name_str = env->GetStringUTFChars(feature_name, NULL);
if (!feature_name_str) {
- ALOGW("%s: feature name is null.", __func__);
+ log::warn("feature name is null.");
return;
}
const char* name_str = env->GetStringUTFChars(name, NULL);
if (!name_str) {
- ALOGW("%s: name is null.", __func__);
+ log::warn("name is null.");
env->ReleaseStringUTFChars(feature_name, feature_name_str);
return;
}
@@ -2095,13 +2105,13 @@
static int getRemotePbapPceVersionNative(JNIEnv* env, jobject /* obj */,
jstring address) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
const char* tmp_addr = env->GetStringUTFChars(address, NULL);
if (!tmp_addr) {
- ALOGW("%s: address is null.", __func__);
+ log::warn("address is null.");
return JNI_FALSE;
}
@@ -2111,7 +2121,7 @@
env->ReleaseStringUTFChars(address, tmp_addr);
if (!success) {
- ALOGW("%s: address is invalid.", __func__);
+ log::warn("address is invalid.");
return JNI_FALSE;
}
@@ -2120,7 +2130,7 @@
static jboolean pbapPseDynamicVersionUpgradeIsEnabledNative(JNIEnv* /* env */,
jobject /* obj */) {
- ALOGV("%s", __func__);
+ log::verbose("");
if (!sBluetoothInterface) return JNI_FALSE;
@@ -2243,11 +2253,11 @@
GET_JAVA_METHODS(env, "android/bluetooth/UidTraffic", javaUuidTrafficMethods);
if (env->GetJavaVM(&vm) != JNI_OK) {
- ALOGE("Could not get JavaVM");
+ log::error("Could not get JavaVM");
}
if (hal_util_load_bt_library((bt_interface_t const**)&sBluetoothInterface)) {
- ALOGE("No Bluetooth Library found");
+ log::error("No Bluetooth Library found");
}
return 0;
@@ -2262,120 +2272,120 @@
JNIEnv* e;
int status;
- ALOGV("Bluetooth Adapter Service : loading JNI\n");
+ log::verbose("Bluetooth Adapter Service : loading JNI\n");
// Check JNI version
if (jvm->GetEnv((void**)&e, JNI_VERSION_1_6)) {
- ALOGE("JNI version mismatch error");
+ log::error("JNI version mismatch error");
return JNI_ERR;
}
status = android::register_com_android_bluetooth_btservice_AdapterService(e);
if (status < 0) {
- ALOGE("jni adapter service registration failure, status: %d", status);
+ log::error("jni adapter service registration failure, status: {}", status);
return JNI_ERR;
}
status =
android::register_com_android_bluetooth_btservice_BluetoothKeystore(e);
if (status < 0) {
- ALOGE("jni BluetoothKeyStore registration failure: %d", status);
+ log::error("jni BluetoothKeyStore registration failure: {}", status);
return JNI_ERR;
}
status = android::register_com_android_bluetooth_hfp(e);
if (status < 0) {
- ALOGE("jni hfp registration failure, status: %d", status);
+ log::error("jni hfp registration failure, status: {}", status);
return JNI_ERR;
}
status = android::register_com_android_bluetooth_hfpclient(e);
if (status < 0) {
- ALOGE("jni hfp client registration failure, status: %d", status);
+ log::error("jni hfp client registration failure, status: {}", status);
return JNI_ERR;
}
status = android::register_com_android_bluetooth_a2dp(e);
if (status < 0) {
- ALOGE("jni a2dp source registration failure: %d", status);
+ log::error("jni a2dp source registration failure: {}", status);
return JNI_ERR;
}
status = android::register_com_android_bluetooth_a2dp_sink(e);
if (status < 0) {
- ALOGE("jni a2dp sink registration failure: %d", status);
+ log::error("jni a2dp sink registration failure: {}", status);
return JNI_ERR;
}
status = android::register_com_android_bluetooth_avrcp_target(e);
if (status < 0) {
- ALOGE("jni new avrcp target registration failure: %d", status);
+ log::error("jni new avrcp target registration failure: {}", status);
}
status = android::register_com_android_bluetooth_avrcp_controller(e);
if (status < 0) {
- ALOGE("jni avrcp controller registration failure: %d", status);
+ log::error("jni avrcp controller registration failure: {}", status);
return JNI_ERR;
}
status = android::register_com_android_bluetooth_hid_host(e);
if (status < 0) {
- ALOGE("jni hid registration failure: %d", status);
+ log::error("jni hid registration failure: {}", status);
return JNI_ERR;
}
status = android::register_com_android_bluetooth_hid_device(e);
if (status < 0) {
- ALOGE("jni hidd registration failure: %d", status);
+ log::error("jni hidd registration failure: {}", status);
return JNI_ERR;
}
status = android::register_com_android_bluetooth_pan(e);
if (status < 0) {
- ALOGE("jni pan registration failure: %d", status);
+ log::error("jni pan registration failure: {}", status);
return JNI_ERR;
}
status = android::register_com_android_bluetooth_gatt(e);
if (status < 0) {
- ALOGE("jni gatt registration failure: %d", status);
+ log::error("jni gatt registration failure: {}", status);
return JNI_ERR;
}
status = android::register_com_android_bluetooth_sdp(e);
if (status < 0) {
- ALOGE("jni sdp registration failure: %d", status);
+ log::error("jni sdp registration failure: {}", status);
return JNI_ERR;
}
status = android::register_com_android_bluetooth_hearing_aid(e);
if (status < 0) {
- ALOGE("jni hearing aid registration failure: %d", status);
+ log::error("jni hearing aid registration failure: {}", status);
return JNI_ERR;
}
status = android::register_com_android_bluetooth_hap_client(e);
if (status < 0) {
- ALOGE("jni le audio hearing access client registration failure: %d",
- status);
+ log::error("jni le audio hearing access client registration failure: {}",
+ status);
return JNI_ERR;
}
status = android::register_com_android_bluetooth_le_audio(e);
if (status < 0) {
- ALOGE("jni le_audio registration failure: %d", status);
+ log::error("jni le_audio registration failure: {}", status);
return JNI_ERR;
}
status = android::register_com_android_bluetooth_vc(e);
if (status < 0) {
- ALOGE("jni vc registration failure: %d", status);
+ log::error("jni vc registration failure: {}", status);
return JNI_ERR;
}
status = android::register_com_android_bluetooth_csip_set_coordinator(e);
if (status < 0) {
- ALOGE("jni csis client registration failure: %d", status);
+ log::error("jni csis client registration failure: {}", status);
return JNI_ERR;
}
@@ -2383,7 +2393,7 @@
android::register_com_android_bluetooth_btservice_BluetoothQualityReport(
e);
if (status < 0) {
- ALOGE("jni bluetooth quality report registration failure: %d", status);
+ log::error("jni bluetooth quality report registration failure: {}", status);
return JNI_ERR;
}
@@ -2397,8 +2407,8 @@
const JNIJavaMethod* methods, int nMethods) {
jclass clazz = env->FindClass(className);
if (clazz == nullptr) {
- LOG(FATAL) << "Native registration unable to find class '" << className
- << "'; aborting...";
+ log::fatal("Native registration unable to find class '{}' aborting...",
+ className);
}
for (int i = 0; i < nMethods; i++) {
@@ -2409,9 +2419,9 @@
*method.id = env->GetMethodID(clazz, method.name, method.signature);
}
if (method.id == nullptr) {
- LOG(FATAL) << "In class " << className << ": Unable to find '"
- << method.name << "' with signature=" << method.signature
- << " is_static=" << method.is_static;
+ log::fatal(
+ "In class {}: Unable to find '{}' with signature={} is_static={}",
+ className, method.name, method.signature, method.is_static);
}
}
diff --git a/android/app/jni/com_android_bluetooth_btservice_BluetoothKeystore.cpp b/android/app/jni/com_android_bluetooth_btservice_BluetoothKeystore.cpp
index 1c5e382..7d083cc 100644
--- a/android/app/jni/com_android_bluetooth_btservice_BluetoothKeystore.cpp
+++ b/android/app/jni/com_android_bluetooth_btservice_BluetoothKeystore.cpp
@@ -44,7 +44,7 @@
void set_encrypt_key_or_remove_key(
const std::string prefixString,
const std::string decryptedString) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -60,7 +60,7 @@
}
std::string get_key(const std::string prefixString) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -72,7 +72,7 @@
mCallbacksObj, method_getKeyCallback, j_prefixString);
if (j_decrypt_str == nullptr) {
- ALOGE("%s: Got a null decrypt_str", __func__);
+ log::error("Got a null decrypt_str");
return "";
}
@@ -92,32 +92,30 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == nullptr) {
- LOG(ERROR) << "Bluetooth module is not loaded";
+ log::error("Bluetooth module is not loaded");
return;
}
if (sBluetoothKeystoreInterface != nullptr) {
- LOG(INFO)
- << "Cleaning up BluetoothKeystore Interface before initializing...";
+ log::info("Cleaning up BluetoothKeystore Interface before initializing...");
sBluetoothKeystoreInterface = nullptr;
}
if (mCallbacksObj != nullptr) {
- LOG(INFO) << "Cleaning up BluetoothKeystore callback object";
+ log::info("Cleaning up BluetoothKeystore callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = nullptr;
}
if ((mCallbacksObj = env->NewGlobalRef(object)) == nullptr) {
- LOG(ERROR)
- << "Failed to allocate Global Ref for BluetoothKeystore Callbacks";
+ log::error("Failed to allocate Global Ref for BluetoothKeystore Callbacks");
return;
}
sBluetoothKeystoreInterface =
(BluetoothKeystoreInterface*)btInf->get_profile_interface(BT_KEYSTORE_ID);
if (sBluetoothKeystoreInterface == nullptr) {
- LOG(ERROR) << "Failed to get BluetoothKeystore Interface";
+ log::error("Failed to get BluetoothKeystore Interface");
return;
}
@@ -130,7 +128,7 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == nullptr) {
- LOG(ERROR) << "Bluetooth module is not loaded";
+ log::error("Bluetooth module is not loaded");
return;
}
diff --git a/android/app/jni/com_android_bluetooth_csip_set_coordinator.cpp b/android/app/jni/com_android_bluetooth_csip_set_coordinator.cpp
index bd24892..58f8c7f 100644
--- a/android/app/jni/com_android_bluetooth_csip_set_coordinator.cpp
+++ b/android/app/jni/com_android_bluetooth_csip_set_coordinator.cpp
@@ -75,8 +75,8 @@
void OnConnectionState(const RawAddress& bd_addr,
ConnectionState state) override {
- LOG(INFO) << __func__ << ", state:" << int(state)
- << ", addr: " << bd_addr.ToRedactedStringForLogging();
+ log::info("state:{}, addr: {}", int(state),
+ bd_addr.ToRedactedStringForLogging());
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -85,7 +85,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new bd addr jbyteArray for connection state";
+ log::error("Failed to new bd addr jbyteArray for connection state");
return;
}
@@ -105,7 +105,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new bd addr jbyteArray for device available";
+ log::error("Failed to new bd addr jbyteArray for device available");
return;
}
sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress),
@@ -117,7 +117,7 @@
}
void OnSetMemberAvailable(const RawAddress& bd_addr, int group_id) override {
- LOG(INFO) << __func__ << ", group id:" << group_id;
+ log::info("group id:{}", group_id);
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -126,7 +126,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new jbyteArray bd addr for connection state";
+ log::error("Failed to new jbyteArray bd addr for connection state");
return;
}
@@ -138,8 +138,8 @@
void OnGroupLockChanged(int group_id, bool locked,
CsisGroupLockStatus status) override {
- LOG(INFO) << __func__ << ", group_id: " << int(group_id)
- << ", locked: " << locked << ", status: " << (int)status;
+ log::info("group_id: {}, locked: {}, status: {}", group_id, locked,
+ (int)status);
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -159,31 +159,31 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == nullptr) {
- LOG(ERROR) << "Bluetooth module is not loaded";
+ log::error("Bluetooth module is not loaded");
return;
}
if (sCsisClientInterface != nullptr) {
- LOG(INFO) << "Cleaning up Csis Interface before initializing...";
+ log::info("Cleaning up Csis Interface before initializing...");
sCsisClientInterface->Cleanup();
sCsisClientInterface = nullptr;
}
if (mCallbacksObj != nullptr) {
- LOG(INFO) << "Cleaning up Csis callback object";
+ log::info("Cleaning up Csis callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = nullptr;
}
if ((mCallbacksObj = env->NewGlobalRef(object)) == nullptr) {
- LOG(ERROR) << "Failed to allocate Global Ref for Csis Client Callbacks";
+ log::error("Failed to allocate Global Ref for Csis Client Callbacks");
return;
}
sCsisClientInterface = (CsisClientInterface*)btInf->get_profile_interface(
BT_PROFILE_CSIS_CLIENT_ID);
if (sCsisClientInterface == nullptr) {
- LOG(ERROR) << "Failed to get Csis Client Interface";
+ log::error("Failed to get Csis Client Interface");
return;
}
@@ -196,7 +196,7 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == nullptr) {
- LOG(ERROR) << "Bluetooth module is not loaded";
+ log::error("Bluetooth module is not loaded");
return;
}
@@ -215,8 +215,7 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sCsisClientInterface) {
- LOG(ERROR) << __func__
- << ": Failed to get the Csis Client Interface Interface";
+ log::error("Failed to get the Csis Client Interface Interface");
return JNI_FALSE;
}
@@ -236,7 +235,7 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sCsisClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Csis Client Interface";
+ log::error("Failed to get the Csis Client Interface");
return JNI_FALSE;
}
@@ -254,11 +253,10 @@
static void groupLockSetNative(JNIEnv* /* env */, jobject /* object */,
jint group_id, jboolean lock) {
- LOG(INFO) << __func__;
+ log::info("");
if (!sCsisClientInterface) {
- LOG(ERROR) << __func__
- << ": Failed to get the Bluetooth Csis Client Interface";
+ log::error("Failed to get the Bluetooth Csis Client Interface");
return;
}
diff --git a/android/app/jni/com_android_bluetooth_gatt.cpp b/android/app/jni/com_android_bluetooth_gatt.cpp
index 8275150..0c611f8 100644
--- a/android/app/jni/com_android_bluetooth_gatt.cpp
+++ b/android/app/jni/com_android_bluetooth_gatt.cpp
@@ -33,15 +33,6 @@
#include "rust/src/gatt/ffi/gatt_shim.h"
#include "src/gatt/ffi.rs.h"
#include "utils/Log.h"
-#define info(fmt, ...) ALOGI("%s(L%d): " fmt, __func__, __LINE__, ##__VA_ARGS__)
-#define debug(fmt, ...) \
- ALOGD("%s(L%d): " fmt, __func__, __LINE__, ##__VA_ARGS__)
-#define warn(fmt, ...) \
- ALOGW("WARNING: %s(L%d): " fmt "##", __func__, __LINE__, ##__VA_ARGS__)
-#define error(fmt, ...) \
- ALOGE("ERROR: %s(L%d): " fmt "##", __func__, __LINE__, ##__VA_ARGS__)
-#define asrt(s) \
- if (!(s)) ALOGE("%s(L%d): ASSERT %s failed! ##", __func__, __LINE__, #s)
using bluetooth::Uuid;
@@ -1111,7 +1102,7 @@
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!mPeriodicScanCallbacksObj) {
- ALOGE("mPeriodicScanCallbacksObj is NULL. Return.");
+ log::error("mPeriodicScanCallbacksObj is NULL. Return.");
return;
}
ScopedLocalRef<jstring> addr(sCallbackEnv.get(),
@@ -1154,7 +1145,7 @@
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!mPeriodicScanCallbacksObj) {
- ALOGE("mPeriodicScanCallbacksObj is NULL. Return.");
+ log::error("mPeriodicScanCallbacksObj is NULL. Return.");
return;
}
ScopedLocalRef<jstring> addr(sCallbackEnv.get(),
@@ -1171,7 +1162,7 @@
if (!sCallbackEnv.valid()) return;
if (!mPeriodicScanCallbacksObj) {
- ALOGE("mPeriodicScanCallbacksObj is NULL. Return.");
+ log::error("mPeriodicScanCallbacksObj is NULL. Return.");
return;
}
sCallbackEnv->CallVoidMethod(mPeriodicScanCallbacksObj,
@@ -1247,18 +1238,18 @@
btIf = getBluetoothInterface();
if (btIf == NULL) {
- error("Bluetooth module is not loaded");
+ log::error("Bluetooth module is not loaded");
return;
}
if (sGattIf != NULL) {
- ALOGW("Cleaning up Bluetooth GATT Interface before initializing...");
+ log::warn("Cleaning up Bluetooth GATT Interface before initializing...");
sGattIf->cleanup();
sGattIf = NULL;
}
if (mCallbacksObj != NULL) {
- ALOGW("Cleaning up Bluetooth GATT callback object");
+ log::warn("Cleaning up Bluetooth GATT callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = NULL;
}
@@ -1266,13 +1257,14 @@
sGattIf =
(btgatt_interface_t*)btIf->get_profile_interface(BT_PROFILE_GATT_ID);
if (sGattIf == NULL) {
- error("Failed to get Bluetooth GATT Interface");
+ log::error("Failed to get Bluetooth GATT Interface");
return;
}
bt_status_t status = sGattIf->init(&sGattCallbacks);
if (status != BT_STATUS_SUCCESS) {
- error("Failed to initialize Bluetooth GATT, status: %d", status);
+ log::error("Failed to initialize Bluetooth GATT, status: {}",
+ bt_status_text(status));
sGattIf = NULL;
return;
}
@@ -1477,7 +1469,7 @@
if (!sGattIf) return;
if (value == NULL) {
- warn("gattClientWriteCharacteristicNative() ignoring NULL array");
+ log::warn("gattClientWriteCharacteristicNative() ignoring NULL array");
return;
}
@@ -1505,7 +1497,7 @@
if (!sGattIf) return;
if (value == NULL) {
- warn("gattClientWriteDescriptorNative() ignoring NULL array");
+ log::warn("gattClientWriteDescriptorNative() ignoring NULL array");
return;
}
@@ -1551,8 +1543,8 @@
jint scan_window_unit) {
if (!sGattIf) return;
sGattIf->scanner->SetScanParameters(
- client_if, scan_interval_unit, scan_window_unit,
- base::Bind(&set_scan_params_cmpl_cb, client_if));
+ client_if, /* use active scan */ 0x01, scan_interval_unit,
+ scan_window_unit, base::Bind(&set_scan_params_cmpl_cb, client_if));
}
void scan_filter_param_cb(uint8_t client_if, uint8_t avbl_space, uint8_t action,
@@ -1716,7 +1708,7 @@
int len = env->GetArrayLength(irkByteArray.get());
// IRK is 128 bits or 16 octets, set the bytes or zero it out
if (len != 16) {
- ALOGE("%s: Invalid IRK length '%d'; expected 16", __func__, len);
+ log::error("Invalid IRK length '{}'; expected 16", len);
jniThrowIOException(env, EINVAL);
return;
}
@@ -2139,7 +2131,7 @@
static void advertiseInitializeNative(JNIEnv* env, jobject object) {
std::unique_lock<std::shared_mutex> lock(callbacks_mutex);
if (mAdvertiseCallbacksObj != NULL) {
- ALOGW("Cleaning up Advertise callback object");
+ log::warn("Cleaning up Advertise callback object");
env->DeleteGlobalRef(mAdvertiseCallbacksObj);
mAdvertiseCallbacksObj = NULL;
}
@@ -2449,7 +2441,7 @@
static void periodicScanInitializeNative(JNIEnv* env, jobject object) {
std::unique_lock<std::shared_mutex> lock(callbacks_mutex);
if (mPeriodicScanCallbacksObj != NULL) {
- ALOGW("Cleaning up periodic scan callback object");
+ log::warn("Cleaning up periodic scan callback object");
env->DeleteGlobalRef(mPeriodicScanCallbacksObj);
mPeriodicScanCallbacksObj = NULL;
}
@@ -2524,7 +2516,7 @@
static void distanceMeasurementInitializeNative(JNIEnv* env, jobject object) {
std::unique_lock<std::shared_mutex> lock(callbacks_mutex);
if (mDistanceMeasurementCallbacksObj != NULL) {
- ALOGW("Cleaning up Advertise callback object");
+ log::warn("Cleaning up Advertise callback object");
env->DeleteGlobalRef(mDistanceMeasurementCallbacksObj);
mDistanceMeasurementCallbacksObj = NULL;
}
diff --git a/android/app/jni/com_android_bluetooth_hap_client.cpp b/android/app/jni/com_android_bluetooth_hap_client.cpp
index 067af34..148a6e2 100644
--- a/android/app/jni/com_android_bluetooth_hap_client.cpp
+++ b/android/app/jni/com_android_bluetooth_hap_client.cpp
@@ -73,7 +73,7 @@
void OnConnectionState(ConnectionState state,
const RawAddress& bd_addr) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -82,7 +82,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new bd addr jbyteArray for connection state";
+ log::error("Failed to new bd addr jbyteArray for connection state");
return;
}
@@ -100,7 +100,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new bd addr jbyteArray for device available";
+ log::error("Failed to new bd addr jbyteArray for device available");
return;
}
sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress),
@@ -118,7 +118,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new bd addr jbyteArray for device available";
+ log::error("Failed to new bd addr jbyteArray for device available");
return;
}
sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress),
@@ -138,7 +138,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new bd addr jbyteArray for preset selected";
+ log::error("Failed to new bd addr jbyteArray for preset selected");
return;
}
sCallbackEnv->SetByteArrayRegion(
@@ -164,8 +164,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR)
- << "Failed to new bd addr jbyteArray for preset select error";
+ log::error("Failed to new bd addr jbyteArray for preset select error");
return;
}
sCallbackEnv->SetByteArrayRegion(
@@ -198,14 +197,14 @@
for (auto const& info : detail_records) {
const char* name = info.preset_name.c_str();
if (!sCallbackEnv.isValidUtf(name)) {
- ALOGE("%s: name is not a valid UTF string.", __func__);
+ log::error("name is not a valid UTF string.");
name = null_str;
}
ScopedLocalRef<jstring> name_str(sCallbackEnv.get(),
sCallbackEnv->NewStringUTF(name));
if (!name_str.get()) {
- LOG(ERROR) << "Failed to new preset name String for preset name";
+ log::error("Failed to new preset name String for preset name");
return;
}
@@ -222,7 +221,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new bd addr jbyteArray for preset name";
+ log::error("Failed to new bd addr jbyteArray for preset name");
return;
}
sCallbackEnv->SetByteArrayRegion(
@@ -250,8 +249,8 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR)
- << "Failed to new bd addr jbyteArray for preset name get error";
+ log::error(
+ "Failed to new bd addr jbyteArray for preset name get error");
return;
}
sCallbackEnv->SetByteArrayRegion(
@@ -279,8 +278,8 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR)
- << "Failed to new bd addr jbyteArray for preset name set error";
+ log::error(
+ "Failed to new bd addr jbyteArray for preset name set error");
return;
}
sCallbackEnv->SetByteArrayRegion(
@@ -307,40 +306,40 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == nullptr) {
- LOG(ERROR) << "Bluetooth module is not loaded";
+ log::error("Bluetooth module is not loaded");
return;
}
if (sHasClientInterface != nullptr) {
- LOG(INFO) << "Cleaning up HearingAid Interface before initializing...";
+ log::info("Cleaning up HearingAid Interface before initializing...");
sHasClientInterface->Cleanup();
sHasClientInterface = nullptr;
}
if (mCallbacksObj != nullptr) {
- LOG(INFO) << "Cleaning up HearingAid callback object";
+ log::info("Cleaning up HearingAid callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = nullptr;
}
if ((mCallbacksObj = env->NewGlobalRef(object)) == nullptr) {
- LOG(ERROR) << "Failed to allocate Global Ref for Hearing Access Callbacks";
+ log::error("Failed to allocate Global Ref for Hearing Access Callbacks");
return;
}
android_bluetooth_BluetoothHapPresetInfo.clazz = (jclass)env->NewGlobalRef(
env->FindClass("android/bluetooth/BluetoothHapPresetInfo"));
if (android_bluetooth_BluetoothHapPresetInfo.clazz == nullptr) {
- ALOGE("%s: Failed to allocate Global Ref for BluetoothHapPresetInfo class",
- __func__);
+ log::error(
+ "Failed to allocate Global Ref for BluetoothHapPresetInfo class");
return;
}
sHasClientInterface = (HasClientInterface*)btInf->get_profile_interface(
BT_PROFILE_HAP_CLIENT_ID);
if (sHasClientInterface == nullptr) {
- LOG(ERROR)
- << "Failed to get Bluetooth Hearing Access Service Client Interface";
+ log::error(
+ "Failed to get Bluetooth Hearing Access Service Client Interface");
return;
}
@@ -353,7 +352,7 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == nullptr) {
- LOG(ERROR) << "Bluetooth module is not loaded";
+ log::error("Bluetooth module is not loaded");
return;
}
@@ -372,7 +371,7 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sHasClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Bluetooth HAP Interface";
+ log::error("Failed to get the Bluetooth HAP Interface");
return JNI_FALSE;
}
@@ -392,7 +391,7 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sHasClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Bluetooth HAP Interface";
+ log::error("Failed to get the Bluetooth HAP Interface");
return JNI_FALSE;
}
@@ -412,7 +411,7 @@
jbyteArray address, jint preset_index) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sHasClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Bluetooth HAP Interface";
+ log::error("Failed to get the Bluetooth HAP Interface");
return;
}
@@ -432,7 +431,7 @@
jint preset_index) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sHasClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Bluetooth HAP Interface";
+ log::error("Failed to get the Bluetooth HAP Interface");
return;
}
@@ -443,7 +442,7 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sHasClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Bluetooth HAP Interface";
+ log::error("Failed to get the Bluetooth HAP Interface");
return;
}
@@ -462,7 +461,7 @@
jint group_id) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sHasClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Bluetooth HAP Interface";
+ log::error("Failed to get the Bluetooth HAP Interface");
return;
}
@@ -473,7 +472,7 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sHasClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Bluetooth HAP Interface";
+ log::error("Failed to get the Bluetooth HAP Interface");
return;
}
@@ -493,7 +492,7 @@
jint group_id) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sHasClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Bluetooth HAP Interface";
+ log::error("Failed to get the Bluetooth HAP Interface");
return;
}
@@ -504,7 +503,7 @@
jbyteArray address, jint preset_index) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sHasClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Bluetooth HAP Interface";
+ log::error("Failed to get the Bluetooth HAP Interface");
return;
}
@@ -524,7 +523,7 @@
jstring name) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sHasClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Bluetooth HAP Interface";
+ log::error("Failed to get the Bluetooth HAP Interface");
return;
}
@@ -552,7 +551,7 @@
jstring name) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sHasClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Bluetooth HAP Interface";
+ log::error("Failed to get the Bluetooth HAP Interface");
return;
}
diff --git a/android/app/jni/com_android_bluetooth_hearing_aid.cpp b/android/app/jni/com_android_bluetooth_hearing_aid.cpp
index 648ff8d..6ccee32 100644
--- a/android/app/jni/com_android_bluetooth_hearing_aid.cpp
+++ b/android/app/jni/com_android_bluetooth_hearing_aid.cpp
@@ -42,7 +42,7 @@
~HearingAidCallbacksImpl() = default;
void OnConnectionState(ConnectionState state,
const RawAddress& bd_addr) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -51,7 +51,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new jbyteArray bd addr for connection state";
+ log::error("Failed to new jbyteArray bd addr for connection state");
return;
}
@@ -63,8 +63,7 @@
void OnDeviceAvailable(uint8_t capabilities, uint64_t hi_sync_id,
const RawAddress& bd_addr) override {
- LOG(INFO) << __func__ << ": capabilities=" << +capabilities
- << " hi_sync_id=" << hi_sync_id;
+ log::info("capabilities={} hi_sync_id={}", +capabilities, hi_sync_id);
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -73,7 +72,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new jbyteArray bd addr for connection state";
+ log::error("Failed to new jbyteArray bd addr for connection state");
return;
}
@@ -93,31 +92,31 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == nullptr) {
- LOG(ERROR) << "Bluetooth module is not loaded";
+ log::error("Bluetooth module is not loaded");
return;
}
if (sHearingAidInterface != nullptr) {
- LOG(INFO) << "Cleaning up HearingAid Interface before initializing...";
+ log::info("Cleaning up HearingAid Interface before initializing...");
sHearingAidInterface->Cleanup();
sHearingAidInterface = nullptr;
}
if (mCallbacksObj != nullptr) {
- LOG(INFO) << "Cleaning up HearingAid callback object";
+ log::info("Cleaning up HearingAid callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = nullptr;
}
if ((mCallbacksObj = env->NewGlobalRef(object)) == nullptr) {
- LOG(ERROR) << "Failed to allocate Global Ref for Hearing Aid Callbacks";
+ log::error("Failed to allocate Global Ref for Hearing Aid Callbacks");
return;
}
sHearingAidInterface = (HearingAidInterface*)btInf->get_profile_interface(
BT_PROFILE_HEARING_AID_ID);
if (sHearingAidInterface == nullptr) {
- LOG(ERROR) << "Failed to get Bluetooth Hearing Aid Interface";
+ log::error("Failed to get Bluetooth Hearing Aid Interface");
return;
}
@@ -130,7 +129,7 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == nullptr) {
- LOG(ERROR) << "Bluetooth module is not loaded";
+ log::error("Bluetooth module is not loaded");
return;
}
@@ -147,7 +146,7 @@
static jboolean connectHearingAidNative(JNIEnv* env, jobject /* object */,
jbyteArray address) {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sHearingAidInterface) return JNI_FALSE;
@@ -165,7 +164,7 @@
static jboolean disconnectHearingAidNative(JNIEnv* env, jobject /* object */,
jbyteArray address) {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sHearingAidInterface) return JNI_FALSE;
@@ -200,8 +199,7 @@
static void setVolumeNative(JNIEnv* /* env */, jclass /* clazz */,
jint volume) {
if (!sHearingAidInterface) {
- LOG(ERROR) << __func__
- << ": Failed to get the Bluetooth Hearing Aid Interface";
+ log::error("Failed to get the Bluetooth Hearing Aid Interface");
return;
}
sHearingAidInterface->SetVolume(volume);
diff --git a/android/app/jni/com_android_bluetooth_hfp.cpp b/android/app/jni/com_android_bluetooth_hfp.cpp
index d33669f..beea022 100644
--- a/android/app/jni/com_android_bluetooth_hfp.cpp
+++ b/android/app/jni/com_android_bluetooth_hfp.cpp
@@ -61,7 +61,7 @@
jbyteArray addr = sCallbackEnv->NewByteArray(sizeof(RawAddress));
if (!addr) {
- ALOGE("Fail to new jbyteArray bd addr");
+ log::error("Fail to new jbyteArray bd addr");
return nullptr;
}
sCallbackEnv->SetByteArrayRegion(addr, 0, sizeof(RawAddress),
@@ -79,7 +79,7 @@
void ConnectionStateCallback(
bluetooth::headset::bthf_connection_state_t state,
RawAddress* bd_addr) override {
- ALOGI("%s %d for %s", __func__, state, ADDRESS_TO_LOGGABLE_CSTR(*bd_addr));
+ log::info("{} for {}", state, ADDRESS_TO_LOGGABLE_CSTR(*bd_addr));
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -94,7 +94,7 @@
void AudioStateCallback(bluetooth::headset::bthf_audio_state_t state,
RawAddress* bd_addr) override {
- ALOGI("%s, %d for %s", __func__, state, ADDRESS_TO_LOGGABLE_CSTR(*bd_addr));
+ log::info("{} for {}", state, ADDRESS_TO_LOGGABLE_CSTR(*bd_addr));
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -115,7 +115,7 @@
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for audio state");
+ log::error("Fail to new jbyteArray bd addr for audio state");
return;
}
@@ -130,7 +130,7 @@
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for audio state");
+ log::error("Fail to new jbyteArray bd addr for audio state");
return;
}
@@ -145,7 +145,7 @@
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for audio state");
+ log::error("Fail to new jbyteArray bd addr for audio state");
return;
}
@@ -161,7 +161,7 @@
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for audio state");
+ log::error("Fail to new jbyteArray bd addr for audio state");
return;
}
@@ -176,13 +176,13 @@
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for audio state");
+ log::error("Fail to new jbyteArray bd addr for audio state");
return;
}
char null_str[] = "";
if (!sCallbackEnv.isValidUtf(number)) {
- ALOGE("%s: number is not a valid UTF string.", __func__);
+ log::error("number is not a valid UTF string.");
number = null_str;
}
@@ -199,7 +199,7 @@
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for audio state");
+ log::error("Fail to new jbyteArray bd addr for audio state");
return;
}
@@ -216,7 +216,7 @@
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for audio state");
+ log::error("Fail to new jbyteArray bd addr for audio state");
return;
}
sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onNoiseReductionEnable,
@@ -260,7 +260,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for audio state");
+ log::error("Fail to new jbyteArray bd addr for audio state");
return;
}
@@ -277,7 +277,7 @@
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for audio state");
+ log::error("Fail to new jbyteArray bd addr for audio state");
return;
}
@@ -291,7 +291,7 @@
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for audio state");
+ log::error("Fail to new jbyteArray bd addr for audio state");
return;
}
@@ -305,7 +305,7 @@
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for audio state");
+ log::error("Fail to new jbyteArray bd addr for audio state");
return;
}
@@ -319,7 +319,7 @@
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for audio state");
+ log::error("Fail to new jbyteArray bd addr for audio state");
return;
}
@@ -333,13 +333,13 @@
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for audio state");
+ log::error("Fail to new jbyteArray bd addr for audio state");
return;
}
char null_str[] = "";
if (!sCallbackEnv.isValidUtf(at_string)) {
- ALOGE("%s: at_string is not a valid UTF string.", __func__);
+ log::error("at_string is not a valid UTF string.");
at_string = null_str;
}
@@ -356,7 +356,7 @@
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for audio state");
+ log::error("Fail to new jbyteArray bd addr for audio state");
return;
}
@@ -374,7 +374,7 @@
char null_str[] = "";
if (!sCallbackEnv.isValidUtf(at_string)) {
- ALOGE("%s: at_string is not a valid UTF string.", __func__);
+ log::error("at_string is not a valid UTF string.");
at_string = null_str;
}
@@ -417,7 +417,7 @@
uint64_t /* end_ts */,
const char* /* pkt_status_in_hex */,
const char* /* pkt_status_in_binary */) override {
- ALOGE("Not implemented and shouldn't be called");
+ log::error("Not implemented and shouldn't be called");
}
};
@@ -428,20 +428,19 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (!btInf) {
- ALOGE("%s: Bluetooth module is not loaded", __func__);
+ log::error("Bluetooth module is not loaded");
jniThrowIOException(env, EINVAL);
return;
}
if (sBluetoothHfpInterface) {
- ALOGI("%s: Cleaning up Bluetooth Handsfree Interface before initializing",
- __func__);
+ log::info("Cleaning up Bluetooth Handsfree Interface before initializing");
sBluetoothHfpInterface->Cleanup();
sBluetoothHfpInterface = nullptr;
}
if (mCallbacksObj) {
- ALOGI("%s: Cleaning up Bluetooth Handsfree callback object", __func__);
+ log::info("Cleaning up Bluetooth Handsfree callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = nullptr;
}
@@ -450,7 +449,7 @@
(bluetooth::headset::Interface*)btInf->get_profile_interface(
BT_PROFILE_HANDSFREE_ID);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: Failed to get Bluetooth Handsfree Interface", __func__);
+ log::warn("Failed to get Bluetooth Handsfree Interface");
jniThrowIOException(env, EINVAL);
return;
}
@@ -458,8 +457,8 @@
sBluetoothHfpInterface->Init(JniHeadsetCallbacks::GetInstance(),
max_hf_clients, inband_ringing_enabled);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("%s: Failed to initialize Bluetooth Handsfree Interface, status: %d",
- __func__, status);
+ log::error("Failed to initialize Bluetooth Handsfree Interface, status: {}",
+ bt_status_text(status));
sBluetoothHfpInterface = nullptr;
return;
}
@@ -473,18 +472,18 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (!btInf) {
- ALOGW("%s: Bluetooth module is not loaded", __func__);
+ log::warn("Bluetooth module is not loaded");
return;
}
if (sBluetoothHfpInterface) {
- ALOGI("%s: Cleaning up Bluetooth Handsfree Interface", __func__);
+ log::info("Cleaning up Bluetooth Handsfree Interface");
sBluetoothHfpInterface->Cleanup();
sBluetoothHfpInterface = nullptr;
}
if (mCallbacksObj) {
- ALOGI("%s: Cleaning up Bluetooth Handsfree callback object", __func__);
+ log::info("Cleaning up Bluetooth Handsfree callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = nullptr;
}
@@ -494,20 +493,19 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: sBluetoothHfpInterface is null", __func__);
+ log::warn("sBluetoothHfpInterface is null");
return JNI_FALSE;
}
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (!addr) {
- ALOGE("%s: failed to get device address", __func__);
+ log::error("failed to get device address");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
- ALOGI("%s: device %s", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(*((RawAddress*)addr)));
+ log::info("device {}", ADDRESS_TO_LOGGABLE_CSTR(*((RawAddress*)addr)));
bt_status_t status = sBluetoothHfpInterface->Connect((RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed HF connection, status: %d", status);
+ log::error("Failed HF connection, status: {}", bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -517,20 +515,19 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: sBluetoothHfpInterface is null", __func__);
+ log::warn("sBluetoothHfpInterface is null");
return JNI_FALSE;
}
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (!addr) {
- ALOGE("%s: failed to get device address", __func__);
+ log::error("failed to get device address");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
- ALOGI("%s: device %s", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(*((RawAddress*)addr)));
+ log::info("device {}", ADDRESS_TO_LOGGABLE_CSTR(*((RawAddress*)addr)));
bt_status_t status = sBluetoothHfpInterface->Disconnect((RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed HF disconnection, status: %d", status);
+ log::error("Failed HF disconnection, status: {}", bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -540,21 +537,21 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: sBluetoothHfpInterface is null", __func__);
+ log::warn("sBluetoothHfpInterface is null");
return JNI_FALSE;
}
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (!addr) {
- ALOGE("%s: failed to get device address", __func__);
+ log::error("failed to get device address");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
- ALOGI("%s: device %s", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(*((RawAddress*)addr)));
+ log::info("device {}", ADDRESS_TO_LOGGABLE_CSTR(*((RawAddress*)addr)));
bt_status_t status =
sBluetoothHfpInterface->ConnectAudio((RawAddress*)addr, 0);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed HF audio connection, status: %d", status);
+ log::error("Failed HF audio connection, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -564,21 +561,21 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: sBluetoothHfpInterface is null", __func__);
+ log::warn("sBluetoothHfpInterface is null");
return JNI_FALSE;
}
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (!addr) {
- ALOGE("%s: failed to get device address", __func__);
+ log::error("failed to get device address");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
- ALOGI("%s: device %s", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(*((RawAddress*)addr)));
+ log::info("device {}", ADDRESS_TO_LOGGABLE_CSTR(*((RawAddress*)addr)));
bt_status_t status =
sBluetoothHfpInterface->DisconnectAudio((RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed HF audio disconnection, status: %d", status);
+ log::error("Failed HF audio disconnection, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -589,12 +586,12 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: sBluetoothHfpInterface is null", __func__);
+ log::warn("sBluetoothHfpInterface is null");
return JNI_FALSE;
}
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (!addr) {
- ALOGE("%s: failed to get device address", __func__);
+ log::error("failed to get device address");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
@@ -609,12 +606,12 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: sBluetoothHfpInterface is null", __func__);
+ log::warn("sBluetoothHfpInterface is null");
return JNI_FALSE;
}
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (!addr) {
- ALOGE("%s: failed to get device address", __func__);
+ log::error("failed to get device address");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
@@ -628,19 +625,20 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: sBluetoothHfpInterface is null", __func__);
+ log::warn("sBluetoothHfpInterface is null");
return JNI_FALSE;
}
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (!addr) {
- ALOGE("%s: failed to get device address", __func__);
+ log::error("failed to get device address");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
bt_status_t status =
sBluetoothHfpInterface->StartVoiceRecognition((RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed to start voice recognition, status: %d", status);
+ log::error("Failed to start voice recognition, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -650,19 +648,20 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: sBluetoothHfpInterface is null", __func__);
+ log::warn("sBluetoothHfpInterface is null");
return JNI_FALSE;
}
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (!addr) {
- ALOGE("%s: failed to get device address", __func__);
+ log::error("failed to get device address");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
bt_status_t status =
sBluetoothHfpInterface->StopVoiceRecognition((RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed to stop voice recognition, status: %d", status);
+ log::error("Failed to stop voice recognition, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -673,12 +672,12 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: sBluetoothHfpInterface is null", __func__);
+ log::warn("sBluetoothHfpInterface is null");
return JNI_FALSE;
}
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (!addr) {
- ALOGE("%s: failed to get device address", __func__);
+ log::error("failed to get device address");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
@@ -686,7 +685,7 @@
(bluetooth::headset::bthf_volume_type_t)volume_type, volume,
(RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("FAILED to control volume, status: %d", status);
+ log::error("FAILED to control volume, status: {}", bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -698,12 +697,12 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: sBluetoothHfpInterface is null", __func__);
+ log::warn("sBluetoothHfpInterface is null");
return JNI_FALSE;
}
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (!addr) {
- ALOGE("%s: failed to get device address", __func__);
+ log::error("failed to get device address");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
@@ -713,7 +712,8 @@
battery_charge, (RawAddress*)addr);
env->ReleaseByteArrayElements(address, addr, 0);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("FAILED to notify device status, status: %d", status);
+ log::error("FAILED to notify device status, status: {}",
+ bt_status_text(status));
}
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
}
@@ -722,12 +722,12 @@
jstring operator_str, jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: sBluetoothHfpInterface is null", __func__);
+ log::warn("sBluetoothHfpInterface is null");
return JNI_FALSE;
}
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (!addr) {
- ALOGE("%s: failed to get device address", __func__);
+ log::error("failed to get device address");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
@@ -735,7 +735,8 @@
bt_status_t status =
sBluetoothHfpInterface->CopsResponse(operator_name, (RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed sending cops response, status: %d", status);
+ log::error("Failed sending cops response, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
env->ReleaseStringUTFChars(operator_str, operator_name);
@@ -748,12 +749,12 @@
jint battery_charge, jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: sBluetoothHfpInterface is null", __func__);
+ log::warn("sBluetoothHfpInterface is null");
return JNI_FALSE;
}
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (!addr) {
- ALOGE("%s: failed to get device address", __func__);
+ log::error("failed to get device address");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
@@ -762,7 +763,7 @@
(bluetooth::headset::bthf_call_state_t)call_state, signal, roam,
battery_charge, (RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("%s: failed, status: %d", __func__, status);
+ log::error("failed, status: {}", bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -773,12 +774,12 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: sBluetoothHfpInterface is null", __func__);
+ log::warn("sBluetoothHfpInterface is null");
return JNI_FALSE;
}
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (!addr) {
- ALOGE("%s: failed to get device address", __func__);
+ log::error("failed to get device address");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
@@ -786,7 +787,8 @@
bt_status_t status =
sBluetoothHfpInterface->FormattedAtResponse(response, (RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed formatted AT response, status: %d", status);
+ log::error("Failed formatted AT response, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
env->ReleaseStringUTFChars(response_str, response);
@@ -798,12 +800,12 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: sBluetoothHfpInterface is null", __func__);
+ log::warn("sBluetoothHfpInterface is null");
return JNI_FALSE;
}
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (!addr) {
- ALOGE("%s: failed to get device address", __func__);
+ log::error("failed to get device address");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
@@ -811,7 +813,7 @@
(bluetooth::headset::bthf_at_response_t)response_code, cmee_code,
(RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed AT response, status: %d", status);
+ log::error("Failed AT response, status: {}", bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -823,12 +825,12 @@
jint type, jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: sBluetoothHfpInterface is null", __func__);
+ log::warn("sBluetoothHfpInterface is null");
return JNI_FALSE;
}
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (!addr) {
- ALOGE("%s: failed to get device address", __func__);
+ log::error("failed to get device address");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
@@ -845,7 +847,8 @@
number, (bluetooth::headset::bthf_call_addrtype_t)type,
(RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed sending CLCC response, status: %d", status);
+ log::error("Failed sending CLCC response, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
if (number) {
@@ -861,12 +864,12 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: sBluetoothHfpInterface is null", __func__);
+ log::warn("sBluetoothHfpInterface is null");
return JNI_FALSE;
}
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (!addr) {
- ALOGE("%s: failed to get device address", __func__);
+ log::error("failed to get device address");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
@@ -880,7 +883,8 @@
number, (bluetooth::headset::bthf_call_addrtype_t)type, name,
(RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed report phone state change, status: %d", status);
+ log::error("Failed report phone state change, status: {}",
+ bt_status_text(status));
}
env->ReleaseStringUTFChars(number_str, number);
if (name != nullptr) {
@@ -894,12 +898,12 @@
jboolean value) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: sBluetoothHfpInterface is null", __func__);
+ log::warn("sBluetoothHfpInterface is null");
return JNI_FALSE;
}
bt_status_t status = sBluetoothHfpInterface->SetScoAllowed(value == JNI_TRUE);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed HF set sco allowed, status: %d", status);
+ log::error("Failed HF set sco allowed, status: {}", bt_status_text(status));
}
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
}
@@ -908,19 +912,20 @@
jboolean value, jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: sBluetoothHfpInterface is null", __func__);
+ log::warn("sBluetoothHfpInterface is null");
return JNI_FALSE;
}
jbyte* addr = env->GetByteArrayElements(address, NULL);
if (!addr) {
- ALOGE("%s: failed to get device address", __func__);
+ log::error("failed to get device address");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
bt_status_t status =
sBluetoothHfpInterface->SendBsir(value == JNI_TRUE, (RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed sending BSIR, value=%d, status=%d", value, status);
+ log::error("Failed sending BSIR, value={}, status={}", value,
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -930,19 +935,20 @@
jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sBluetoothHfpInterface) {
- ALOGW("%s: sBluetoothHfpInterface is null", __func__);
+ log::warn("sBluetoothHfpInterface is null");
return JNI_FALSE;
}
jbyte* addr = env->GetByteArrayElements(address, NULL);
if (!addr) {
- ALOGE("%s: failed to get device address", __func__);
+ log::error("failed to get device address");
jniThrowIOException(env, EINVAL);
return JNI_FALSE;
}
bt_status_t status =
sBluetoothHfpInterface->SetActiveDevice((RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed to set active device, status: %d", status);
+ log::error("Failed to set active device, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
diff --git a/android/app/jni/com_android_bluetooth_hfpclient.cpp b/android/app/jni/com_android_bluetooth_hfpclient.cpp
index b5d5910..f51255b 100644
--- a/android/app/jni/com_android_bluetooth_hfpclient.cpp
+++ b/android/app/jni/com_android_bluetooth_hfpclient.cpp
@@ -17,11 +17,11 @@
#define LOG_TAG "BluetoothHeadsetClientServiceJni"
+#include <shared_mutex>
+
#include "com_android_bluetooth.h"
#include "hardware/bt_hf_client.h"
-#include "utils/Log.h"
-
-#include <shared_mutex>
+#include "os/logging/log_adapter.h"
namespace android {
@@ -60,7 +60,7 @@
jbyteArray addr = sCallbackEnv->NewByteArray(sizeof(RawAddress));
if (!addr) {
- ALOGE("Fail to new jbyteArray bd addr");
+ log::error("Fail to new jbyteArray bd addr");
return NULL;
}
sCallbackEnv->SetByteArrayRegion(addr, 0, sizeof(RawAddress),
@@ -79,7 +79,7 @@
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) return;
- ALOGD("%s: state %d peer_feat %d chld_feat %d", __func__, state, peer_feat, chld_feat);
+ log::debug("state {} peer_feat {} chld_feat {}", state, peer_feat, chld_feat);
sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectionStateChanged,
(jint)state, (jint)peer_feat, (jint)chld_feat,
addr.get());
@@ -170,7 +170,7 @@
const char null_str[] = "";
if (!sCallbackEnv.isValidUtf(name)) {
- ALOGE("%s: name is not a valid UTF string.", __func__);
+ log::error("name is not a valid UTF string.");
name = null_str;
}
@@ -201,9 +201,7 @@
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) return;
- ALOGD("callsetup_cb bdaddr %02x:%02x:%02x:%02x:%02x:%02x",
- bd_addr->address[0], bd_addr->address[1], bd_addr->address[2],
- bd_addr->address[3], bd_addr->address[4], bd_addr->address[5]);
+ log::debug("callsetup_cb bdaddr {}", ADDRESS_TO_LOGGABLE_STR(*bd_addr));
sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onCallSetup,
(jint)callsetup, addr.get());
@@ -245,7 +243,7 @@
const char null_str[] = "";
if (!sCallbackEnv.isValidUtf(number)) {
- ALOGE("%s: number is not a valid UTF string.", __func__);
+ log::error("number is not a valid UTF string.");
number = null_str;
}
@@ -265,7 +263,7 @@
const char null_str[] = "";
if (!sCallbackEnv.isValidUtf(number)) {
- ALOGE("%s: number is not a valid UTF string.", __func__);
+ log::error("number is not a valid UTF string.");
number = null_str;
}
@@ -289,7 +287,7 @@
const char null_str[] = "";
if (!sCallbackEnv.isValidUtf(number)) {
- ALOGE("%s: number is not a valid UTF string.", __func__);
+ log::error("number is not a valid UTF string.");
number = null_str;
}
@@ -334,7 +332,7 @@
const char null_str[] = "";
if (!sCallbackEnv.isValidUtf(name)) {
- ALOGE("%s: name is not a valid UTF string.", __func__);
+ log::error("name is not a valid UTF string.");
name = null_str;
}
@@ -367,7 +365,7 @@
const char null_str[] = "";
if (!sCallbackEnv.isValidUtf(number)) {
- ALOGE("%s: number is not a valid UTF string.", __func__);
+ log::error("number is not a valid UTF string.");
number = null_str;
}
@@ -430,24 +428,24 @@
};
static void initializeNative(JNIEnv* env, jobject object) {
- ALOGD("%s: HfpClient", __func__);
+ log::debug("HfpClient");
std::unique_lock<std::shared_mutex> interface_lock(interface_mutex);
std::unique_lock<std::shared_mutex> callbacks_lock(callbacks_mutex);
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == NULL) {
- ALOGE("Bluetooth module is not loaded");
+ log::error("Bluetooth module is not loaded");
return;
}
if (sBluetoothHfpClientInterface != NULL) {
- ALOGW("Cleaning up Bluetooth HFP Client Interface before initializing");
+ log::warn("Cleaning up Bluetooth HFP Client Interface before initializing");
sBluetoothHfpClientInterface->cleanup();
sBluetoothHfpClientInterface = NULL;
}
if (mCallbacksObj != NULL) {
- ALOGW("Cleaning up Bluetooth HFP Client callback object");
+ log::warn("Cleaning up Bluetooth HFP Client callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = NULL;
}
@@ -456,14 +454,15 @@
(bthf_client_interface_t*)btInf->get_profile_interface(
BT_PROFILE_HANDSFREE_CLIENT_ID);
if (sBluetoothHfpClientInterface == NULL) {
- ALOGE("Failed to get Bluetooth HFP Client Interface");
+ log::error("Failed to get Bluetooth HFP Client Interface");
return;
}
bt_status_t status =
sBluetoothHfpClientInterface->init(&sBluetoothHfpClientCallbacks);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed to initialize Bluetooth HFP Client, status: %d", status);
+ log::error("Failed to initialize Bluetooth HFP Client, status: {}",
+ bt_status_text(status));
sBluetoothHfpClientInterface = NULL;
return;
}
@@ -477,18 +476,18 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == NULL) {
- ALOGE("Bluetooth module is not loaded");
+ log::error("Bluetooth module is not loaded");
return;
}
if (sBluetoothHfpClientInterface != NULL) {
- ALOGW("Cleaning up Bluetooth HFP Client Interface...");
+ log::warn("Cleaning up Bluetooth HFP Client Interface...");
sBluetoothHfpClientInterface->cleanup();
sBluetoothHfpClientInterface = NULL;
}
if (mCallbacksObj != NULL) {
- ALOGW("Cleaning up Bluetooth HFP Client callback object");
+ log::warn("Cleaning up Bluetooth HFP Client callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = NULL;
}
@@ -508,7 +507,7 @@
bt_status_t status =
sBluetoothHfpClientInterface->connect((const RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed AG connection, status: %d", status);
+ log::error("Failed AG connection, status: {}", bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -528,7 +527,7 @@
bt_status_t status =
sBluetoothHfpClientInterface->disconnect((const RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed AG disconnection, status: %d", status);
+ log::error("Failed AG disconnection, status: {}", bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -548,7 +547,8 @@
bt_status_t status =
sBluetoothHfpClientInterface->connect_audio((const RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed AG audio connection, status: %d", status);
+ log::error("Failed AG audio connection, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -568,7 +568,8 @@
bt_status_t status =
sBluetoothHfpClientInterface->disconnect_audio((const RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed AG audio disconnection, status: %d", status);
+ log::error("Failed AG audio disconnection, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -588,7 +589,8 @@
bt_status_t status = sBluetoothHfpClientInterface->start_voice_recognition(
(const RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed to start voice recognition, status: %d", status);
+ log::error("Failed to start voice recognition, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -608,7 +610,8 @@
bt_status_t status = sBluetoothHfpClientInterface->stop_voice_recognition(
(const RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed to stop voice recognition, status: %d", status);
+ log::error("Failed to stop voice recognition, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -629,7 +632,7 @@
bt_status_t status = sBluetoothHfpClientInterface->volume_control(
(const RawAddress*)addr, (bthf_client_volume_type_t)volume_type, volume);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("FAILED to control volume, status: %d", status);
+ log::error("FAILED to control volume, status: {}", bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -655,7 +658,7 @@
number == nullptr ? "" : number);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed to dial, status: %d", status);
+ log::error("Failed to dial, status: {}", bt_status_text(status));
}
if (number != nullptr) {
env->ReleaseStringUTFChars(number_str, number);
@@ -678,7 +681,8 @@
bt_status_t status = sBluetoothHfpClientInterface->dial_memory(
(const RawAddress*)addr, (int)location);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed to dial from memory, status: %d", status);
+ log::error("Failed to dial from memory, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
@@ -701,7 +705,8 @@
(const RawAddress*)addr, (bthf_client_call_action_t)action, (int)index);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed to enter private mode, status: %d", status);
+ log::error("Failed to enter private mode, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -722,7 +727,8 @@
(const RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed to query current calls, status: %d", status);
+ log::error("Failed to query current calls, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
@@ -744,7 +750,8 @@
sBluetoothHfpClientInterface->query_current_operator_name(
(const RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed to query current operator name, status: %d", status);
+ log::error("Failed to query current operator name, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
@@ -765,7 +772,8 @@
bt_status_t status = sBluetoothHfpClientInterface->retrieve_subscriber_info(
(const RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed to retrieve subscriber info, status: %d", status);
+ log::error("Failed to retrieve subscriber info, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
@@ -786,7 +794,7 @@
bt_status_t status = sBluetoothHfpClientInterface->send_dtmf(
(const RawAddress*)addr, (char)code);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed to send DTMF, status: %d", status);
+ log::error("Failed to send DTMF, status: {}", bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
@@ -810,7 +818,8 @@
(const RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed to request last Voice Tag number, status: %d", status);
+ log::error("Failed to request last Voice Tag number, status: {}",
+ bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
@@ -837,7 +846,7 @@
(const RawAddress*)addr, cmd, val1, val2, arg);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed to send cmd, status: %d", status);
+ log::error("Failed to send cmd, status: {}", bt_status_text(status));
}
if (arg != NULL) {
@@ -868,7 +877,7 @@
(const RawAddress*)addr, arg);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("FAILED to control volume, status: %d", status);
+ log::error("FAILED to control volume, status: {}", bt_status_text(status));
}
if (arg != NULL) {
diff --git a/android/app/jni/com_android_bluetooth_hid_device.cpp b/android/app/jni/com_android_bluetooth_hid_device.cpp
index 4a7c155..e4cff15 100644
--- a/android/app/jni/com_android_bluetooth_hid_device.cpp
+++ b/android/app/jni/com_android_bluetooth_hid_device.cpp
@@ -41,7 +41,7 @@
jbyteArray addr = sCallbackEnv->NewByteArray(sizeof(RawAddress));
if (!addr) {
- ALOGE("Fail to new jbyteArray bd addr");
+ log::error("Fail to new jbyteArray bd addr");
return NULL;
}
sCallbackEnv->SetByteArrayRegion(addr, 0, sizeof(RawAddress),
@@ -64,7 +64,7 @@
if (bd_addr) {
addr.reset(marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("%s: failed to allocate storage for bt_addr", __FUNCTION__);
+ log::error("failed to allocate storage for bt_addr");
return;
}
}
@@ -79,7 +79,7 @@
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("%s: failed to allocate storage for bt_addr", __FUNCTION__);
+ log::error("failed to allocate storage for bt_addr");
return;
}
@@ -102,7 +102,7 @@
ScopedLocalRef<jbyteArray> data(sCallbackEnv.get(),
sCallbackEnv->NewByteArray(len));
if (!data.get()) {
- ALOGE("%s: failed to allocate storage for report data", __FUNCTION__);
+ log::error("failed to allocate storage for report data");
return;
}
sCallbackEnv->SetByteArrayRegion(data.get(), 0, len, (jbyte*)p_data);
@@ -124,7 +124,7 @@
ScopedLocalRef<jbyteArray> data(sCallbackEnv.get(),
sCallbackEnv->NewByteArray(len));
if (!data.get()) {
- ALOGE("%s: failed to allocate storage for report data", __FUNCTION__);
+ log::error("failed to allocate storage for report data");
return;
}
sCallbackEnv->SetByteArrayRegion(data.get(), 0, len, (jbyte*)p_data);
@@ -154,58 +154,58 @@
const bt_interface_t* btif;
bt_status_t status;
- ALOGV("%s enter", __FUNCTION__);
+ log::verbose("enter");
if ((btif = getBluetoothInterface()) == NULL) {
- ALOGE("Cannot obtain BT interface");
+ log::error("Cannot obtain BT interface");
return;
}
if (sHiddIf != NULL) {
- ALOGW("Cleaning up interface");
+ log::warn("Cleaning up interface");
sHiddIf->cleanup();
sHiddIf = NULL;
}
if (mCallbacksObj != NULL) {
- ALOGW("Cleaning up callback object");
+ log::warn("Cleaning up callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = NULL;
}
if ((sHiddIf = (bthd_interface_t*)btif->get_profile_interface(
BT_PROFILE_HIDDEV_ID)) == NULL) {
- ALOGE("Cannot obtain interface");
+ log::error("Cannot obtain interface");
return;
}
if ((status = sHiddIf->init(&sHiddCb)) != BT_STATUS_SUCCESS) {
- ALOGE("Failed to initialize interface (%d)", status);
+ log::error("Failed to initialize interface ({})", bt_status_text(status));
sHiddIf = NULL;
return;
}
mCallbacksObj = env->NewGlobalRef(object);
- ALOGV("%s done", __FUNCTION__);
+ log::verbose("done");
}
static void cleanupNative(JNIEnv* env, jobject /* object */) {
- ALOGV("%s enter", __FUNCTION__);
+ log::verbose("enter");
if (sHiddIf != NULL) {
- ALOGI("Cleaning up interface");
+ log::info("Cleaning up interface");
sHiddIf->cleanup();
sHiddIf = NULL;
}
if (mCallbacksObj != NULL) {
- ALOGI("Cleaning up callback object");
+ log::info("Cleaning up callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = NULL;
}
- ALOGV("%s done", __FUNCTION__);
+ log::verbose("done");
}
static void fill_qos(JNIEnv* env, jintArray in, bthd_qos_param_t* out) {
@@ -241,10 +241,10 @@
jstring description, jstring provider,
jbyte subclass, jbyteArray descriptors,
jintArray p_in_qos, jintArray p_out_qos) {
- ALOGV("%s enter", __FUNCTION__);
+ log::verbose("enter");
if (!sHiddIf) {
- ALOGE("%s: Failed to get the Bluetooth HIDD Interface", __func__);
+ log::error("Failed to get the Bluetooth HIDD Interface");
return JNI_FALSE;
}
@@ -273,7 +273,7 @@
bt_status_t ret = sHiddIf->register_app(&app_param, &in_qos, &out_qos);
- ALOGV("%s: register_app() returned %d", __FUNCTION__, ret);
+ log::verbose("register_app() returned {}", bt_status_text(ret));
if (ret == BT_STATUS_SUCCESS) {
result = JNI_TRUE;
@@ -286,30 +286,30 @@
free(data);
}
- ALOGV("%s done (%d)", __FUNCTION__, result);
+ log::verbose("done ({})", result);
return result;
}
static jboolean unregisterAppNative(JNIEnv* /* env */, jobject /* thiz */) {
- ALOGV("%s enter", __FUNCTION__);
+ log::verbose("enter");
jboolean result = JNI_FALSE;
if (!sHiddIf) {
- ALOGE("%s: Failed to get the Bluetooth HIDD Interface", __func__);
+ log::error("Failed to get the Bluetooth HIDD Interface");
return JNI_FALSE;
}
bt_status_t ret = sHiddIf->unregister_app();
- ALOGV("%s: unregister_app() returned %d", __FUNCTION__, ret);
+ log::verbose("unregister_app() returned {}", bt_status_text(ret));
if (ret == BT_STATUS_SUCCESS) {
result = JNI_TRUE;
}
- ALOGV("%s done (%d)", __FUNCTION__, result);
+ log::verbose("done ({})", result);
return result;
}
@@ -319,7 +319,7 @@
jboolean result = JNI_FALSE;
if (!sHiddIf) {
- ALOGE("%s: Failed to get the Bluetooth HIDD Interface", __func__);
+ log::error("Failed to get the Bluetooth HIDD Interface");
return JNI_FALSE;
}
@@ -347,10 +347,10 @@
static jboolean replyReportNative(JNIEnv* env, jobject /* thiz */, jbyte type,
jbyte id, jbyteArray data) {
- ALOGV("%s enter", __FUNCTION__);
+ log::verbose("enter");
if (!sHiddIf) {
- ALOGE("%s: Failed to get the Bluetooth HIDD Interface", __func__);
+ log::error("Failed to get the Bluetooth HIDD Interface");
return JNI_FALSE;
}
@@ -368,7 +368,7 @@
bt_status_t ret =
sHiddIf->send_report((bthd_report_type_t)report_type, id, size, buf);
- ALOGV("%s: send_report() returned %d", __FUNCTION__, ret);
+ log::verbose("send_report() returned {}", bt_status_text(ret));
if (ret == BT_STATUS_SUCCESS) {
result = JNI_TRUE;
@@ -377,17 +377,17 @@
free(buf);
}
- ALOGV("%s done (%d)", __FUNCTION__, result);
+ log::verbose("done ({})", result);
return result;
}
static jboolean reportErrorNative(JNIEnv* /* env */, jobject /* thiz */,
jbyte error) {
- ALOGV("%s enter", __FUNCTION__);
+ log::verbose("enter");
if (!sHiddIf) {
- ALOGE("%s: Failed to get the Bluetooth HIDD Interface", __func__);
+ log::error("Failed to get the Bluetooth HIDD Interface");
return JNI_FALSE;
}
@@ -395,22 +395,22 @@
bt_status_t ret = sHiddIf->report_error(error);
- ALOGV("%s: report_error() returned %d", __FUNCTION__, ret);
+ log::verbose("report_error() returned {}", bt_status_text(ret));
if (ret == BT_STATUS_SUCCESS) {
result = JNI_TRUE;
}
- ALOGV("%s done (%d)", __FUNCTION__, result);
+ log::verbose("done ({})", result);
return result;
}
static jboolean unplugNative(JNIEnv* /* env */, jobject /* thiz */) {
- ALOGV("%s enter", __FUNCTION__);
+ log::verbose("enter");
if (!sHiddIf) {
- ALOGE("%s: Failed to get the Bluetooth HIDD Interface", __func__);
+ log::error("Failed to get the Bluetooth HIDD Interface");
return JNI_FALSE;
}
@@ -418,23 +418,23 @@
bt_status_t ret = sHiddIf->virtual_cable_unplug();
- ALOGV("%s: virtual_cable_unplug() returned %d", __FUNCTION__, ret);
+ log::verbose("virtual_cable_unplug() returned {}", bt_status_text(ret));
if (ret == BT_STATUS_SUCCESS) {
result = JNI_TRUE;
}
- ALOGV("%s done (%d)", __FUNCTION__, result);
+ log::verbose("done ({})", result);
return result;
}
static jboolean connectNative(JNIEnv* env, jobject /* thiz */,
jbyteArray address) {
- ALOGV("%s enter", __FUNCTION__);
+ log::verbose("enter");
if (!sHiddIf) {
- ALOGE("%s: Failed to get the Bluetooth HIDD Interface", __func__);
+ log::error("Failed to get the Bluetooth HIDD Interface");
return JNI_FALSE;
}
@@ -442,28 +442,28 @@
jbyte* addr = env->GetByteArrayElements(address, NULL);
if (!addr) {
- ALOGE("Bluetooth device address null");
+ log::error("Bluetooth device address null");
return JNI_FALSE;
}
bt_status_t ret = sHiddIf->connect((RawAddress*)addr);
- ALOGV("%s: connect() returned %d", __FUNCTION__, ret);
+ log::verbose("connect() returned {}", bt_status_text(ret));
if (ret == BT_STATUS_SUCCESS) {
result = JNI_TRUE;
}
- ALOGV("%s done (%d)", __FUNCTION__, result);
+ log::verbose("done ({})", result);
return result;
}
static jboolean disconnectNative(JNIEnv* /* env */, jobject /* thiz */) {
- ALOGV("%s enter", __FUNCTION__);
+ log::verbose("enter");
if (!sHiddIf) {
- ALOGE("%s: Failed to get the Bluetooth HIDD Interface", __func__);
+ log::error("Failed to get the Bluetooth HIDD Interface");
return JNI_FALSE;
}
@@ -471,13 +471,13 @@
bt_status_t ret = sHiddIf->disconnect();
- ALOGV("%s: disconnect() returned %d", __FUNCTION__, ret);
+ log::verbose("disconnect() returned {}", bt_status_text(ret));
if (ret == BT_STATUS_SUCCESS) {
result = JNI_TRUE;
}
- ALOGV("%s done (%d)", __FUNCTION__, result);
+ log::verbose("done ({})", result);
return result;
}
diff --git a/android/app/jni/com_android_bluetooth_hid_host.cpp b/android/app/jni/com_android_bluetooth_hid_host.cpp
index e89ce84..b21fc9c 100644
--- a/android/app/jni/com_android_bluetooth_hid_host.cpp
+++ b/android/app/jni/com_android_bluetooth_hid_host.cpp
@@ -41,7 +41,7 @@
jbyteArray addr = sCallbackEnv->NewByteArray(sizeof(RawAddress));
if (!addr) {
- ALOGE("Fail to new jbyteArray bd addr");
+ log::error("Fail to new jbyteArray bd addr");
return NULL;
}
sCallbackEnv->SetByteArrayRegion(addr, 0, sizeof(RawAddress),
@@ -55,12 +55,12 @@
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!mCallbacksObj) {
- ALOGE("%s: mCallbacksObj is null", __func__);
+ log::error("mCallbacksObj is null");
return;
}
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for HID channel state");
+ log::error("Fail to new jbyteArray bd addr for HID channel state");
return;
}
@@ -75,17 +75,17 @@
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!mCallbacksObj) {
- ALOGE("%s: mCallbacksObj is null", __func__);
+ log::error("mCallbacksObj is null");
return;
}
if (hh_status != BTHH_OK) {
- ALOGE("BTHH Status is not OK!");
+ log::error("BTHH Status is not OK!");
return;
}
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for get protocal mode callback");
+ log::error("Fail to new jbyteArray bd addr for get protocol mode callback");
return;
}
@@ -99,23 +99,23 @@
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!mCallbacksObj) {
- ALOGE("%s: mCallbacksObj is null", __func__);
+ log::error("mCallbacksObj is null");
return;
}
if (hh_status != BTHH_OK) {
- ALOGE("BTHH Status is not OK!");
+ log::error("BTHH Status is not OK!");
return;
}
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for get report callback");
+ log::error("Fail to new jbyteArray bd addr for get report callback");
return;
}
ScopedLocalRef<jbyteArray> data(sCallbackEnv.get(),
sCallbackEnv->NewByteArray(rpt_size));
if (!data.get()) {
- ALOGE("Fail to new jbyteArray data for get report callback");
+ log::error("Fail to new jbyteArray data for get report callback");
return;
}
@@ -126,17 +126,17 @@
static void virtual_unplug_callback(RawAddress* bd_addr,
bthh_status_t hh_status) {
- ALOGV("call to virtual_unplug_callback");
+ log::verbose("call to virtual_unplug_callback");
std::shared_lock<std::shared_timed_mutex> lock(mCallbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!mCallbacksObj) {
- ALOGE("%s: mCallbacksObj is null", __func__);
+ log::error("mCallbacksObj is null");
return;
}
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for HID channel state");
+ log::error("Fail to new jbyteArray bd addr for HID channel state");
return;
}
sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onVirtualUnplug,
@@ -148,13 +148,13 @@
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
if (!mCallbacksObj) {
- ALOGE("%s: mCallbacksObj is null", __func__);
+ log::error("mCallbacksObj is null");
return;
}
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("Fail to new jbyteArray bd addr for handshake callback");
+ log::error("Fail to new jbyteArray bd addr for handshake callback");
return;
}
sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onHandshake, addr.get(),
@@ -170,7 +170,7 @@
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- ALOGE("%s: Fail to new jbyteArray bd addr", __func__);
+ log::error("Fail to new jbyteArray bd addr");
return;
}
sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGetIdleTime, addr.get(),
@@ -192,18 +192,18 @@
std::unique_lock<std::shared_timed_mutex> lock(mCallbacks_mutex);
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == NULL) {
- ALOGE("Bluetooth module is not loaded");
+ log::error("Bluetooth module is not loaded");
return;
}
if (sBluetoothHidInterface != NULL) {
- ALOGW("Cleaning up Bluetooth HID Interface before initializing...");
+ log::warn("Cleaning up Bluetooth HID Interface before initializing...");
sBluetoothHidInterface->cleanup();
sBluetoothHidInterface = NULL;
}
if (mCallbacksObj != NULL) {
- ALOGW("Cleaning up Bluetooth GID callback object");
+ log::warn("Cleaning up Bluetooth GID callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = NULL;
}
@@ -211,13 +211,14 @@
sBluetoothHidInterface =
(bthh_interface_t*)btInf->get_profile_interface(BT_PROFILE_HIDHOST_ID);
if (sBluetoothHidInterface == NULL) {
- ALOGE("Failed to get Bluetooth HID Interface");
+ log::error("Failed to get Bluetooth HID Interface");
return;
}
bt_status_t status = sBluetoothHidInterface->init(&sBluetoothHidCallbacks);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed to initialize Bluetooth HID, status: %d", status);
+ log::error("Failed to initialize Bluetooth HID, status: {}",
+ bt_status_text(status));
sBluetoothHidInterface = NULL;
return;
}
@@ -230,18 +231,18 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == NULL) {
- ALOGE("Bluetooth module is not loaded");
+ log::error("Bluetooth module is not loaded");
return;
}
if (sBluetoothHidInterface != NULL) {
- ALOGW("Cleaning up Bluetooth HID Interface...");
+ log::warn("Cleaning up Bluetooth HID Interface...");
sBluetoothHidInterface->cleanup();
sBluetoothHidInterface = NULL;
}
if (mCallbacksObj != NULL) {
- ALOGW("Cleaning up Bluetooth GID callback object");
+ log::warn("Cleaning up Bluetooth GID callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = NULL;
}
@@ -253,14 +254,15 @@
jbyte* addr = env->GetByteArrayElements(address, NULL);
if (!addr) {
- ALOGE("Bluetooth device address null");
+ log::error("Bluetooth device address null");
return JNI_FALSE;
}
jboolean ret = JNI_TRUE;
bt_status_t status = sBluetoothHidInterface->connect((RawAddress*)addr);
if (status != BT_STATUS_SUCCESS && status != BT_STATUS_BUSY) {
- ALOGE("Failed HID channel connection, status: %d", status);
+ log::error("Failed HID channel connection, status: {}",
+ bt_status_text(status));
ret = JNI_FALSE;
}
env->ReleaseByteArrayElements(address, addr, 0);
@@ -276,13 +278,14 @@
addr = env->GetByteArrayElements(address, NULL);
if (!addr) {
- ALOGE("Bluetooth device address null");
+ log::error("Bluetooth device address null");
return JNI_FALSE;
}
bt_status_t status = sBluetoothHidInterface->disconnect((RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed disconnect hid channel, status: %d", status);
+ log::error("Failed disconnect hid channel, status: {}",
+ bt_status_text(status));
ret = JNI_FALSE;
}
env->ReleaseByteArrayElements(address, addr, 0);
@@ -296,7 +299,7 @@
jbyte* addr = env->GetByteArrayElements(address, NULL);
if (!addr) {
- ALOGE("Bluetooth device address null");
+ log::error("Bluetooth device address null");
return JNI_FALSE;
}
@@ -306,7 +309,7 @@
bt_status_t status = sBluetoothHidInterface->get_protocol(
(RawAddress*)addr, (bthh_protocol_mode_t)protocolMode);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed get protocol mode, status: %d", status);
+ log::error("Failed get protocol mode, status: {}", bt_status_text(status));
ret = JNI_FALSE;
}
env->ReleaseByteArrayElements(address, addr, 0);
@@ -320,7 +323,7 @@
jbyte* addr = env->GetByteArrayElements(address, NULL);
if (!addr) {
- ALOGE("Bluetooth device address null");
+ log::error("Bluetooth device address null");
return JNI_FALSE;
}
@@ -328,7 +331,7 @@
bt_status_t status =
sBluetoothHidInterface->virtual_unplug((RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed virual unplug, status: %d", status);
+ log::error("Failed virual unplug, status: {}", bt_status_text(status));
ret = JNI_FALSE;
}
env->ReleaseByteArrayElements(address, addr, 0);
@@ -339,11 +342,11 @@
jbyteArray address, jint protocolMode) {
if (!sBluetoothHidInterface) return JNI_FALSE;
- ALOGD("%s: protocolMode = %d", __func__, protocolMode);
+ log::debug("protocolMode = {}", protocolMode);
jbyte* addr = env->GetByteArrayElements(address, NULL);
if (!addr) {
- ALOGE("Bluetooth device address null");
+ log::error("Bluetooth device address null");
return JNI_FALSE;
}
@@ -356,7 +359,7 @@
mode = BTHH_BOOT_MODE;
break;
default:
- ALOGE("Unknown HID protocol mode");
+ log::error("Unknown HID protocol mode");
return JNI_FALSE;
}
@@ -364,7 +367,7 @@
bt_status_t status =
sBluetoothHidInterface->set_protocol((RawAddress*)addr, mode);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed set protocol mode, status: %d", status);
+ log::error("Failed set protocol mode, status: {}", bt_status_text(status));
ret = JNI_FALSE;
}
env->ReleaseByteArrayElements(address, addr, 0);
@@ -375,13 +378,13 @@
static jboolean getReportNative(JNIEnv* env, jobject /* object */,
jbyteArray address, jbyte reportType,
jbyte reportId, jint bufferSize) {
- ALOGV("%s: reportType = %d, reportId = %d, bufferSize = %d", __func__,
- reportType, reportId, bufferSize);
+ log::verbose("reportType = {}, reportId = {}, bufferSize = {}", reportType,
+ reportId, bufferSize);
if (!sBluetoothHidInterface) return JNI_FALSE;
jbyte* addr = env->GetByteArrayElements(address, NULL);
if (!addr) {
- ALOGE("Bluetooth device address null");
+ log::error("Bluetooth device address null");
return JNI_FALSE;
}
@@ -392,7 +395,7 @@
(RawAddress*)addr, (bthh_report_type_t)rType, (uint8_t)rId, bufferSize);
jboolean ret = JNI_TRUE;
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed get report, status: %d", status);
+ log::error("Failed get report, status: {}", bt_status_text(status));
ret = JNI_FALSE;
}
env->ReleaseByteArrayElements(address, addr, 0);
@@ -403,12 +406,12 @@
static jboolean setReportNative(JNIEnv* env, jobject /* object */,
jbyteArray address, jbyte reportType,
jstring report) {
- ALOGV("%s: reportType = %d", __func__, reportType);
+ log::verbose("reportType = {}", reportType);
if (!sBluetoothHidInterface) return JNI_FALSE;
jbyte* addr = env->GetByteArrayElements(address, NULL);
if (!addr) {
- ALOGE("Bluetooth device address null");
+ log::error("Bluetooth device address null");
return JNI_FALSE;
}
jint rType = reportType;
@@ -418,7 +421,7 @@
bt_status_t status = sBluetoothHidInterface->set_report(
(RawAddress*)addr, (bthh_report_type_t)rType, (char*)c_report);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed set report, status: %d", status);
+ log::error("Failed set report, status: {}", bt_status_text(status));
ret = JNI_FALSE;
}
env->ReleaseStringUTFChars(report, c_report);
@@ -429,13 +432,13 @@
static jboolean sendDataNative(JNIEnv* env, jobject /* object */,
jbyteArray address, jstring report) {
- ALOGV("%s", __func__);
+ log::verbose("");
jboolean ret = JNI_TRUE;
if (!sBluetoothHidInterface) return JNI_FALSE;
jbyte* addr = env->GetByteArrayElements(address, NULL);
if (!addr) {
- ALOGE("Bluetooth device address null");
+ log::error("Bluetooth device address null");
return JNI_FALSE;
}
@@ -444,7 +447,7 @@
bt_status_t status =
sBluetoothHidInterface->send_data((RawAddress*)addr, (char*)c_report);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("Failed set data, status: %d", status);
+ log::error("Failed set data, status: {}", bt_status_text(status));
ret = JNI_FALSE;
}
env->ReleaseStringUTFChars(report, c_report);
@@ -459,13 +462,13 @@
jbyte* addr = env->GetByteArrayElements(address, NULL);
if (!addr) {
- ALOGE("%s: Bluetooth device address null", __func__);
+ log::error("Bluetooth device address null");
return JNI_FALSE;
}
bt_status_t status = sBluetoothHidInterface->get_idle_time((RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("%s: Failed get idle time, status: %d", __func__, status);
+ log::error("Failed get idle time, status: {}", bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
@@ -478,14 +481,14 @@
jbyte* addr = env->GetByteArrayElements(address, NULL);
if (!addr) {
- ALOGE("%s: Bluetooth device address null", __func__);
+ log::error("Bluetooth device address null");
return JNI_FALSE;
}
bt_status_t status =
sBluetoothHidInterface->set_idle_time((RawAddress*)addr, idle_time);
if (status != BT_STATUS_SUCCESS) {
- ALOGE("%s: Failed set idle time, status: %d", __func__, status);
+ log::error("Failed set idle time, status: {}", bt_status_text(status));
}
env->ReleaseByteArrayElements(address, addr, 0);
diff --git a/android/app/jni/com_android_bluetooth_le_audio.cpp b/android/app/jni/com_android_bluetooth_le_audio.cpp
index e6f07c4..21996ef 100644
--- a/android/app/jni/com_android_bluetooth_le_audio.cpp
+++ b/android/app/jni/com_android_bluetooth_le_audio.cpp
@@ -36,6 +36,7 @@
using bluetooth::le_audio::ConnectionState;
using bluetooth::le_audio::GroupNodeStatus;
using bluetooth::le_audio::GroupStatus;
+using bluetooth::le_audio::GroupStreamStatus;
using bluetooth::le_audio::LeAudioBroadcasterCallbacks;
using bluetooth::le_audio::LeAudioBroadcasterInterface;
using bluetooth::le_audio::LeAudioClientCallbacks;
@@ -55,6 +56,7 @@
static jmethodID method_onHealthBasedRecommendationAction;
static jmethodID method_onHealthBasedGroupRecommendationAction;
static jmethodID method_onUnicastMonitorModeStatus;
+static jmethodID method_onGroupStreamStatus;
static struct {
jclass clazz;
@@ -112,13 +114,13 @@
jobject prepareCodecConfigObj(JNIEnv* env,
btle_audio_codec_config_t codecConfig) {
- LOG(INFO) << __func__ << "ct: " << codecConfig.codec_type
- << ", codec_priority: " << codecConfig.codec_priority
- << ", sample_rate: " << codecConfig.sample_rate
- << ", bits_per_sample: " << codecConfig.bits_per_sample
- << ", channel_count: " << codecConfig.channel_count
- << ", frame_duration: " << codecConfig.frame_duration
- << ", octets_per_frame: " << codecConfig.octets_per_frame;
+ log::info(
+ "ct: {}, codec_priority: {}, sample_rate: {}, bits_per_sample: {}, "
+ "channel_count: {}, frame_duration: {}, octets_per_frame: {}",
+ codecConfig.codec_type, codecConfig.codec_priority,
+ codecConfig.sample_rate, codecConfig.bits_per_sample,
+ codecConfig.channel_count, codecConfig.frame_duration,
+ codecConfig.octets_per_frame);
jobject codecConfigObj = env->NewObject(
android_bluetooth_BluetoothLeAudioCodecConfig.clazz,
@@ -152,7 +154,7 @@
~LeAudioClientCallbacksImpl() = default;
void OnInitialized(void) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return;
@@ -161,8 +163,8 @@
void OnConnectionState(ConnectionState state,
const RawAddress& bd_addr) override {
- LOG(INFO) << __func__ << ", state:" << int(state)
- << ", addr: " << bd_addr.ToRedactedStringForLogging();
+ log::info("state:{}, addr: {}", int(state),
+ bd_addr.ToRedactedStringForLogging());
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -171,7 +173,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new jbyteArray bd addr for connection state";
+ log::error("Failed to new jbyteArray bd addr for connection state");
return;
}
@@ -182,7 +184,7 @@
}
void OnGroupStatus(int group_id, GroupStatus group_status) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -194,7 +196,7 @@
void OnGroupNodeStatus(const RawAddress& bd_addr, int group_id,
GroupNodeStatus node_status) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -203,7 +205,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new jbyteArray bd addr for group status";
+ log::error("Failed to new jbyteArray bd addr for group status");
return;
}
@@ -216,7 +218,7 @@
void OnAudioConf(uint8_t direction, int group_id,
uint32_t sink_audio_location, uint32_t source_audio_location,
uint16_t avail_cont) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -230,7 +232,7 @@
void OnSinkAudioLocationAvailable(const RawAddress& bd_addr,
uint32_t sink_audio_location) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -239,7 +241,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new jbyteArray bd addr for group status";
+ log::error("Failed to new jbyteArray bd addr for group status");
return;
}
@@ -254,7 +256,7 @@
std::vector<btle_audio_codec_config_t> local_input_capa_codec_conf,
std::vector<btle_audio_codec_config_t> local_output_capa_codec_conf)
override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -274,7 +276,7 @@
void OnAudioGroupCurrentCodecConf(
int group_id, btle_audio_codec_config_t input_codec_conf,
btle_audio_codec_config_t output_codec_conf) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -295,7 +297,7 @@
std::vector<btle_audio_codec_config_t> input_selectable_codec_conf,
std::vector<btle_audio_codec_config_t> output_selectable_codec_conf)
override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -314,7 +316,7 @@
void OnHealthBasedRecommendationAction(
const RawAddress& bd_addr,
bluetooth::le_audio::LeAudioHealthBasedAction action) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -323,7 +325,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new jbyteArray bd addr for group status";
+ log::error("Failed to new jbyteArray bd addr for group status");
return;
}
@@ -337,7 +339,7 @@
void OnHealthBasedGroupRecommendationAction(
int group_id,
bluetooth::le_audio::LeAudioHealthBasedAction action) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -350,7 +352,7 @@
void OnUnicastMonitorModeStatus(uint8_t direction,
UnicastMonitorModeStatus status) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -360,6 +362,18 @@
method_onUnicastMonitorModeStatus,
(jint)direction, (jint)status);
}
+
+ void OnGroupStreamStatus(int group_id,
+ GroupStreamStatus group_stream_status) override {
+ LOG(INFO) << __func__;
+
+ std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
+ CallbackEnv sCallbackEnv(__func__);
+ if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) return;
+
+ sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGroupStreamStatus,
+ (jint)group_id, (jint)group_stream_status);
+ }
};
static LeAudioClientCallbacksImpl sLeAudioClientCallbacks;
@@ -375,7 +389,7 @@
if (!env->IsInstanceOf(
jcodecConfig,
android_bluetooth_BluetoothLeAudioCodecConfig.clazz)) {
- ALOGE("%s: Invalid BluetoothLeAudioCodecConfig instance", __func__);
+ log::error("Invalid BluetoothLeAudioCodecConfig instance");
continue;
}
jint codecType = env->CallIntMethod(
@@ -397,18 +411,18 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == nullptr) {
- LOG(ERROR) << "Bluetooth module is not loaded";
+ log::error("Bluetooth module is not loaded");
return;
}
if (mCallbacksObj != nullptr) {
- LOG(INFO) << "Cleaning up LeAudio callback object";
+ log::info("Cleaning up LeAudio callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = nullptr;
}
if ((mCallbacksObj = env->NewGlobalRef(object)) == nullptr) {
- LOG(ERROR) << "Failed to allocate Global Ref for LeAudio Callbacks";
+ log::error("Failed to allocate Global Ref for LeAudio Callbacks");
return;
}
@@ -416,8 +430,8 @@
(jclass)env->NewGlobalRef(
env->FindClass("android/bluetooth/BluetoothLeAudioCodecConfig"));
if (android_bluetooth_BluetoothLeAudioCodecConfig.clazz == nullptr) {
- LOG(ERROR) << "Failed to allocate Global Ref for "
- "BluetoothLeAudioCodecConfig class";
+ log::error(
+ "Failed to allocate Global Ref for BluetoothLeAudioCodecConfig class");
return;
}
@@ -425,7 +439,7 @@
(LeAudioClientInterface*)btInf->get_profile_interface(
BT_PROFILE_LE_AUDIO_ID);
if (sLeAudioClientInterface == nullptr) {
- LOG(ERROR) << "Failed to get Bluetooth LeAudio Interface";
+ log::error("Failed to get Bluetooth LeAudio Interface");
return;
}
@@ -442,7 +456,7 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == nullptr) {
- LOG(ERROR) << "Bluetooth module is not loaded";
+ log::error("Bluetooth module is not loaded");
return;
}
@@ -462,7 +476,7 @@
static jboolean connectLeAudioNative(JNIEnv* env, jobject /* object */,
jbyteArray address) {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sLeAudioClientInterface) return JNI_FALSE;
@@ -480,7 +494,7 @@
static jboolean disconnectLeAudioNative(JNIEnv* env, jobject /* object */,
jbyteArray address) {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sLeAudioClientInterface) return JNI_FALSE;
@@ -502,7 +516,7 @@
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (!sLeAudioClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Bluetooth LeAudio Interface";
+ log::error("Failed to get the Bluetooth LeAudio Interface");
return JNI_FALSE;
}
@@ -523,7 +537,7 @@
jbyte* addr = env->GetByteArrayElements(address, nullptr);
if (!sLeAudioClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Bluetooth LeAudio Interface";
+ log::error("Failed to get the Bluetooth LeAudio Interface");
return JNI_FALSE;
}
@@ -543,7 +557,7 @@
jint group_id, jbyteArray address) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sLeAudioClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Bluetooth LeAudio Interface";
+ log::error("Failed to get the Bluetooth LeAudio Interface");
return JNI_FALSE;
}
@@ -561,11 +575,11 @@
static void groupSetActiveNative(JNIEnv* /* env */, jobject /* object */,
jint group_id) {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sLeAudioClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Bluetooth LeAudio Interface";
+ log::error("Failed to get the Bluetooth LeAudio Interface");
return;
}
@@ -582,7 +596,7 @@
android_bluetooth_BluetoothLeAudioCodecConfig.clazz) ||
!env->IsInstanceOf(outputCodecConfig,
android_bluetooth_BluetoothLeAudioCodecConfig.clazz)) {
- ALOGE("%s: Invalid BluetoothLeAudioCodecConfig instance", __func__);
+ log::error("Invalid BluetoothLeAudioCodecConfig instance");
return;
}
@@ -678,7 +692,7 @@
jint ccid, jint contextType) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sLeAudioClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Bluetooth LeAudio Interface";
+ log::error("Failed to get the Bluetooth LeAudio Interface");
return;
}
@@ -689,7 +703,7 @@
jboolean inCall) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sLeAudioClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Bluetooth LeAudio Interface";
+ log::error("Failed to get the Bluetooth LeAudio Interface");
return;
}
@@ -700,7 +714,7 @@
jint direction, jboolean enable) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sLeAudioClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Bluetooth LeAudio Interface";
+ log::error("Failed to get the Bluetooth LeAudio Interface");
return;
}
@@ -712,7 +726,7 @@
jboolean isDuplexPreferenceLeAudio) {
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sLeAudioClientInterface) {
- LOG(ERROR) << __func__ << ": Failed to get the Bluetooth LeAudio Interface";
+ log::error("Failed to get the Bluetooth LeAudio Interface");
return;
}
@@ -752,7 +766,7 @@
jbyteArray raw_metadata = env->NewByteArray(raw_meta_size);
if (!raw_metadata) {
- LOG(ERROR) << "Failed to create new jbyteArray for raw LTV";
+ log::error("Failed to create new jbyteArray for raw LTV");
return nullptr;
}
@@ -828,7 +842,7 @@
ScopedLocalRef<jbyteArray> raw_metadata(env,
prepareRawLtvArray(env, metadata));
if (!raw_metadata.get()) {
- LOG(ERROR) << "Failed to create raw metadata jbyteArray";
+ log::error("Failed to create raw metadata jbyteArray");
return nullptr;
}
@@ -848,7 +862,7 @@
env, prepareLeAudioCodecConfigMetadataObject(
env, bis_config.codec_specific_params));
if (!meta_object.get()) {
- LOG(ERROR) << "Failed to create new metadata object for bis config";
+ log::error("Failed to create new metadata object for bis config");
return nullptr;
}
@@ -874,7 +888,7 @@
program_info_str = env->NewStringUTF(p_str.c_str());
if (!program_info_str) {
- LOG(ERROR) << "Failed to create new preset name String for preset name";
+ log::error("Failed to create new preset name String for preset name");
return nullptr;
}
}
@@ -890,7 +904,7 @@
language_str = env->NewStringUTF(l_str.c_str());
if (!language_str) {
- LOG(ERROR) << "Failed to create new preset name String for language";
+ log::error("Failed to create new preset name String for language");
return nullptr;
}
}
@@ -899,7 +913,7 @@
ScopedLocalRef<jbyteArray> raw_metadata(env,
prepareRawLtvArray(env, metadata));
if (!raw_metadata.get()) {
- LOG(ERROR) << "Failed to create raw_metadata jbyteArray";
+ log::error("Failed to create raw_metadata jbyteArray");
return nullptr;
}
@@ -926,7 +940,7 @@
jobject array = env->NewObject(java_util_ArrayList.clazz,
java_util_ArrayList.constructor);
if (!array) {
- LOG(ERROR) << "Failed to create array for subgroups";
+ log::error("Failed to create array for subgroups");
return nullptr;
}
@@ -934,7 +948,7 @@
ScopedLocalRef<jobject> channel_obj(
env, prepareLeBroadcastChannelObject(env, el));
if (!channel_obj.get()) {
- LOG(ERROR) << "Failed to create new channel object";
+ log::error("Failed to create new channel object");
return nullptr;
}
@@ -956,21 +970,21 @@
env, prepareLeAudioCodecConfigMetadataObject(
env, subgroup.codec_config.codec_specific_params));
if (!codec_config_meta_obj.get()) {
- LOG(ERROR) << "Failed to create new codec config metadata";
+ log::error("Failed to create new codec config metadata");
return nullptr;
}
ScopedLocalRef<jobject> content_meta_obj(
env, prepareLeAudioContentMetadataObject(env, subgroup.metadata));
if (!content_meta_obj.get()) {
- LOG(ERROR) << "Failed to create new codec config metadata";
+ log::error("Failed to create new codec config metadata");
return nullptr;
}
ScopedLocalRef<jobject> channel_list_obj(
env, prepareLeBroadcastChannelListObject(env, subgroup.bis_configs));
if (!channel_list_obj.get()) {
- LOG(ERROR) << "Failed to create new codec config metadata";
+ log::error("Failed to create new codec config metadata");
return nullptr;
}
@@ -989,7 +1003,7 @@
jobject array = env->NewObject(java_util_ArrayList.clazz,
java_util_ArrayList.constructor);
if (!array) {
- LOG(ERROR) << "Failed to create array for subgroups";
+ log::error("Failed to create array for subgroups");
return nullptr;
}
@@ -997,7 +1011,7 @@
ScopedLocalRef<jobject> subgroup_obj(
env, prepareLeBroadcastSubgroupObject(env, el));
if (!subgroup_obj.get()) {
- LOG(ERROR) << "Failed to create new subgroup object";
+ log::error("Failed to create new subgroup object");
return nullptr;
}
@@ -1016,7 +1030,7 @@
ScopedLocalRef<jstring> addr_jstr(env, env->NewStringUTF(addr_str.c_str()));
if (!addr_jstr.get()) {
- LOG(ERROR) << "Failed to create new preset name String for preset name";
+ log::error("Failed to create new preset name String for preset name");
return nullptr;
}
@@ -1032,7 +1046,7 @@
env, prepareBluetoothDeviceObject(env, broadcast_metadata.addr,
broadcast_metadata.addr_type));
if (!device_obj.get()) {
- LOG(ERROR) << "Failed to create new BluetoothDevice";
+ log::error("Failed to create new BluetoothDevice");
return nullptr;
}
@@ -1041,7 +1055,7 @@
prepareLeBroadcastSubgroupListObject(
env, broadcast_metadata.basic_audio_announcement.subgroup_configs));
if (!subgroup_list_obj.get()) {
- LOG(ERROR) << "Failed to create new Subgroup array";
+ log::error("Failed to create new Subgroup array");
return nullptr;
}
@@ -1057,7 +1071,7 @@
ScopedLocalRef<jbyteArray> code(env, env->NewByteArray(nativeCodeSize));
if (!code.get()) {
- LOG(ERROR) << "Failed to create new jbyteArray for the broadcast code";
+ log::error("Failed to create new jbyteArray for the broadcast code");
return nullptr;
}
@@ -1071,7 +1085,7 @@
ScopedLocalRef<jstring> broadcast_name(
env, env->NewStringUTF(broadcast_metadata.broadcast_name.c_str()));
if (!broadcast_name.get()) {
- LOG(ERROR) << "Failed to create new broadcast name String";
+ log::error("Failed to create new broadcast name String");
return nullptr;
}
@@ -1091,7 +1105,7 @@
env, prepareLeAudioContentMetadataObject(
env, broadcast_metadata.public_announcement.metadata));
if (!public_meta_obj.get()) {
- LOG(ERROR) << "Failed to create new public metadata obj";
+ log::error("Failed to create new public metadata obj");
return nullptr;
}
@@ -1114,7 +1128,7 @@
~LeAudioBroadcasterCallbacksImpl() = default;
void OnBroadcastCreated(uint32_t broadcast_id, bool success) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(sBroadcasterCallbacksMutex);
CallbackEnv sCallbackEnv(__func__);
@@ -1126,7 +1140,7 @@
}
void OnBroadcastDestroyed(uint32_t broadcast_id) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(sBroadcasterCallbacksMutex);
CallbackEnv sCallbackEnv(__func__);
@@ -1139,7 +1153,7 @@
void OnBroadcastStateChanged(uint32_t broadcast_id,
BroadcastState state) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(sBroadcasterCallbacksMutex);
CallbackEnv sCallbackEnv(__func__);
@@ -1154,7 +1168,7 @@
void OnBroadcastMetadataChanged(uint32_t broadcast_id,
const bluetooth::le_audio::BroadcastMetadata&
broadcast_metadata) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(sBroadcasterCallbacksMutex);
CallbackEnv sCallbackEnv(__func__);
@@ -1180,21 +1194,21 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == nullptr) {
- LOG(ERROR) << "Bluetooth module is not loaded";
+ log::error("Bluetooth module is not loaded");
return;
}
android_bluetooth_BluetoothDevice.clazz = (jclass)env->NewGlobalRef(
env->FindClass("android/bluetooth/BluetoothDevice"));
if (android_bluetooth_BluetoothDevice.clazz == nullptr) {
- LOG(ERROR) << "Failed to allocate Global Ref for BluetoothDevice class";
+ log::error("Failed to allocate Global Ref for BluetoothDevice class");
return;
}
java_util_ArrayList.clazz =
(jclass)env->NewGlobalRef(env->FindClass("java/util/ArrayList"));
if (java_util_ArrayList.clazz == nullptr) {
- LOG(ERROR) << "Failed to allocate Global Ref for ArrayList class";
+ log::error("Failed to allocate Global Ref for ArrayList class");
return;
}
@@ -1202,8 +1216,9 @@
(jclass)env->NewGlobalRef(env->FindClass(
"android/bluetooth/BluetoothLeAudioCodecConfigMetadata"));
if (android_bluetooth_BluetoothLeAudioCodecConfigMetadata.clazz == nullptr) {
- LOG(ERROR) << "Failed to allocate Global Ref for "
- "BluetoothLeAudioCodecConfigMetadata class";
+ log::error(
+ "Failed to allocate Global Ref for BluetoothLeAudioCodecConfigMetadata "
+ "class");
return;
}
@@ -1211,8 +1226,9 @@
(jclass)env->NewGlobalRef(
env->FindClass("android/bluetooth/BluetoothLeAudioContentMetadata"));
if (android_bluetooth_BluetoothLeAudioContentMetadata.clazz == nullptr) {
- LOG(ERROR) << "Failed to allocate Global Ref for "
- "BluetoothLeAudioContentMetadata class";
+ log::error(
+ "Failed to allocate Global Ref for BluetoothLeAudioContentMetadata "
+ "class");
return;
}
@@ -1220,8 +1236,8 @@
(jclass)env->NewGlobalRef(
env->FindClass("android/bluetooth/BluetoothLeBroadcastSubgroup"));
if (android_bluetooth_BluetoothLeBroadcastSubgroup.clazz == nullptr) {
- LOG(ERROR) << "Failed to allocate Global Ref for "
- "BluetoothLeBroadcastSubgroup class";
+ log::error(
+ "Failed to allocate Global Ref for BluetoothLeBroadcastSubgroup class");
return;
}
@@ -1229,8 +1245,8 @@
(jclass)env->NewGlobalRef(
env->FindClass("android/bluetooth/BluetoothLeBroadcastChannel"));
if (android_bluetooth_BluetoothLeBroadcastChannel.clazz == nullptr) {
- LOG(ERROR) << "Failed to allocate Global Ref for "
- "BluetoothLeBroadcastChannel class";
+ log::error(
+ "Failed to allocate Global Ref for BluetoothLeBroadcastChannel class");
return;
}
@@ -1238,20 +1254,20 @@
(jclass)env->NewGlobalRef(
env->FindClass("android/bluetooth/BluetoothLeBroadcastMetadata"));
if (android_bluetooth_BluetoothLeBroadcastMetadata.clazz == nullptr) {
- LOG(ERROR) << "Failed to allocate Global Ref for "
- "BluetoothLeBroadcastMetadata class";
+ log::error(
+ "Failed to allocate Global Ref for BluetoothLeBroadcastMetadata class");
return;
}
if (sBroadcasterCallbacksObj != nullptr) {
- LOG(INFO) << "Cleaning up LeAudio Broadcaster callback object";
+ log::info("Cleaning up LeAudio Broadcaster callback object");
env->DeleteGlobalRef(sBroadcasterCallbacksObj);
sBroadcasterCallbacksObj = nullptr;
}
if ((sBroadcasterCallbacksObj = env->NewGlobalRef(object)) == nullptr) {
- LOG(ERROR)
- << "Failed to allocate Global Ref for LeAudio Broadcaster Callbacks";
+ log::error(
+ "Failed to allocate Global Ref for LeAudio Broadcaster Callbacks");
return;
}
@@ -1259,7 +1275,7 @@
(LeAudioBroadcasterInterface*)btInf->get_profile_interface(
BT_PROFILE_LE_AUDIO_BROADCASTER_ID);
if (sLeAudioBroadcasterInterface == nullptr) {
- LOG(ERROR) << "Failed to get Bluetooth LeAudio Broadcaster Interface";
+ log::error("Failed to get Bluetooth LeAudio Broadcaster Interface");
return;
}
@@ -1272,7 +1288,7 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == nullptr) {
- LOG(ERROR) << "Bluetooth module is not loaded";
+ log::error("Bluetooth module is not loaded");
return;
}
@@ -1288,7 +1304,7 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == nullptr) {
- LOG(ERROR) << "Bluetooth module is not loaded";
+ log::error("Bluetooth module is not loaded");
return;
}
@@ -1348,7 +1364,7 @@
jbyteArray publicMetadata,
jintArray qualityArray,
jobjectArray metadataArray) {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(sBroadcasterInterfaceMutex);
if (!sLeAudioBroadcasterInterface) return;
@@ -1356,7 +1372,7 @@
if (broadcast_code) {
jsize size = env->GetArrayLength(broadcast_code);
if (size > 16) {
- ALOGE("%s: broadcast code to long", __func__);
+ log::error("broadcast code to long");
return;
}
@@ -1424,7 +1440,7 @@
static void StartBroadcastNative(JNIEnv* /* env */, jobject /* object */,
jint broadcast_id) {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(sBroadcasterInterfaceMutex);
if (!sLeAudioBroadcasterInterface) return;
sLeAudioBroadcasterInterface->StartBroadcast(broadcast_id);
@@ -1432,7 +1448,7 @@
static void StopBroadcastNative(JNIEnv* /* env */, jobject /* object */,
jint broadcast_id) {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(sBroadcasterInterfaceMutex);
if (!sLeAudioBroadcasterInterface) return;
sLeAudioBroadcasterInterface->StopBroadcast(broadcast_id);
@@ -1440,7 +1456,7 @@
static void PauseBroadcastNative(JNIEnv* /* env */, jobject /* object */,
jint broadcast_id) {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(sBroadcasterInterfaceMutex);
if (!sLeAudioBroadcasterInterface) return;
sLeAudioBroadcasterInterface->PauseBroadcast(broadcast_id);
@@ -1448,7 +1464,7 @@
static void DestroyBroadcastNative(JNIEnv* /* env */, jobject /* object */,
jint broadcast_id) {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(sBroadcasterInterfaceMutex);
if (!sLeAudioBroadcasterInterface) return;
sLeAudioBroadcasterInterface->DestroyBroadcast(broadcast_id);
@@ -1456,7 +1472,7 @@
static void getBroadcastMetadataNative(JNIEnv* /* env */, jobject /* object */,
jint broadcast_id) {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(sBroadcasterInterfaceMutex);
if (!sLeAudioBroadcasterInterface) return;
sLeAudioBroadcasterInterface->GetBroadcastMetadata(broadcast_id);
@@ -1609,6 +1625,7 @@
&method_onHealthBasedGroupRecommendationAction},
{"onUnicastMonitorModeStatus", "(II)V",
&method_onUnicastMonitorModeStatus},
+ {"onGroupStreamStatus", "(II)V", &method_onGroupStreamStatus},
};
GET_JAVA_METHODS(env, "com/android/bluetooth/le_audio/LeAudioNativeInterface",
javaMethods);
diff --git a/android/app/jni/com_android_bluetooth_pan.cpp b/android/app/jni/com_android_bluetooth_pan.cpp
index a216ebb..975f18a 100644
--- a/android/app/jni/com_android_bluetooth_pan.cpp
+++ b/android/app/jni/com_android_bluetooth_pan.cpp
@@ -16,23 +16,13 @@
#define LOG_TAG "BluetoothPanServiceJni"
+#include <cutils/log.h>
+#include <string.h>
+
#include "com_android_bluetooth.h"
#include "hardware/bt_pan.h"
#include "utils/Log.h"
-#include <string.h>
-
-#include <cutils/log.h>
-#define info(fmt, ...) ALOGI("%s(L%d): " fmt, __func__, __LINE__, ##__VA_ARGS__)
-#define debug(fmt, ...) \
- ALOGD("%s(L%d): " fmt, __func__, __LINE__, ##__VA_ARGS__)
-#define warn(fmt, ...) \
- ALOGW("## WARNING : %s(L%d): " fmt "##", __func__, __LINE__, ##__VA_ARGS__)
-#define error(fmt, ...) \
- ALOGE("## ERROR : %s(L%d): " fmt "##", __func__, __LINE__, ##__VA_ARGS__)
-#define asrt(s) \
- if (!(s)) ALOGE("## %s(L%d): ASSERT %s failed! ##", __func__, __LINE__, #s)
-
namespace android {
static jmethodID method_onConnectStateChanged;
@@ -47,7 +37,7 @@
jbyteArray addr = sCallbackEnv->NewByteArray(sizeof(RawAddress));
if (!addr) {
- ALOGE("Fail to new jbyteArray bd addr");
+ log::error("Fail to new jbyteArray bd addr");
return NULL;
}
sCallbackEnv->SetByteArrayRegion(addr, 0, sizeof(RawAddress),
@@ -57,9 +47,9 @@
static void control_state_callback(btpan_control_state_t state, int local_role,
bt_status_t error, const char* ifname) {
- debug("state:%d, local_role:%d, ifname:%s", state, local_role, ifname);
+ log::debug("state:{}, local_role:{}, ifname:{}", state, local_role, ifname);
if (mCallbacksObj == NULL) {
- error("Callbacks Obj is NULL: '%s", __func__);
+ log::error("Callbacks Obj is NULL");
return;
}
CallbackEnv sCallbackEnv(__func__);
@@ -75,17 +65,17 @@
bt_status_t error,
const RawAddress* bd_addr, int local_role,
int remote_role) {
- debug("state:%d, local_role:%d, remote_role:%d", state, local_role,
- remote_role);
+ log::debug("state:{}, local_role:{}, remote_role:{}", state, local_role,
+ remote_role);
if (mCallbacksObj == NULL) {
- error("Callbacks Obj is NULL: '%s", __func__);
+ log::error("Callbacks Obj is NULL");
return;
}
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid()) return;
ScopedLocalRef<jbyteArray> addr(sCallbackEnv.get(), marshall_bda(bd_addr));
if (!addr.get()) {
- error("Fail to new jbyteArray bd addr for PAN channel state");
+ log::error("Fail to new jbyteArray bd addr for PAN channel state");
return;
}
sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConnectStateChanged,
@@ -101,30 +91,30 @@
static const bt_interface_t* btIf;
static void initializeNative(JNIEnv* env, jobject object) {
- debug("Initialize pan");
+ log::debug("Initialize pan");
if (btIf) return;
btIf = getBluetoothInterface();
if (btIf == NULL) {
- error("Bluetooth module is not loaded");
+ log::error("Bluetooth module is not loaded");
return;
}
if (sPanIf != NULL) {
- ALOGW("Cleaning up Bluetooth PAN Interface before initializing...");
+ log::warn("Cleaning up Bluetooth PAN Interface before initializing...");
sPanIf->cleanup();
sPanIf = NULL;
}
if (mCallbacksObj != NULL) {
- ALOGW("Cleaning up Bluetooth PAN callback object");
+ log::warn("Cleaning up Bluetooth PAN callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = NULL;
}
sPanIf = (btpan_interface_t*)btIf->get_profile_interface(BT_PROFILE_PAN_ID);
if (sPanIf == NULL) {
- error("Failed to get Bluetooth PAN Interface");
+ log::error("Failed to get Bluetooth PAN Interface");
return;
}
@@ -132,10 +122,12 @@
bt_status_t status = sPanIf->init(&sBluetoothPanCallbacks);
if (status != BT_STATUS_SUCCESS) {
- error("Failed to initialize Bluetooth PAN, status: %d", status);
+ log::error("Failed to initialize Bluetooth PAN, status: {}",
+ bt_status_text(status));
sPanIf = NULL;
if (mCallbacksObj != NULL) {
- ALOGW("initialization failed: Cleaning up Bluetooth PAN callback object");
+ log::warn(
+ "initialization failed: Cleaning up Bluetooth PAN callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = NULL;
}
@@ -144,17 +136,17 @@
}
static void cleanupNative(JNIEnv* env, jobject /* object */) {
- debug("Cleanup pan");
+ log::debug("Cleanup pan");
if (!btIf) return;
if (sPanIf != NULL) {
- ALOGW("Cleaning up Bluetooth PAN Interface...");
+ log::warn("Cleaning up Bluetooth PAN Interface...");
sPanIf->cleanup();
sPanIf = NULL;
}
if (mCallbacksObj != NULL) {
- ALOGW("Cleaning up Bluetooth PAN callback object");
+ log::warn("Cleaning up Bluetooth PAN callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = NULL;
}
@@ -164,19 +156,20 @@
static jboolean connectPanNative(JNIEnv* env, jobject /* object */,
jbyteArray address, jint src_role,
jint dest_role) {
- debug("Connect pan");
+ log::debug("Connect pan");
if (!sPanIf) return JNI_FALSE;
jbyte* addr = env->GetByteArrayElements(address, NULL);
if (!addr) {
- error("Bluetooth device address null");
+ log::error("Bluetooth device address null");
return JNI_FALSE;
}
jboolean ret = JNI_TRUE;
bt_status_t status = sPanIf->connect((RawAddress*)addr, src_role, dest_role);
if (status != BT_STATUS_SUCCESS) {
- error("Failed PAN channel connection, status: %d", status);
+ log::error("Failed PAN channel connection, status: {}",
+ bt_status_text(status));
ret = JNI_FALSE;
}
env->ReleaseByteArrayElements(address, addr, 0);
@@ -186,19 +179,20 @@
static jboolean disconnectPanNative(JNIEnv* env, jobject /* object */,
jbyteArray address) {
- debug("Disconnects pan");
+ log::debug("Disconnects pan");
if (!sPanIf) return JNI_FALSE;
jbyte* addr = env->GetByteArrayElements(address, NULL);
if (!addr) {
- error("Bluetooth device address null");
+ log::error("Bluetooth device address null");
return JNI_FALSE;
}
jboolean ret = JNI_TRUE;
bt_status_t status = sPanIf->disconnect((RawAddress*)addr);
if (status != BT_STATUS_SUCCESS) {
- error("Failed disconnect pan channel, status: %d", status);
+ log::error("Failed disconnect pan channel, status: {}",
+ bt_status_text(status));
ret = JNI_FALSE;
}
env->ReleaseByteArrayElements(address, addr, 0);
diff --git a/android/app/jni/com_android_bluetooth_sdp.cpp b/android/app/jni/com_android_bluetooth_sdp.cpp
index 62ee16a..206cb44 100644
--- a/android/app/jni/com_android_bluetooth_sdp.cpp
+++ b/android/app/jni/com_android_bluetooth_sdp.cpp
@@ -55,11 +55,11 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == NULL) {
- ALOGE("Bluetooth module is not loaded");
+ log::error("Bluetooth module is not loaded");
return;
}
if (sBluetoothSdpInterface != NULL) {
- ALOGW("Cleaning up Bluetooth SDP Interface before initializing...");
+ log::warn("Cleaning up Bluetooth SDP Interface before initializing...");
sBluetoothSdpInterface->deinit();
sBluetoothSdpInterface = NULL;
}
@@ -67,7 +67,7 @@
sBluetoothSdpInterface = (btsdp_interface_t*)btInf->get_profile_interface(
BT_PROFILE_SDP_CLIENT_ID);
if (sBluetoothSdpInterface == NULL) {
- ALOGE("Error getting SDP client interface");
+ log::error("Error getting SDP client interface");
} else {
sBluetoothSdpInterface->init(&sBluetoothSdpCallbacks);
}
@@ -77,7 +77,7 @@
static jboolean sdpSearchNative(JNIEnv* env, jobject /* obj */,
jbyteArray address, jbyteArray uuidObj) {
- ALOGD("%s", __func__);
+ log::debug("");
if (!sBluetoothSdpInterface) return JNI_FALSE;
@@ -87,22 +87,22 @@
return JNI_FALSE;
}
- jbyte* uuid = env->GetByteArrayElements(uuidObj, NULL);
- if (!uuid) {
- ALOGE("failed to get uuid");
+ jbyte* raw_uuid = env->GetByteArrayElements(uuidObj, NULL);
+ if (!raw_uuid) {
+ log::error("failed to get uuid");
env->ReleaseByteArrayElements(address, addr, 0);
return JNI_FALSE;
}
- ALOGD("%s UUID %.*s", __func__, 16, (uint8_t*)uuid);
+ Uuid uuid = Uuid::From128BitBE((uint8_t*)raw_uuid);
+ log::debug("UUID {}", uuid);
- int ret = sBluetoothSdpInterface->sdp_search(
- (RawAddress*)addr, Uuid::From128BitBE((uint8_t*)uuid));
+ int ret = sBluetoothSdpInterface->sdp_search((RawAddress*)addr, uuid);
if (ret != BT_STATUS_SUCCESS) {
- ALOGE("SDP Search initialization failed: %d", ret);
+ log::error("SDP Search initialization failed: {}", ret);
}
if (addr) env->ReleaseByteArrayElements(address, addr, 0);
- if (uuid) env->ReleaseByteArrayElements(uuidObj, uuid, 0);
+ if (raw_uuid) env->ReleaseByteArrayElements(uuidObj, raw_uuid, 0);
return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
}
@@ -125,7 +125,7 @@
sCallbackEnv->SetByteArrayRegion(uuid.get(), 0, sizeof(Uuid),
(const jbyte*)uuid_in.To128BitBE().data());
- ALOGD("%s: Status is: %d, Record count: %d", __func__, status, count);
+ log::debug("Status is: {}, Record count: {}", bt_status_text(status), count);
// Ensure we run the loop at least once, to also signal errors if they occur
for (int i = 0; i < count || i == 0; i++) {
@@ -133,7 +133,7 @@
bluetooth_sdp_record* record = &records[i];
ScopedLocalRef<jstring> service_name(sCallbackEnv.get(), NULL);
if (record->hdr.service_name_length > 0) {
- ALOGD("%s, ServiceName: %s", __func__, record->mas.hdr.service_name);
+ log::debug("ServiceName: {}", record->mas.hdr.service_name);
service_name.reset(
(jstring)sCallbackEnv->NewStringUTF(record->mas.hdr.service_name));
}
@@ -192,7 +192,7 @@
(jint)record->mas.hdr.profile_version, service_name.get(),
more_results);
} else if (uuid_in == UUID_DIP) {
- ALOGD("%s, Get UUID_DIP", __func__);
+ log::debug("Get UUID_DIP");
sCallbackEnv->CallVoidMethod(
sCallbacksObj, method_sdpDipRecordFoundCallback, (jint)status,
addr.get(), uuid.get(), (jint)record->dip.spec_id,
@@ -222,7 +222,7 @@
jstring name_str, jint mas_id, jint scn,
jint l2cap_psm, jint version,
jint msg_types, jint features) {
- ALOGD("%s", __func__);
+ log::debug("");
if (!sBluetoothSdpInterface) return -1;
bluetooth_sdp_record record = {}; // Must be zero initialized
@@ -248,9 +248,9 @@
int handle = -1;
int ret = sBluetoothSdpInterface->create_sdp_record(&record, &handle);
if (ret != BT_STATUS_SUCCESS) {
- ALOGE("SDP Create record failed: %d", ret);
+ log::error("SDP Create record failed: {}", ret);
} else {
- ALOGD("SDP Create record success - handle: %d", handle);
+ log::debug("SDP Create record success - handle: {}", handle);
}
if (service_name) env->ReleaseStringUTFChars(name_str, service_name);
@@ -261,7 +261,7 @@
jstring name_str, jint scn,
jint l2cap_psm, jint version,
jint features) {
- ALOGD("%s", __func__);
+ log::debug("");
if (!sBluetoothSdpInterface) return -1;
bluetooth_sdp_record record = {}; // Must be zero initialized
@@ -285,9 +285,9 @@
int handle = -1;
int ret = sBluetoothSdpInterface->create_sdp_record(&record, &handle);
if (ret != BT_STATUS_SUCCESS) {
- ALOGE("SDP Create record failed: %d", ret);
+ log::error("SDP Create record failed: {}", ret);
} else {
- ALOGD("SDP Create record success - handle: %d", handle);
+ log::debug("SDP Create record success - handle: {}", handle);
}
if (service_name) env->ReleaseStringUTFChars(name_str, service_name);
@@ -296,7 +296,7 @@
static jint sdpCreatePbapPceRecordNative(JNIEnv* env, jobject /* obj */,
jstring name_str, jint version) {
- ALOGD("%s", __func__);
+ log::debug("");
if (!sBluetoothSdpInterface) return -1;
bluetooth_sdp_record record = {}; // Must be zero initialized
@@ -316,9 +316,9 @@
int handle = -1;
int ret = sBluetoothSdpInterface->create_sdp_record(&record, &handle);
if (ret != BT_STATUS_SUCCESS) {
- ALOGE("SDP Create record failed: %d", ret);
+ log::error("SDP Create record failed: {}", ret);
} else {
- ALOGD("SDP Create record success - handle: %d", handle);
+ log::debug("SDP Create record success - handle: {}", handle);
}
if (service_name) env->ReleaseStringUTFChars(name_str, service_name);
@@ -330,7 +330,7 @@
jint l2cap_psm, jint version,
jint supported_repositories,
jint features) {
- ALOGD("%s", __func__);
+ log::debug("");
if (!sBluetoothSdpInterface) return -1;
bluetooth_sdp_record record = {}; // Must be zero initialized
@@ -355,9 +355,9 @@
int handle = -1;
int ret = sBluetoothSdpInterface->create_sdp_record(&record, &handle);
if (ret != BT_STATUS_SUCCESS) {
- ALOGE("SDP Create record failed: %d", ret);
+ log::error("SDP Create record failed: {}", ret);
} else {
- ALOGD("SDP Create record success - handle: %d", handle);
+ log::debug("SDP Create record success - handle: {}", handle);
}
if (service_name) env->ReleaseStringUTFChars(name_str, service_name);
@@ -368,7 +368,7 @@
jstring name_str, jint scn,
jint l2cap_psm, jint version,
jbyteArray supported_formats_list) {
- ALOGD("%s", __func__);
+ log::debug("");
if (!sBluetoothSdpInterface) return -1;
bluetooth_sdp_record record = {}; // Must be zero initialized
@@ -402,9 +402,9 @@
int handle = -1;
int ret = sBluetoothSdpInterface->create_sdp_record(&record, &handle);
if (ret != BT_STATUS_SUCCESS) {
- ALOGE("SDP Create record failed: %d", ret);
+ log::error("SDP Create record failed: {}", ret);
} else {
- ALOGD("SDP Create record success - handle: %d", handle);
+ log::debug("SDP Create record success - handle: {}", handle);
}
if (service_name) env->ReleaseStringUTFChars(name_str, service_name);
@@ -416,7 +416,7 @@
static jint sdpCreateSapsRecordNative(JNIEnv* env, jobject /* obj */,
jstring name_str, jint scn,
jint version) {
- ALOGD("%s", __func__);
+ log::debug("");
if (!sBluetoothSdpInterface) return -1;
bluetooth_sdp_record record = {}; // Must be zero initialized
@@ -437,9 +437,9 @@
int handle = -1;
int ret = sBluetoothSdpInterface->create_sdp_record(&record, &handle);
if (ret != BT_STATUS_SUCCESS) {
- ALOGE("SDP Create record failed: %d", ret);
+ log::error("SDP Create record failed: {}", ret);
} else {
- ALOGD("SDP Create record success - handle: %d", handle);
+ log::debug("SDP Create record success - handle: {}", handle);
}
if (service_name) env->ReleaseStringUTFChars(name_str, service_name);
@@ -448,16 +448,16 @@
static jboolean sdpRemoveSdpRecordNative(JNIEnv* /* env */, jobject /* obj */,
jint record_id) {
- ALOGD("%s", __func__);
+ log::debug("");
if (!sBluetoothSdpInterface) return false;
int ret = sBluetoothSdpInterface->remove_sdp_record(record_id);
if (ret != BT_STATUS_SUCCESS) {
- ALOGE("SDP Remove record failed: %d", ret);
+ log::error("SDP Remove record failed: {}", ret);
return false;
}
- ALOGD("SDP Remove record success - handle: %d", record_id);
+ log::debug("SDP Remove record success - handle: {}", record_id);
return true;
}
@@ -465,18 +465,18 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == NULL) {
- ALOGE("Bluetooth module is not loaded");
+ log::error("Bluetooth module is not loaded");
return;
}
if (sBluetoothSdpInterface != NULL) {
- ALOGW("Cleaning up Bluetooth SDP Interface...");
+ log::warn("Cleaning up Bluetooth SDP Interface...");
sBluetoothSdpInterface->deinit();
sBluetoothSdpInterface = NULL;
}
if (sCallbacksObj != NULL) {
- ALOGW("Cleaning up Bluetooth SDP object");
+ log::warn("Cleaning up Bluetooth SDP object");
env->DeleteGlobalRef(sCallbacksObj);
sCallbacksObj = NULL;
}
diff --git a/android/app/jni/com_android_bluetooth_vc.cpp b/android/app/jni/com_android_bluetooth_vc.cpp
index 60cd30e..26dee38 100644
--- a/android/app/jni/com_android_bluetooth_vc.cpp
+++ b/android/app/jni/com_android_bluetooth_vc.cpp
@@ -48,8 +48,8 @@
~VolumeControlCallbacksImpl() = default;
void OnConnectionState(ConnectionState state,
const RawAddress& bd_addr) override {
- LOG(INFO) << __func__ << ", state:" << int(state)
- << ", addr: " << bd_addr.ToRedactedStringForLogging();
+ log::info("state:{}, addr: {}", int(state),
+ bd_addr.ToRedactedStringForLogging());
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -58,7 +58,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new jbyteArray bd addr for connection state";
+ log::error("Failed to new jbyteArray bd addr for connection state");
return;
}
@@ -70,7 +70,7 @@
void OnVolumeStateChanged(const RawAddress& bd_addr, uint8_t volume,
bool mute, bool isAutonomous) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -79,7 +79,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new jbyteArray bd addr for connection state";
+ log::error("Failed to new jbyteArray bd addr for connection state");
return;
}
@@ -91,7 +91,7 @@
void OnGroupVolumeStateChanged(int group_id, uint8_t volume,
bool mute, bool isAutonomous) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -104,7 +104,7 @@
void OnDeviceAvailable(const RawAddress& bd_addr,
uint8_t num_offsets) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -113,7 +113,7 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new jbyteArray bd addr for onDeviceAvailable";
+ log::error("Failed to new jbyteArray bd addr for onDeviceAvailable");
return;
}
@@ -126,7 +126,7 @@
void OnExtAudioOutVolumeOffsetChanged(const RawAddress& bd_addr,
uint8_t ext_output_id,
int16_t offset) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -135,8 +135,9 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new jbyteArray bd addr for "
- "OnExtAudioOutVolumeOffsetChanged";
+ log::error(
+ "Failed to new jbyteArray bd addr for "
+ "OnExtAudioOutVolumeOffsetChanged");
return;
}
@@ -150,7 +151,7 @@
void OnExtAudioOutLocationChanged(const RawAddress& bd_addr,
uint8_t ext_output_id,
uint32_t location) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -159,8 +160,8 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new jbyteArray bd addr for "
- "OnExtAudioOutLocationChanged";
+ log::error(
+ "Failed to new jbyteArray bd addr for OnExtAudioOutLocationChanged");
return;
}
@@ -174,7 +175,7 @@
void OnExtAudioOutDescriptionChanged(const RawAddress& bd_addr,
uint8_t ext_output_id,
std::string descr) override {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
@@ -183,8 +184,9 @@
ScopedLocalRef<jbyteArray> addr(
sCallbackEnv.get(), sCallbackEnv->NewByteArray(sizeof(RawAddress)));
if (!addr.get()) {
- LOG(ERROR) << "Failed to new jbyteArray bd addr for "
- "OnExtAudioOutDescriptionChanged";
+ log::error(
+ "Failed to new jbyteArray bd addr for "
+ "OnExtAudioOutDescriptionChanged");
return;
}
@@ -205,31 +207,31 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == nullptr) {
- LOG(ERROR) << "Bluetooth module is not loaded";
+ log::error("Bluetooth module is not loaded");
return;
}
if (sVolumeControlInterface != nullptr) {
- LOG(INFO) << "Cleaning up VolumeControl Interface before initializing...";
+ log::info("Cleaning up VolumeControl Interface before initializing...");
sVolumeControlInterface->Cleanup();
sVolumeControlInterface = nullptr;
}
if (mCallbacksObj != nullptr) {
- LOG(INFO) << "Cleaning up VolumeControl callback object";
+ log::info("Cleaning up VolumeControl callback object");
env->DeleteGlobalRef(mCallbacksObj);
mCallbacksObj = nullptr;
}
if ((mCallbacksObj = env->NewGlobalRef(object)) == nullptr) {
- LOG(ERROR) << "Failed to allocate Global Ref for Volume control Callbacks";
+ log::error("Failed to allocate Global Ref for Volume control Callbacks");
return;
}
sVolumeControlInterface =
(VolumeControlInterface*)btInf->get_profile_interface(BT_PROFILE_VC_ID);
if (sVolumeControlInterface == nullptr) {
- LOG(ERROR) << "Failed to get Bluetooth Volume Control Interface";
+ log::error("Failed to get Bluetooth Volume Control Interface");
return;
}
@@ -242,7 +244,7 @@
const bt_interface_t* btInf = getBluetoothInterface();
if (btInf == nullptr) {
- LOG(ERROR) << "Bluetooth module is not loaded";
+ log::error("Bluetooth module is not loaded");
return;
}
@@ -259,12 +261,11 @@
static jboolean connectVolumeControlNative(JNIEnv* env, jobject /* object */,
jbyteArray address) {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sVolumeControlInterface) {
- LOG(ERROR) << __func__
- << ": Failed to get the Bluetooth Volume Control Interface";
+ log::error("Failed to get the Bluetooth Volume Control Interface");
return JNI_FALSE;
}
@@ -282,12 +283,11 @@
static jboolean disconnectVolumeControlNative(JNIEnv* env, jobject /* object */,
jbyteArray address) {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sVolumeControlInterface) {
- LOG(ERROR) << __func__
- << ": Failed to get the Bluetooth Volume Control Interface";
+ log::error("Failed to get the Bluetooth Volume Control Interface");
return JNI_FALSE;
}
@@ -306,8 +306,7 @@
static void setVolumeNative(JNIEnv* env, jobject /* object */,
jbyteArray address, jint volume) {
if (!sVolumeControlInterface) {
- LOG(ERROR) << __func__
- << ": Failed to get the Bluetooth Volume Control Interface";
+ log::error("Failed to get the Bluetooth Volume Control Interface");
return;
}
@@ -325,8 +324,7 @@
static void setGroupVolumeNative(JNIEnv* /* env */, jobject /* object */,
jint group_id, jint volume) {
if (!sVolumeControlInterface) {
- LOG(ERROR) << __func__
- << ": Failed to get the Bluetooth Volume Control Interface";
+ log::error("Failed to get the Bluetooth Volume Control Interface");
return;
}
@@ -335,8 +333,7 @@
static void muteNative(JNIEnv* env, jobject /* object */, jbyteArray address) {
if (!sVolumeControlInterface) {
- LOG(ERROR) << __func__
- << ": Failed to get the Bluetooth Volume Control Interface";
+ log::error("Failed to get the Bluetooth Volume Control Interface");
return;
}
@@ -354,8 +351,7 @@
static void muteGroupNative(JNIEnv* /* env */, jobject /* object */,
jint group_id) {
if (!sVolumeControlInterface) {
- LOG(ERROR) << __func__
- << ": Failed to get the Bluetooth Volume Control Interface";
+ log::error("Failed to get the Bluetooth Volume Control Interface");
return;
}
sVolumeControlInterface->Mute(group_id);
@@ -364,8 +360,7 @@
static void unmuteNative(JNIEnv* env, jobject /* object */,
jbyteArray address) {
if (!sVolumeControlInterface) {
- LOG(ERROR) << __func__
- << ": Failed to get the Bluetooth Volume Control Interface";
+ log::error("Failed to get the Bluetooth Volume Control Interface");
return;
}
@@ -383,8 +378,7 @@
static void unmuteGroupNative(JNIEnv* /* env */, jobject /* object */,
jint group_id) {
if (!sVolumeControlInterface) {
- LOG(ERROR) << __func__
- << ": Failed to get the Bluetooth Volume Control Interface";
+ log::error("Failed to get the Bluetooth Volume Control Interface");
return;
}
sVolumeControlInterface->Unmute(group_id);
@@ -395,7 +389,7 @@
jobject /* object */,
jbyteArray address,
jint ext_output_id) {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sVolumeControlInterface) return JNI_FALSE;
@@ -416,7 +410,7 @@
jbyteArray address,
jint ext_output_id,
jint offset) {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sVolumeControlInterface) return JNI_FALSE;
@@ -436,7 +430,7 @@
static jboolean getExtAudioOutLocationNative(JNIEnv* env, jobject /* object */,
jbyteArray address,
jint ext_output_id) {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sVolumeControlInterface) return JNI_FALSE;
@@ -456,7 +450,7 @@
jbyteArray address,
jint ext_output_id,
jint location) {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sVolumeControlInterface) return JNI_FALSE;
@@ -477,7 +471,7 @@
jobject /* object */,
jbyteArray address,
jint ext_output_id) {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sVolumeControlInterface) return JNI_FALSE;
@@ -498,7 +492,7 @@
jbyteArray address,
jint ext_output_id,
jstring descr) {
- LOG(INFO) << __func__;
+ log::info("");
std::shared_lock<std::shared_timed_mutex> lock(interface_mutex);
if (!sVolumeControlInterface) return JNI_FALSE;
diff --git a/android/app/res/drawable/ic_bluetooth_settings.xml b/android/app/res/drawable/ic_bluetooth_settings.xml
new file mode 100644
index 0000000..00678fb
--- /dev/null
+++ b/android/app/res/drawable/ic_bluetooth_settings.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="960"
+ android:viewportHeight="960">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M450,472.15L277.08,645.08Q268.77,653.38 256.19,653.58Q243.62,653.77 234.92,645.08Q226.23,636.38 226.23,624Q226.23,611.62 234.92,602.92L437.85,400L234.92,197.08Q226.62,188.77 226.42,176.19Q226.23,163.62 234.92,154.92Q243.62,146.23 256,146.23Q268.38,146.23 277.08,154.92L450,327.85L450,71.23Q450,54.77 461.04,44.62Q472.08,34.46 486.15,34.46Q493,34.46 499.42,37.08Q505.85,39.69 511.46,45.31L668.84,202.69Q674.46,208.31 676.77,214.54Q679.08,220.77 679.08,228Q679.08,235.23 676.77,241.46Q674.46,247.69 668.84,253.31L522.15,400L668.84,546.69Q674.46,552.31 676.77,558.54Q679.08,564.77 679.08,572Q679.08,579.23 676.77,585.46Q674.46,591.69 668.84,597.31L511.46,754.69Q505.85,760.31 499.42,762.92Q493,765.54 486.15,765.54Q472.08,765.54 461.04,755.38Q450,745.23 450,728.77L450,472.15ZM510,670.62L609.85,572L510,472.15L510,670.62ZM510,327.85L609.85,228L510,129.38L510,327.85ZM320,955.38Q305.31,955.38 294.96,945.04Q284.62,934.69 284.62,920Q284.62,905.31 294.96,894.96Q305.31,884.62 320,884.62Q334.69,884.62 345.04,894.96Q355.38,905.31 355.38,920Q355.38,934.69 345.04,945.04Q334.69,955.38 320,955.38ZM480,955.38Q465.31,955.38 454.96,945.04Q444.62,934.69 444.62,920Q444.62,905.31 454.96,894.96Q465.31,884.62 480,884.62Q494.69,884.62 505.04,894.96Q515.38,905.31 515.38,920Q515.38,934.69 505.04,945.04Q494.69,955.38 480,955.38ZM640,955.38Q625.31,955.38 614.96,945.04Q604.62,934.69 604.62,920Q604.62,905.31 614.96,894.96Q625.31,884.62 640,884.62Q654.69,884.62 665.04,894.96Q675.38,905.31 675.38,920Q675.38,934.69 665.04,945.04Q654.69,955.38 640,955.38Z" />
+</vector>
diff --git a/android/app/res/values/strings.xml b/android/app/res/values/strings.xml
index 78a3dd6..fe34075 100644
--- a/android/app/res/values/strings.xml
+++ b/android/app/res/values/strings.xml
@@ -256,4 +256,8 @@
<string name="bluetooth_stays_on_message">Your device remembers to keep Bluetooth on in airplane mode. Turn off Bluetooth if you don\'t want it to stay on.</string>
<string name="bluetooth_and_wifi_stays_on_title">Wi-Fi and Bluetooth stay on</string>
<string name="bluetooth_and_wifi_stays_on_message">Your device remembers to keep Wi-Fi and Bluetooth on in airplane mode. Turn off Wi-Fi and Bluetooth if you don\'t want them to stay on.</string>
+ <string name="bluetooth_enabled_auto_on_title">Bluetooth has been automatically enabled</string>
+ <string name="bluetooth_enabled_auto_on_message">Automatic restart can be toggled in Bluetooth Settings.</string>
+ <string name="bluetooth_disable_auto_on">Turn off</string>
+ <string name="bluetooth_notification_group">Bluetooth automatic state change</string>
</resources>
diff --git a/android/app/src/com/android/bluetooth/ObexServerSockets.java b/android/app/src/com/android/bluetooth/ObexServerSockets.java
index 1b6864b..2b1c9d6 100644
--- a/android/app/src/com/android/bluetooth/ObexServerSockets.java
+++ b/android/app/src/com/android/bluetooth/ObexServerSockets.java
@@ -47,9 +47,8 @@
* In both cases the {@link ObexServerSockets} object have terminated, and a new must be created.
*/
public class ObexServerSockets {
- private final String mTag;
- private static final String STAG = "ObexServerSockets";
- private static final boolean D = true; // TODO: set to false!
+ private static final String TAG = "ObexServerSockets";
+ private static final boolean D = true; // TODO: set this to false!
private final IObexConnectionHandler mConHandler;
/* The wrapped sockets */
@@ -66,7 +65,6 @@
mConHandler = conHandler;
mRfcommSocket = rfcommSocket;
mL2capSocket = l2capSocket;
- mTag = "ObexServerSockets" + sInstanceCounter.getAndIncrement();
}
/**
@@ -113,7 +111,7 @@
private static ObexServerSockets create(IObexConnectionHandler validator, int rfcommChannel,
int l2capPsm, boolean isSecure) {
if (D) {
- Log.d(STAG, "create(rfcomm = " + rfcommChannel + ", l2capPsm = " + l2capPsm + ")");
+ Log.d(TAG, "create(rfcomm = " + rfcommChannel + ", l2capPsm = " + l2capPsm + ")");
}
BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter();
if (bt == null) {
@@ -142,10 +140,10 @@
}
}
} catch (IOException e) {
- Log.e(STAG, "Error create ServerSockets ", e);
+ Log.e(TAG, "Error create ServerSockets ", e);
initSocketOK = false;
} catch (SecurityException e) {
- Log.e(STAG, "Error create ServerSockets ", e);
+ Log.e(TAG, "Error create ServerSockets ", e);
initSocketOK = false;
break;
}
@@ -154,16 +152,16 @@
int state = bt.getState();
if ((state != BluetoothAdapter.STATE_TURNING_ON) && (state
!= BluetoothAdapter.STATE_ON)) {
- Log.w(STAG, "initServerSockets failed as BT is (being) turned off");
+ Log.w(TAG, "initServerSockets failed as BT is (being) turned off");
break;
}
try {
if (D) {
- Log.v(STAG, "waiting 300 ms...");
+ Log.v(TAG, "waiting 300 ms...");
}
Thread.sleep(300);
} catch (InterruptedException e) {
- Log.e(STAG, "create() was interrupted");
+ Log.e(TAG, "create() was interrupted");
}
} else {
break;
@@ -172,13 +170,13 @@
if (initSocketOK) {
if (D) {
- Log.d(STAG, "Succeed to create listening sockets ");
+ Log.d(TAG, "Succeed to create listening sockets ");
}
ObexServerSockets sockets = new ObexServerSockets(validator, rfcommSocket, l2capSocket);
sockets.startAccept();
return sockets;
} else {
- Log.e(STAG, "Error to create listening socket after " + CREATE_RETRY_TIME + " try");
+ Log.e(TAG, "Error to create listening socket after " + CREATE_RETRY_TIME + " try");
return null;
}
}
@@ -207,9 +205,7 @@
* the {@link IObexConnectionValidator#onConnect()}, at which point both threads will exit.
*/
private void startAccept() {
- if (D) {
- Log.d(mTag, "startAccept()");
- }
+ Log.d(TAG, "startAccept()");
mRfcommThread = new SocketAcceptThread(mRfcommSocket);
mRfcommThread.start();
@@ -225,9 +221,7 @@
* @return true if the connection is accepted, false otherwise.
*/
private synchronized boolean onConnect(BluetoothDevice device, BluetoothSocket conSocket) {
- if (D) {
- Log.d(mTag, "onConnect() socket: " + conSocket);
- }
+ Log.d(TAG, "onConnect() socket: " + conSocket);
return mConHandler.onConnect(device, conSocket);
}
@@ -238,7 +232,7 @@
shutdown(false);
BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
if ((mAdapter != null) && (mAdapter.getState() == BluetoothAdapter.STATE_ON)) {
- Log.d(mTag, "onAcceptFailed() calling shutdown...");
+ Log.d(TAG, "onAcceptFailed() calling shutdown...");
mConHandler.onAcceptFailed();
}
}
@@ -249,9 +243,7 @@
* has ended execution
*/
public synchronized void shutdown(boolean block) {
- if (D) {
- Log.d(mTag, "shutdown(block = " + block + ")");
- }
+ Log.d(TAG, "shutdown(block = " + block + ")");
if (mRfcommThread != null) {
mRfcommThread.shutdown();
}
@@ -270,7 +262,7 @@
mL2capThread = null;
}
} catch (InterruptedException e) {
- Log.i(mTag, "shutdown() interrupted, continue waiting...", e);
+ Log.i(TAG, "shutdown() interrupted, continue waiting...", e);
}
}
} else {
@@ -314,28 +306,24 @@
BluetoothDevice device;
try {
- if (D) {
- Log.d(mTag, "Accepting socket connection...");
- }
+ Log.d(TAG, "Accepting socket connection...");
connSocket = mServerSocket.accept();
- if (D) {
- Log.d(mTag, "Accepted socket connection from: " + mServerSocket);
- }
+ Log.d(TAG, "Accepted socket connection from: " + mServerSocket);
if (connSocket == null) {
// TODO: Do we need a max error count, to avoid spinning?
- Log.w(mTag, "connSocket is null - reattempt accept");
+ Log.w(TAG, "connSocket is null - reattempt accept");
continue;
}
device = connSocket.getRemoteDevice();
if (device == null) {
- Log.i(mTag, "getRemoteDevice() = null - reattempt accept");
+ Log.i(TAG, "getRemoteDevice() = null - reattempt accept");
try {
connSocket.close();
} catch (IOException e) {
- Log.w(mTag, "Error closing the socket. ignoring...", e);
+ Log.w(TAG, "Error closing the socket. ignoring...", e);
}
continue;
}
@@ -348,7 +336,7 @@
/* Close connection if we already have a connection with another device
* by responding to the OBEX connect request.
*/
- Log.i(mTag, "RemoteDevice is invalid - creating ObexRejectServer.");
+ Log.i(TAG, "RemoteDevice is invalid - creating ObexRejectServer.");
BluetoothObexTransport obexTrans =
new BluetoothObexTransport(connSocket);
// Create and detach a selfdestructing ServerSession to respond to any
@@ -364,16 +352,14 @@
if (mStopped) {
// Expected exception because of shutdown.
} else {
- Log.w(mTag, "Accept exception for " + mServerSocket, ex);
+ Log.w(TAG, "Accept exception for " + mServerSocket, ex);
ObexServerSockets.this.onAcceptFailed();
}
mStopped = true;
}
} // End while()
} finally {
- if (D) {
- Log.d(mTag, "AcceptThread ended for: " + mServerSocket);
- }
+ Log.d(TAG, "AcceptThread ended for: " + mServerSocket);
}
}
@@ -391,18 +377,14 @@
try {
mServerSocket.close();
} catch (IOException e) {
- if (D) {
- Log.d(mTag, "Exception while thread shutdown:", e);
- }
+ Log.w(TAG, "Exception while thread shutdown:", e);
}
}
// If called from another thread, interrupt the thread
if (!Thread.currentThread().equals(this)) {
// TODO: Will this interrupt the thread if it is blocked in synchronized?
// Else: change to use InterruptableLock
- if (D) {
- Log.d(mTag, "shutdown called from another thread - interrupt().");
- }
+ Log.d(TAG, "shutdown called from another thread - interrupt().");
interrupt();
}
}
diff --git a/android/app/src/com/android/bluetooth/Utils.java b/android/app/src/com/android/bluetooth/Utils.java
index 3e686bb..8ce32f5 100644
--- a/android/app/src/com/android/bluetooth/Utils.java
+++ b/android/app/src/com/android/bluetooth/Utils.java
@@ -189,6 +189,23 @@
return String.format("XX:XX:XX:XX:%02X:%02X", address[4], address[5]);
}
+ /**
+ * Returns the correct device address to be used for connections over BR/EDR transport.
+ *
+ * @param device the device for which to obtain the connection address
+ * @return either identity address or device address as a byte array
+ */
+ public static byte[] getByteBrEdrAddress(BluetoothDevice device) {
+ final AdapterService service = AdapterService.getAdapterService();
+ // If dual mode device bonded over BLE first, BR/EDR address will be identity address
+ // Otherwise, BR/EDR address will be same address as in BluetoothDevice#getAddress
+ byte[] address = service.getByteIdentityAddress(device);
+ if (address == null) {
+ address = getByteAddress(device);
+ }
+ return address;
+ }
+
public static byte[] getByteAddress(BluetoothDevice device) {
return getBytesFromAddress(device.getAddress());
}
diff --git a/android/app/src/com/android/bluetooth/a2dp/A2dpNativeInterface.java b/android/app/src/com/android/bluetooth/a2dp/A2dpNativeInterface.java
index 000229b..6c52b2b 100644
--- a/android/app/src/com/android/bluetooth/a2dp/A2dpNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/a2dp/A2dpNativeInterface.java
@@ -31,6 +31,7 @@
import com.android.bluetooth.Utils;
import com.android.bluetooth.btservice.AdapterService;
+import com.android.bluetooth.flags.Flags;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
@@ -173,7 +174,11 @@
if (device == null) {
return Utils.getBytesFromAddress("00:00:00:00:00:00");
}
- return mAdapterService.getByteIdentityAddress(device);
+ if (Flags.identityAddressNullIfUnknown()) {
+ return Utils.getByteBrEdrAddress(device);
+ } else {
+ return mAdapterService.getByteIdentityAddress(device);
+ }
}
private void sendMessageToService(A2dpStackEvent event) {
diff --git a/android/app/src/com/android/bluetooth/a2dp/A2dpService.java b/android/app/src/com/android/bluetooth/a2dp/A2dpService.java
index 2cb65a3..cc98537 100644
--- a/android/app/src/com/android/bluetooth/a2dp/A2dpService.java
+++ b/android/app/src/com/android/bluetooth/a2dp/A2dpService.java
@@ -141,14 +141,17 @@
return BluetoothProperties.isProfileA2dpSourceEnabled().orElse(false);
}
- @Override
- protected IProfileServiceBinder initBinder() {
- return new BluetoothA2dpBinder(
- this, AdapterService.getAdapterService().getActiveDeviceManager());
+ ActiveDeviceManager getActiveDeviceManager() {
+ return mAdapterService.getActiveDeviceManager();
}
@Override
- protected void start() {
+ protected IProfileServiceBinder initBinder() {
+ return new BluetoothA2dpBinder(this);
+ }
+
+ @Override
+ public void start() {
Log.i(TAG, "start()");
if (sA2dpService != null) {
throw new IllegalStateException("start() called twice");
@@ -205,7 +208,7 @@
}
@Override
- protected void stop() {
+ public void stop() {
Log.i(TAG, "stop()");
if (sA2dpService == null) {
Log.w(TAG, "stop() called before start()");
@@ -259,7 +262,7 @@
}
@Override
- protected void cleanup() {
+ public void cleanup() {
Log.i(TAG, "cleanup()");
}
@@ -1372,7 +1375,6 @@
static class BluetoothA2dpBinder extends IBluetoothA2dp.Stub
implements IProfileServiceBinder {
private A2dpService mService;
- private ActiveDeviceManager mActiveDeviceManager;
@RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)
private A2dpService getService(AttributionSource source) {
@@ -1387,9 +1389,8 @@
return mService;
}
- BluetoothA2dpBinder(A2dpService svc, ActiveDeviceManager activeDeviceManager) {
+ BluetoothA2dpBinder(A2dpService svc) {
mService = svc;
- mActiveDeviceManager = activeDeviceManager;
}
@Override
@@ -1479,7 +1480,7 @@
A2dpService service = getService(source);
if (service != null) {
if (Flags.audioRoutingCentralization()) {
- ((AudioRoutingManager) mActiveDeviceManager)
+ ((AudioRoutingManager) service.getActiveDeviceManager())
.activateDeviceProfile(device, BluetoothProfile.A2DP, receiver);
} else {
boolean result;
diff --git a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface.java b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface.java
index e61d8da..08c1247 100644
--- a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface.java
@@ -21,6 +21,7 @@
import com.android.bluetooth.Utils;
import com.android.bluetooth.btservice.AdapterService;
+import com.android.bluetooth.flags.Flags;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
@@ -85,7 +86,11 @@
}
private byte[] getByteAddress(BluetoothDevice device) {
- return mAdapterService.getByteIdentityAddress(device);
+ if (Flags.identityAddressNullIfUnknown()) {
+ return Utils.getByteBrEdrAddress(device);
+ } else {
+ return mAdapterService.getByteIdentityAddress(device);
+ }
}
/**
diff --git a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java
index 465efda..c823b76 100644
--- a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java
+++ b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java
@@ -92,7 +92,7 @@
}
@Override
- protected void start() {
+ public void start() {
mAdapterService =
requireNonNull(
AdapterService.getAdapterService(),
@@ -113,7 +113,7 @@
}
@Override
- protected void stop() {
+ public void stop() {
setA2dpSinkService(null);
mNativeInterface.cleanup();
for (A2dpSinkStateMachine stateMachine : mDeviceStateMap.values()) {
@@ -636,6 +636,13 @@
return;
}
A2dpSinkStateMachine stateMachine = getStateMachineForDevice(device);
+ if (stateMachine == null) {
+ Log.w(
+ TAG,
+ "Received audio config changed event for an unconnected device, device="
+ + device);
+ return;
+ }
stateMachine.onStackEvent(event);
}
diff --git a/android/app/src/com/android/bluetooth/audio_util/MediaPlayerList.java b/android/app/src/com/android/bluetooth/audio_util/MediaPlayerList.java
index 67bf06f..a7a814d 100644
--- a/android/app/src/com/android/bluetooth/audio_util/MediaPlayerList.java
+++ b/android/app/src/com/android/bluetooth/audio_util/MediaPlayerList.java
@@ -37,8 +37,7 @@
import com.android.bluetooth.BluetoothEventLogger;
import com.android.bluetooth.Utils;
-import com.android.bluetooth.flags.FeatureFlags;
-import com.android.bluetooth.flags.FeatureFlagsImpl;
+import com.android.bluetooth.flags.Flags;
import com.android.internal.annotations.VisibleForTesting;
import java.util.ArrayList;
@@ -92,7 +91,6 @@
private MediaSessionManager mMediaSessionManager;
private MediaData mCurrMediaData = null;
private final AudioManager mAudioManager;
- private final FeatureFlags mFeatureFlags = new FeatureFlagsImpl();
private final BluetoothEventLogger mActivePlayerLogger =
new BluetoothEventLogger(ACTIVE_PLAYER_LOGGER_SIZE, ACTIVE_PLAYER_LOGGER_TITLE);
@@ -211,7 +209,7 @@
// Build the list of browsable players and afterwards, build the list of media players
Intent intent = new Intent(android.service.media.MediaBrowserService.SERVICE_INTERFACE);
- if (mFeatureFlags.keepStoppedMediaBrowserService()) {
+ if (Flags.keepStoppedMediaBrowserService()) {
// Don't query stopped apps, that would end up unstopping them
intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
}
diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java
index b71db82..0e33c42 100644
--- a/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java
+++ b/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java
@@ -188,7 +188,7 @@
}
@Override
- protected void start() {
+ public void start() {
if (sInstance != null) {
throw new IllegalStateException("start() called twice");
}
@@ -244,7 +244,7 @@
}
@Override
- protected void stop() {
+ public void stop() {
Log.i(TAG, "Stopping the AVRCP Target Service");
if (sInstance == null) {
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java
index 48b1d54..fc9248c 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java
@@ -150,7 +150,7 @@
}
@Override
- protected synchronized void start() {
+ public synchronized void start() {
mNativeInterface.init(this);
setComponentAvailable(ON_ERROR_SETTINGS_ACTIVITY, true);
mAdapterService = AdapterService.getAdapterService();
@@ -169,7 +169,7 @@
}
@Override
- protected synchronized void stop() {
+ public synchronized void stop() {
setActiveDevice(null);
Intent stopIntent = new Intent(this, BluetoothMediaBrowserService.class);
stopService(stopIntent);
diff --git a/android/app/src/com/android/bluetooth/bas/BatteryService.java b/android/app/src/com/android/bluetooth/bas/BatteryService.java
index 862bfdb..e52220d 100644
--- a/android/app/src/com/android/bluetooth/bas/BatteryService.java
+++ b/android/app/src/com/android/bluetooth/bas/BatteryService.java
@@ -80,7 +80,7 @@
}
@Override
- protected void start() {
+ public void start() {
if (DBG) {
Log.d(TAG, "start()");
}
@@ -102,7 +102,7 @@
}
@Override
- protected void stop() {
+ public void stop() {
if (DBG) {
Log.d(TAG, "stop()");
}
@@ -143,7 +143,7 @@
}
@Override
- protected void cleanup() {
+ public void cleanup() {
if (DBG) {
Log.d(TAG, "cleanup()");
}
diff --git a/android/app/src/com/android/bluetooth/bass_client/BassClientService.java b/android/app/src/com/android/bluetooth/bass_client/BassClientService.java
index c5c4eae..65e5e0d 100644
--- a/android/app/src/com/android/bluetooth/bass_client/BassClientService.java
+++ b/android/app/src/com/android/bluetooth/bass_client/BassClientService.java
@@ -65,6 +65,7 @@
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@@ -85,6 +86,17 @@
private static final int STATUS_LOCAL_STREAM_STREAMING = 1;
private static final int STATUS_LOCAL_STREAM_SUSPENDED = 2;
+ // Do not modify without updating the HAL bt_le_audio.h files.
+ // Match up with BroadcastState enum of bt_le_audio.h
+ private static final int BROADCAST_STATE_STOPPED = 0;
+ private static final int BROADCAST_STATE_CONFIGURING = 1;
+ private static final int BROADCAST_STATE_PAUSED = 2;
+ private static final int BROADCAST_STATE_STOPPING = 3;
+ private static final int BROADCAST_STATE_STREAMING = 4;
+
+ /* 1 minute timeout for primary device reconnection in Private Broadcast case */
+ private static final int DIALING_OUT_TIMEOUT_MS = 60000;
+
private static BassClientService sService;
private final Map<BluetoothDevice, BassClientStateMachine> mStateMachines = new HashMap<>();
@@ -101,6 +113,8 @@
new ConcurrentHashMap<>();
private final LinkedList<BluetoothDevice> mPausedBroadcastSinks = new LinkedList<>();
private final Deque<AddSourceData> mPendingAddSources = new ArrayDeque<>();
+ private final Map<Integer, HashSet<BluetoothDevice>> mLocalBroadcastReceivers =
+ new ConcurrentHashMap<>();
private HandlerThread mStateMachinesThread;
private HandlerThread mCallbackHandlerThread;
@@ -108,6 +122,7 @@
private AdapterService mAdapterService;
private DatabaseManager mDatabaseManager;
private BluetoothAdapter mBluetoothAdapter = null;
+ private DialingOutTimeoutEvent mDialingOutTimeoutEvent = null;
/* Caching the PeriodicAdvertisementResult from Broadcast source */
/* This is stored at service so that each device state machine can access
@@ -374,7 +389,7 @@
}
@Override
- protected void start() {
+ public void start() {
if (DBG) {
Log.d(TAG, "start()");
}
@@ -408,13 +423,18 @@
}
@Override
- protected void stop() {
+ public void stop() {
if (DBG) {
Log.d(TAG, "stop()");
}
mUnicastSourceStreamStatus = Optional.empty();
+ if (mDialingOutTimeoutEvent != null) {
+ mHandler.removeCallbacks(mDialingOutTimeoutEvent);
+ mDialingOutTimeoutEvent = null;
+ }
+
if (mIsAssistantActive) {
LeAudioService leAudioService = mServiceFactory.getLeAudioService();
if (leAudioService != null) {
@@ -455,6 +475,9 @@
if (mActiveSourceMap != null) {
mActiveSourceMap.clear();
}
+ if (mLocalBroadcastReceivers != null) {
+ mLocalBroadcastReceivers.clear();
+ }
if (mPendingGroupOp != null) {
mPendingGroupOp.clear();
}
@@ -650,6 +673,27 @@
}
}
+ private void localNotifySourceAdded(
+ BluetoothDevice sink, BluetoothLeBroadcastReceiveState receiveState) {
+ if (!isLocalBroadcast(receiveState)) {
+ return;
+ }
+
+ int broadcastId = receiveState.getBroadcastId();
+
+ /* Track devices bonded to local broadcast for further broadcast status handling when sink
+ * device is:
+ * - disconnecting (if no more receivers, broadcast can be stopped)
+ * - connecting (resynchronize if connection lost)
+ */
+ if (mLocalBroadcastReceivers.containsKey(broadcastId)) {
+ mLocalBroadcastReceivers.get(broadcastId).add(sink);
+ } else {
+ mLocalBroadcastReceivers.put(
+ broadcastId, new HashSet<BluetoothDevice>(Arrays.asList(sink)));
+ }
+ }
+
private void setSourceGroupManaged(BluetoothDevice sink, int sourceId, boolean isGroupOp) {
log("setSourceGroupManaged device: " + sink);
if (isGroupOp) {
@@ -829,6 +873,38 @@
}
}
+ class DialingOutTimeoutEvent implements Runnable {
+ Integer mBroadcastId;
+
+ DialingOutTimeoutEvent(Integer broadcastId) {
+ mBroadcastId = broadcastId;
+ }
+
+ @Override
+ public void run() {
+ mDialingOutTimeoutEvent = null;
+
+ if (getBassClientService() == null) {
+ Log.e(TAG, "DialingOutTimeoutEvent: No Bass service");
+ return;
+ }
+
+ LeAudioService leAudioService = mServiceFactory.getLeAudioService();
+ if (leAudioService == null) {
+ Log.d(TAG, "DialingOutTimeoutEvent: No available LeAudioService");
+ return;
+ }
+
+ sEventLogger.logd(DBG, TAG, "Broadcast timeout: " + mBroadcastId);
+ mLocalBroadcastReceivers.remove(mBroadcastId);
+ leAudioService.stopBroadcast(mBroadcastId);
+ }
+
+ public boolean isScheduledForBroadcast(Integer broadcastId) {
+ return mBroadcastId.equals(broadcastId);
+ }
+ }
+
/**
* Get the BassClientService instance
*
@@ -866,6 +942,29 @@
mActiveSourceMap.remove(device);
}
+ private void handleReconnectingAudioSharingModeDevice(BluetoothDevice device) {
+ /* In case of reconnecting Audio Sharing mode device */
+ if (mDialingOutTimeoutEvent != null) {
+ for (Map.Entry<Integer, HashSet<BluetoothDevice>> entry :
+ mLocalBroadcastReceivers.entrySet()) {
+ Integer broadcastId = entry.getKey();
+ HashSet<BluetoothDevice> devices = entry.getValue();
+
+ /* If associated with any broadcast, try to remove pending timeout callback */
+ if ((mDialingOutTimeoutEvent.isScheduledForBroadcast(broadcastId))
+ && (devices.contains(device))) {
+ Log.i(
+ TAG,
+ "connectionStateChanged: reconnected previousely synced device: "
+ + device);
+ mHandler.removeCallbacks(mDialingOutTimeoutEvent);
+ mDialingOutTimeoutEvent = null;
+ break;
+ }
+ }
+ }
+ }
+
void handleConnectionStateChanged(BluetoothDevice device, int fromState, int toState) {
mHandler.post(() -> connectionStateChanged(device, fromState, toState));
}
@@ -900,6 +999,8 @@
log("Unbonded " + device + ". Removing state machine");
removeStateMachine(device);
}
+ } else if (toState == BluetoothProfile.STATE_CONNECTED) {
+ handleReconnectingAudioSharingModeDevice(device);
}
}
@@ -1667,25 +1768,38 @@
return stateMachine.getMaximumSourceCapacity();
}
- boolean isLocalBroadcast(BluetoothLeBroadcastMetadata metaData) {
- if (metaData == null) {
- return false;
- }
-
+ private boolean isLocalBroadcast(int sourceAdvertisingSid) {
LeAudioService leAudioService = mServiceFactory.getLeAudioService();
if (leAudioService == null) {
return false;
}
- boolean wasFound = leAudioService.getAllBroadcastMetadata()
- .stream()
- .anyMatch(meta -> {
- return meta.getSourceAdvertisingSid() == metaData.getSourceAdvertisingSid();
- });
+ boolean wasFound =
+ leAudioService.getAllBroadcastMetadata().stream()
+ .anyMatch(
+ meta -> {
+ return meta.getSourceAdvertisingSid() == sourceAdvertisingSid;
+ });
log("isLocalBroadcast=" + wasFound);
return wasFound;
}
+ boolean isLocalBroadcast(BluetoothLeBroadcastMetadata metaData) {
+ if (metaData == null) {
+ return false;
+ }
+
+ return isLocalBroadcast(metaData.getSourceAdvertisingSid());
+ }
+
+ boolean isLocalBroadcast(BluetoothLeBroadcastReceiveState receiveState) {
+ if (receiveState == null) {
+ return false;
+ }
+
+ return isLocalBroadcast(receiveState.getSourceAdvertisingSid());
+ }
+
static void log(String msg) {
if (BassConstants.BASS_DBG) {
Log.d(TAG, msg);
@@ -1773,6 +1887,110 @@
return false;
}
+ /** Return true if there is any non primary device receiving broadcast */
+ private boolean isAudioSharingModeOn(Integer broadcastId) {
+ if (mLocalBroadcastReceivers == null) {
+ Log.w(TAG, "isAudioSharingModeOn: Local Broadcaster Receivers is not initialized");
+ return false;
+ }
+
+ HashSet<BluetoothDevice> devices = mLocalBroadcastReceivers.get(broadcastId);
+ if (devices == null) {
+ Log.w(TAG, "isAudioSharingModeOn: No receivers receiving broadcast: " + broadcastId);
+ return false;
+ }
+
+ LeAudioService leAudioService = mServiceFactory.getLeAudioService();
+ if (leAudioService == null) {
+ Log.d(TAG, "isAudioSharingModeOn: No available LeAudioService");
+ return false;
+ }
+
+ return devices.stream().anyMatch(d -> !leAudioService.isPrimaryDevice(d));
+ }
+
+ /** Handle disconnection of potential broadcast sinks */
+ public void handleDeviceDisconnection(BluetoothDevice sink, boolean isIntentional) {
+ LeAudioService leAudioService = mServiceFactory.getLeAudioService();
+ if (leAudioService == null) {
+ Log.d(TAG, "BluetoothLeBroadcastReceiveState: No available LeAudioService");
+ return;
+ }
+
+ for (Map.Entry<Integer, HashSet<BluetoothDevice>> entry :
+ mLocalBroadcastReceivers.entrySet()) {
+ Integer broadcastId = entry.getKey();
+ HashSet<BluetoothDevice> devices = entry.getValue();
+
+ /* If somehow there is a non playing broadcast, let's remove it */
+ if (!leAudioService.isPlaying(broadcastId)) {
+ Log.w(TAG, "Non playing broadcast remove from receivers list");
+ mLocalBroadcastReceivers.remove(broadcastId);
+ continue;
+ }
+
+ if (isIntentional) {
+ /* Check if disconnecting device participated in this broadcast reception */
+ if (!devices.remove(sink)) {
+ continue;
+ }
+
+ mBroadcastMetadataMap.remove(sink);
+
+ /* Check if there is any other primary device receiving this broadcast */
+ if (devices.stream()
+ .anyMatch(
+ d ->
+ ((getConnectionState(d) == BluetoothProfile.STATE_CONNECTED)
+ && leAudioService.isPrimaryDevice(d)))) {
+ continue;
+ }
+
+ Log.d(
+ TAG,
+ "handleIntendedDeviceDisconnection: No more potential broadcast "
+ + "(broadcast ID: "
+ + broadcastId
+ + ") receivers - stopping broadcast");
+ mLocalBroadcastReceivers.remove(broadcastId);
+ leAudioService.stopBroadcast(broadcastId);
+ } else {
+ /* Unintentional disconnection of primary device in private broadcast mode */
+ if (!isAudioSharingModeOn(broadcastId)
+ && !devices.stream()
+ .anyMatch(
+ d ->
+ !d.equals(sink)
+ && (getConnectionState(d)
+ == BluetoothProfile
+ .STATE_CONNECTED))) {
+ mLocalBroadcastReceivers.remove(broadcastId);
+ leAudioService.stopBroadcast(broadcastId);
+ continue;
+ }
+
+ /* Unintentional disconnection of primary/secondary in broadcast sharing mode */
+ if (devices.stream()
+ .anyMatch(
+ d ->
+ !d.equals(sink)
+ && (getConnectionState(d)
+ == BluetoothProfile.STATE_CONNECTED))) {
+ continue;
+ } else {
+ Log.d(
+ TAG,
+ "handleUnintendedDeviceDisconnection: No more potential broadcast "
+ + "(broadcast ID: "
+ + broadcastId
+ + ") receivers - stopping broadcast");
+ mDialingOutTimeoutEvent = new DialingOutTimeoutEvent(broadcastId);
+ mHandler.postDelayed(mDialingOutTimeoutEvent, DIALING_OUT_TIMEOUT_MS);
+ }
+ }
+ }
+ }
+
/** Request receivers to suspend broadcast sources synchronization */
public void suspendReceiversSourceSynchronization(int broadcastId) {
sEventLogger.logd(DBG, TAG, "Suspend receivers source synchronization: " + broadcastId);
@@ -1834,6 +2052,28 @@
}
}
+ /** Handle broadcast state changed */
+ public void notifyBroadcastStateChanged(int state, int broadcastId) {
+ switch (state) {
+ case BROADCAST_STATE_STOPPED:
+ if (mLocalBroadcastReceivers == null) {
+ Log.e(TAG, "notifyBroadcastStateChanged: mLocalBroadcastReceivers is invalid");
+ break;
+ }
+
+ if (mLocalBroadcastReceivers.remove(broadcastId) != null) {
+ sEventLogger.logd(DBG, TAG, "Broadcast ID: " + broadcastId + ", stopped");
+ }
+ break;
+ case BROADCAST_STATE_CONFIGURING:
+ case BROADCAST_STATE_PAUSED:
+ case BROADCAST_STATE_STOPPING:
+ case BROADCAST_STATE_STREAMING:
+ default:
+ break;
+ }
+ }
+
/**
* Callback handler
*/
@@ -2025,6 +2265,8 @@
void notifySourceAdded(BluetoothDevice sink, BluetoothLeBroadcastReceiveState recvState,
int reason) {
+ sService.localNotifySourceAdded(sink, recvState);
+
sEventLogger.logd(
DBG,
TAG,
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 59502121..ded8600 100644
--- a/android/app/src/com/android/bluetooth/bass_client/BassClientStateMachine.java
+++ b/android/app/src/com/android/bluetooth/bass_client/BassClientStateMachine.java
@@ -1701,6 +1701,7 @@
log("Disconnecting from " + mDevice);
mAllowReconnect = false;
if (mBluetoothGatt != null) {
+ mService.handleDeviceDisconnection(mDevice, true);
mBluetoothGatt.disconnect();
mBluetoothGatt.close();
mBluetoothGatt = null;
@@ -1717,6 +1718,7 @@
Log.w(TAG, "device is already connected to Bass" + mDevice);
} else {
Log.w(TAG, "unexpected disconnected from " + mDevice);
+ mService.handleDeviceDisconnection(mDevice, false);
resetBluetoothGatt();
cancelActiveSync(null);
transitionTo(mDisconnected);
@@ -2052,6 +2054,7 @@
Log.w(TAG, "DISCONNECT requested!: " + mDevice);
mAllowReconnect = false;
if (mBluetoothGatt != null) {
+ mService.handleDeviceDisconnection(mDevice, true);
mBluetoothGatt.disconnect();
mBluetoothGatt.close();
mBluetoothGatt = null;
@@ -2072,6 +2075,7 @@
Log.w(TAG, "should never happen from this state");
} else {
Log.w(TAG, "Unexpected disconnection " + mDevice);
+ mService.handleDeviceDisconnection(mDevice, false);
resetBluetoothGatt();
cancelActiveSync(null);
transitionTo(mDisconnected);
diff --git a/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java b/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java
index eb729ec..71f7ee7 100644
--- a/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java
+++ b/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java
@@ -39,7 +39,7 @@
import com.android.bluetooth.Utils;
import com.android.bluetooth.a2dp.A2dpService;
import com.android.bluetooth.btservice.storage.DatabaseManager;
-import com.android.bluetooth.flags.FeatureFlags;
+import com.android.bluetooth.flags.Flags;
import com.android.bluetooth.hearingaid.HearingAidService;
import com.android.bluetooth.hfp.HeadsetService;
import com.android.bluetooth.le_audio.LeAudioService;
@@ -100,7 +100,7 @@
* active Bluetooth device.
*/
public class ActiveDeviceManager implements AdapterService.BluetoothStateCallback {
- private static final String TAG = "ActiveDeviceManager";
+ private static final String TAG = ActiveDeviceManager.class.getSimpleName();
private static final boolean DBG = true;
@VisibleForTesting
static final int A2DP_HFP_SYNC_CONNECTION_TIMEOUT_MS = 5_000;
@@ -112,7 +112,6 @@
private Handler mHandler = null;
private final AudioManager mAudioManager;
private final AudioManagerAudioDeviceCallback mAudioManagerAudioDeviceCallback;
- private final FeatureFlags mFeatureFlags;
private final Object mLock = new Object();
@GuardedBy("mLock")
@@ -811,10 +810,9 @@
}
}
- ActiveDeviceManager(AdapterService service, ServiceFactory factory, FeatureFlags featureFlags) {
+ ActiveDeviceManager(AdapterService service, ServiceFactory factory) {
mAdapterService = service;
mDbManager = mAdapterService.getDatabase();
- mFeatureFlags = Objects.requireNonNull(featureFlags, "Feature Flags cannot be null");
mFactory = factory;
mAudioManager = service.getSystemService(AudioManager.class);
mAudioManagerAudioDeviceCallback = new AudioManagerAudioDeviceCallback();
@@ -987,6 +985,16 @@
if (device == null) {
success = leAudioService.removeActiveDevice(hasFallbackDevice);
} else {
+ if (Flags.leaudioActiveDeviceManagerGroupHandlingFix()) {
+ if ((mLeAudioActiveDevice != null)
+ && (Objects.equals(
+ mLeAudioActiveDevice, leAudioService.getLeadDevice(device)))) {
+ if (DBG) {
+ Log.d(TAG, "New LeAudioDevice is a part of an active group");
+ }
+ return true;
+ }
+ }
success = leAudioService.setActiveDevice(device);
}
@@ -994,7 +1002,12 @@
return false;
}
- mLeAudioActiveDevice = device;
+ if (Flags.leaudioActiveDeviceManagerGroupHandlingFix()) {
+ mLeAudioActiveDevice = leAudioService.getLeadDevice(device);
+ } else {
+ mLeAudioActiveDevice = device;
+ }
+
if (device == null) {
mLeHearingAidActiveDevice = null;
mPendingLeHearingAidActiveDevice.remove(device);
@@ -1245,7 +1258,7 @@
* @return {@code true} if is broadcasting audio, {@code false} otherwise
*/
private boolean isBroadcastingAudio() {
- if (!mFeatureFlags.leaudioBroadcastAudioHandoverPolicies()) {
+ if (!Flags.leaudioBroadcastAudioHandoverPolicies()) {
// disable this if feature flag is false
return false;
}
diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterService.java b/android/app/src/com/android/bluetooth/btservice/AdapterService.java
index 4af3b9b..cdef731 100644
--- a/android/app/src/com/android/bluetooth/btservice/AdapterService.java
+++ b/android/app/src/com/android/bluetooth/btservice/AdapterService.java
@@ -125,7 +125,6 @@
import com.android.bluetooth.btservice.storage.DatabaseManager;
import com.android.bluetooth.btservice.storage.MetadataDatabase;
import com.android.bluetooth.csip.CsipSetCoordinatorService;
-import com.android.bluetooth.flags.FeatureFlagsImpl;
import com.android.bluetooth.flags.Flags;
import com.android.bluetooth.gatt.GattService;
import com.android.bluetooth.hap.HapClientService;
@@ -402,7 +401,6 @@
private volatile boolean mTestModeEnabled = false;
private MetricsLogger mMetricsLogger;
- private FeatureFlagsImpl mFeatureFlags;
/**
* Register a {@link ProfileService} with AdapterService.
@@ -686,9 +684,7 @@
mSdpManager = SdpManager.init(this);
- mFeatureFlags = new FeatureFlagsImpl();
-
- mDatabaseManager = new DatabaseManager(this, mFeatureFlags);
+ mDatabaseManager = new DatabaseManager(this);
mDatabaseManager.start(MetadataDatabase.createDatabase(this));
boolean isAutomotiveDevice =
@@ -704,18 +700,16 @@
*/
if (!isAutomotiveDevice && getResources().getBoolean(R.bool.enable_phone_policy)) {
Log.i(TAG, "Phone policy enabled");
- mPhonePolicy = new PhonePolicy(this, new ServiceFactory(), mFeatureFlags);
+ mPhonePolicy = new PhonePolicy(this, new ServiceFactory());
mPhonePolicy.start();
} else {
Log.i(TAG, "Phone policy disabled");
}
- if (mFeatureFlags.audioRoutingCentralization()) {
- mActiveDeviceManager =
- new AudioRoutingManager(this, new ServiceFactory(), mFeatureFlags);
+ if (Flags.audioRoutingCentralization()) {
+ mActiveDeviceManager = new AudioRoutingManager(this, new ServiceFactory());
} else {
- mActiveDeviceManager =
- new ActiveDeviceManager(this, new ServiceFactory(), mFeatureFlags);
+ mActiveDeviceManager = new ActiveDeviceManager(this, new ServiceFactory());
}
mActiveDeviceManager.start();
@@ -1049,8 +1043,10 @@
mGattService = new GattService(this);
mStartedProfiles.put(BluetoothProfile.GATT, mGattService);
-
- ((ProfileService) mGattService).doStart();
+ addProfile(mGattService);
+ mGattService.start();
+ mGattService.setAvailable(true);
+ onProfileServiceStateChanged(mGattService, BluetoothAdapter.STATE_ON);
}
private void stopGattProfileService() {
@@ -1062,7 +1058,12 @@
mStartedProfiles.remove(BluetoothProfile.GATT);
if (mGattService != null) {
- ((ProfileService) mGattService).doStop();
+ mGattService.setAvailable(false);
+ onProfileServiceStateChanged(mGattService, BluetoothAdapter.STATE_OFF);
+ mGattService.stop();
+ removeProfile(mGattService);
+ mGattService.cleanup();
+ mGattService.getBinder().cleanup();
mGattService = null;
}
}
@@ -1426,35 +1427,39 @@
BluetoothSap.invalidateBluetoothGetConnectionStateCache();
}
- private static final Map<Integer, Function<Context, ProfileService>> PROFILE_CONSTRUCTORS =
- Map.ofEntries(
- Map.entry(BluetoothProfile.A2DP, A2dpService::new),
- Map.entry(BluetoothProfile.A2DP_SINK, A2dpSinkService::new),
- Map.entry(BluetoothProfile.AVRCP, AvrcpTargetService::new),
- Map.entry(BluetoothProfile.AVRCP_CONTROLLER, AvrcpControllerService::new),
- Map.entry(
- BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT, BassClientService::new),
- Map.entry(BluetoothProfile.BATTERY, BatteryService::new),
- Map.entry(
- BluetoothProfile.CSIP_SET_COORDINATOR, CsipSetCoordinatorService::new),
- Map.entry(BluetoothProfile.HAP_CLIENT, HapClientService::new),
- Map.entry(BluetoothProfile.HEADSET, HeadsetService::new),
- Map.entry(BluetoothProfile.HEADSET_CLIENT, HeadsetClientService::new),
- Map.entry(BluetoothProfile.HEARING_AID, HearingAidService::new),
- Map.entry(BluetoothProfile.HID_DEVICE, HidDeviceService::new),
- Map.entry(BluetoothProfile.HID_HOST, HidHostService::new),
- Map.entry(BluetoothProfile.GATT, GattService::new),
- Map.entry(BluetoothProfile.LE_AUDIO, LeAudioService::new),
- Map.entry(BluetoothProfile.LE_CALL_CONTROL, TbsService::new),
- Map.entry(BluetoothProfile.MAP, BluetoothMapService::new),
- Map.entry(BluetoothProfile.MAP_CLIENT, MapClientService::new),
- Map.entry(BluetoothProfile.MCP_SERVER, McpService::new),
- Map.entry(BluetoothProfile.OPP, BluetoothOppService::new),
- Map.entry(BluetoothProfile.PAN, PanService::new),
- Map.entry(BluetoothProfile.PBAP, BluetoothPbapService::new),
- Map.entry(BluetoothProfile.PBAP_CLIENT, PbapClientService::new),
- Map.entry(BluetoothProfile.SAP, SapService::new),
- Map.entry(BluetoothProfile.VOLUME_CONTROL, VolumeControlService::new));
+ private static final Map<Integer, Function<AdapterService, ProfileService>>
+ PROFILE_CONSTRUCTORS =
+ Map.ofEntries(
+ Map.entry(BluetoothProfile.A2DP, A2dpService::new),
+ Map.entry(BluetoothProfile.A2DP_SINK, A2dpSinkService::new),
+ Map.entry(BluetoothProfile.AVRCP, AvrcpTargetService::new),
+ Map.entry(
+ BluetoothProfile.AVRCP_CONTROLLER, AvrcpControllerService::new),
+ Map.entry(
+ BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT,
+ BassClientService::new),
+ Map.entry(BluetoothProfile.BATTERY, BatteryService::new),
+ Map.entry(
+ BluetoothProfile.CSIP_SET_COORDINATOR,
+ CsipSetCoordinatorService::new),
+ Map.entry(BluetoothProfile.HAP_CLIENT, HapClientService::new),
+ Map.entry(BluetoothProfile.HEADSET, HeadsetService::new),
+ Map.entry(BluetoothProfile.HEADSET_CLIENT, HeadsetClientService::new),
+ Map.entry(BluetoothProfile.HEARING_AID, HearingAidService::new),
+ Map.entry(BluetoothProfile.HID_DEVICE, HidDeviceService::new),
+ Map.entry(BluetoothProfile.HID_HOST, HidHostService::new),
+ Map.entry(BluetoothProfile.GATT, GattService::new),
+ Map.entry(BluetoothProfile.LE_AUDIO, LeAudioService::new),
+ Map.entry(BluetoothProfile.LE_CALL_CONTROL, TbsService::new),
+ Map.entry(BluetoothProfile.MAP, BluetoothMapService::new),
+ Map.entry(BluetoothProfile.MAP_CLIENT, MapClientService::new),
+ Map.entry(BluetoothProfile.MCP_SERVER, McpService::new),
+ Map.entry(BluetoothProfile.OPP, BluetoothOppService::new),
+ Map.entry(BluetoothProfile.PAN, PanService::new),
+ Map.entry(BluetoothProfile.PBAP, BluetoothPbapService::new),
+ Map.entry(BluetoothProfile.PBAP_CLIENT, PbapClientService::new),
+ Map.entry(BluetoothProfile.SAP, SapService::new),
+ Map.entry(BluetoothProfile.VOLUME_CONTROL, VolumeControlService::new));
@VisibleForTesting
void setProfileServiceState(int profileId, int state) {
@@ -1462,7 +1467,10 @@
if (!mStartedProfiles.containsKey(profileId)) {
ProfileService profileService = PROFILE_CONSTRUCTORS.get(profileId).apply(this);
mStartedProfiles.put(profileId, profileService);
- profileService.doStart();
+ addProfile(profileService);
+ profileService.start();
+ profileService.setAvailable(true);
+ onProfileServiceStateChanged(profileService, BluetoothAdapter.STATE_ON);
} else {
Log.e(
TAG,
@@ -1473,7 +1481,12 @@
} else if (state == BluetoothAdapter.STATE_OFF) {
ProfileService profileService = mStartedProfiles.remove(profileId);
if (profileService != null) {
- profileService.doStop();
+ profileService.setAvailable(false);
+ onProfileServiceStateChanged(profileService, BluetoothAdapter.STATE_OFF);
+ profileService.stop();
+ removeProfile(profileService);
+ profileService.cleanup();
+ profileService.getBinder().cleanup();
} else {
Log.e(
TAG,
@@ -6173,7 +6186,7 @@
}
int getConnectionState(BluetoothDevice device) {
- if (mFeatureFlags.apiGetConnectionStateUsingIdentityAddress()) {
+ if (Flags.apiGetConnectionStateUsingIdentityAddress()) {
final String identityAddress = device.getIdentityAddress();
return (identityAddress == null)
? mNativeInterface.getConnectionState(getBytesFromAddress(device.getAddress()))
@@ -7356,7 +7369,7 @@
return true;
}
- void energyInfoCallback(
+ void energyInfoCallbackInternal(
int status,
int ctrlState,
long txTime,
@@ -7364,8 +7377,6 @@
long idleTime,
long energyUsed,
UidTraffic[] data) {
- if (ctrlState >= BluetoothActivityEnergyInfo.BT_STACK_STATE_INVALID
- && ctrlState <= BluetoothActivityEnergyInfo.BT_STACK_STATE_STATE_IDLE) {
// Energy is product of mA, V and ms. If the chipset doesn't
// report it, we have to compute it from time
if (energyUsed == 0) {
@@ -7420,8 +7431,24 @@
}
mEnergyInfoLock.notifyAll();
}
- }
+ }
+ void energyInfoCallback(
+ int status,
+ int ctrlState,
+ long txTime,
+ long rxTime,
+ long idleTime,
+ long energyUsed,
+ UidTraffic[] data) {
+ if (Flags.btSystemContextReport()) {
+ energyInfoCallbackInternal(
+ status, ctrlState, txTime, rxTime, idleTime, energyUsed, data);
+ } else if (ctrlState >= BluetoothActivityEnergyInfo.BT_STACK_STATE_INVALID
+ && ctrlState <= BluetoothActivityEnergyInfo.BT_STACK_STATE_STATE_IDLE) {
+ energyInfoCallbackInternal(
+ status, ctrlState, txTime, rxTime, idleTime, energyUsed, data);
+ }
verboseLog(
"energyInfoCallback()"
+ (" status = " + status)
@@ -7429,7 +7456,7 @@
+ (" rxTime = " + rxTime)
+ (" idleTime = " + idleTime)
+ (" energyUsed = " + energyUsed)
- + (" ctrlState = " + ctrlState)
+ + (" ctrlState = " + String.format("0x%08x", ctrlState))
+ (" traffic = " + Arrays.toString(data)));
}
diff --git a/android/app/src/com/android/bluetooth/btservice/AudioRoutingManager.java b/android/app/src/com/android/bluetooth/btservice/AudioRoutingManager.java
index 6b0865e..2dfed88 100644
--- a/android/app/src/com/android/bluetooth/btservice/AudioRoutingManager.java
+++ b/android/app/src/com/android/bluetooth/btservice/AudioRoutingManager.java
@@ -43,7 +43,6 @@
import com.android.bluetooth.Utils;
import com.android.bluetooth.a2dp.A2dpService;
import com.android.bluetooth.btservice.storage.DatabaseManager;
-import com.android.bluetooth.flags.FeatureFlags;
import com.android.bluetooth.hearingaid.HearingAidService;
import com.android.bluetooth.hfp.HeadsetService;
import com.android.bluetooth.le_audio.LeAudioService;
@@ -146,8 +145,8 @@
}
}
- AudioRoutingManager(AdapterService service, ServiceFactory factory, FeatureFlags featureFlags) {
- super(service, factory, featureFlags);
+ AudioRoutingManager(AdapterService service, ServiceFactory factory) {
+ super(service, factory);
mAdapterService = service;
mDbManager = mAdapterService.getDatabase();
mFactory = factory;
diff --git a/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java b/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java
index 54874ff..c377be4 100644
--- a/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java
+++ b/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java
@@ -38,8 +38,7 @@
import com.android.bluetooth.a2dp.A2dpService;
import com.android.bluetooth.a2dpsink.A2dpSinkService;
import com.android.bluetooth.btservice.RemoteDevices.DeviceProperties;
-import com.android.bluetooth.flags.FeatureFlags;
-import com.android.bluetooth.flags.FeatureFlagsImpl;
+import com.android.bluetooth.flags.Flags;
import com.android.bluetooth.hfp.HeadsetService;
import com.android.bluetooth.hfpclient.HeadsetClientService;
import com.android.bluetooth.hid.HidHostService;
@@ -97,8 +96,6 @@
@VisibleForTesting Set<BluetoothDevice> mPendingBondedDevices = new HashSet<>();
- private final FeatureFlags mFeatureFlags = new FeatureFlagsImpl();
-
private BondStateMachine(AdapterService service, AdapterProperties prop,
RemoteDevices remoteDevices) {
super("BondStateMachine:");
@@ -153,7 +150,7 @@
next pairing is started while previous still makes service discovery, it
would fail. Check the busy status of BTIF instead, and wait with starting
the bond. */
- if (mFeatureFlags.delayBondingWhenBusy()
+ if (Flags.delayBondingWhenBusy()
&& mAdapterService.getNative().pairingIsBusy()) {
short retry_no =
(msg.getData() != null)
diff --git a/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java b/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java
index ea4c1fd..f978c34 100644
--- a/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java
+++ b/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java
@@ -38,7 +38,7 @@
import com.android.bluetooth.bass_client.BassClientService;
import com.android.bluetooth.btservice.storage.DatabaseManager;
import com.android.bluetooth.csip.CsipSetCoordinatorService;
-import com.android.bluetooth.flags.FeatureFlags;
+import com.android.bluetooth.flags.Flags;
import com.android.bluetooth.hap.HapClientService;
import com.android.bluetooth.hearingaid.HearingAidService;
import com.android.bluetooth.hfp.HeadsetService;
@@ -84,7 +84,6 @@
@VisibleForTesting static int sConnectOtherProfilesTimeoutMillis = 6000; // 6s
private DatabaseManager mDatabaseManager;
- private final FeatureFlags mFeatureFlags;
private final AdapterService mAdapterService;
private final ServiceFactory mFactory;
private final Handler mHandler;
@@ -158,7 +157,7 @@
;
// Policy API functions for lifecycle management (protected)
- protected void start() {
+ public void start() {
mAdapterService.registerBluetoothStateCallback((command) -> mHandler.post(command), this);
IntentFilter filter = new IntentFilter();
@@ -166,16 +165,15 @@
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
}
- protected void cleanup() {
+ public void cleanup() {
mAdapterService.unregisterBluetoothStateCallback(this);
resetStates();
}
- PhonePolicy(AdapterService service, ServiceFactory factory, FeatureFlags featureFlags) {
+ PhonePolicy(AdapterService service, ServiceFactory factory) {
mAdapterService = service;
mDatabaseManager = Objects.requireNonNull(mAdapterService.getDatabase(),
"DatabaseManager cannot be null when PhonePolicy starts");
- mFeatureFlags = Objects.requireNonNull(featureFlags, "Feature Flags cannot be null");
mFactory = factory;
mHandler = new PhonePolicyHandler(service.getMainLooper());
mAutoConnectProfilesSupported =
@@ -646,12 +644,12 @@
return;
}
- if (!mFeatureFlags.autoConnectOnHfpWhenNoA2dpDevice()) {
+ if (!Flags.autoConnectOnHfpWhenNoA2dpDevice()) {
debugLog("HFP auto connect is not enabled");
return;
}
- if (mFeatureFlags.autoConnectOnMultipleHfpWhenNoA2dpDevice()) {
+ if (Flags.autoConnectOnMultipleHfpWhenNoA2dpDevice()) {
final List<BluetoothDevice> mostRecentlyConnectedHfpDevices =
mDatabaseManager.getMostRecentlyActiveHfpDevices();
for (BluetoothDevice hfpDevice : mostRecentlyConnectedHfpDevices) {
diff --git a/android/app/src/com/android/bluetooth/btservice/ProfileService.java b/android/app/src/com/android/bluetooth/btservice/ProfileService.java
index 3a9226d..3190463 100644
--- a/android/app/src/com/android/bluetooth/btservice/ProfileService.java
+++ b/android/app/src/com/android/bluetooth/btservice/ProfileService.java
@@ -21,17 +21,14 @@
import android.annotation.RequiresPermission;
import android.annotation.SuppressLint;
-import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
-import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.util.Log;
import com.android.bluetooth.BluetoothMetricsProto;
-import com.android.internal.annotations.VisibleForTesting;
/** Base class for a background service that runs a Bluetooth profile */
public abstract class ProfileService extends ContextWrapper {
@@ -43,16 +40,13 @@
android.Manifest.permission.BLUETOOTH_PRIVILEGED;
public interface IProfileServiceBinder extends IBinder {
- /**
- * Called in {@link #onDestroy()}
- */
void cleanup();
}
private final IProfileServiceBinder mBinder;
private final String mName;
private AdapterService mAdapterService;
- private boolean mProfileStarted = false;
+ private boolean mAvailable = false;
private volatile boolean mTestModeEnabled = false;
public String getName() {
@@ -60,7 +54,11 @@
}
public boolean isAvailable() {
- return mProfileStarted;
+ return mAvailable;
+ }
+
+ public void setAvailable(boolean available) {
+ mAvailable = available;
}
protected boolean isTestModeEnabled() {
@@ -74,20 +72,14 @@
*/
protected abstract IProfileServiceBinder initBinder();
- /**
- * Called in {@link #onStartCommand(Intent, int, int)} when the service is started by intent
- */
- protected abstract void start();
+ /** Start service */
+ public abstract void start();
- /**
- * Called in {@link #onStartCommand(Intent, int, int)} when the service is stopped by intent
- */
- protected abstract void stop();
+ /** Stop service */
+ public abstract void stop();
- /**
- * Called in {@link #onDestroy()} when this object is completely discarded
- */
- protected void cleanup() {}
+ /** Called when this object is completely discarded */
+ public void cleanup() {}
/**
* @param testModeEnabled if the profile should enter or exit a testing mode
@@ -106,7 +98,7 @@
}
/** return the binder of the profile */
- public IBinder getBinder() {
+ public IProfileServiceBinder getBinder() {
return mBinder;
}
@@ -195,50 +187,4 @@
sb.append(s);
sb.append("\n");
}
-
- /** start the profile and inform AdapterService */
- @RequiresPermission(
- anyOf = {
- android.Manifest.permission.MANAGE_USERS,
- android.Manifest.permission.INTERACT_ACROSS_USERS
- })
- @VisibleForTesting
- public void doStart() {
- Log.v(mName, "doStart");
- mAdapterService = AdapterService.getAdapterService();
- if (mAdapterService == null) {
- Log.w(mName, "Could not add this profile because AdapterService is null.");
- return;
- }
- mAdapterService.addProfile(this);
-
- start();
- mProfileStarted = true;
-
- mAdapterService.onProfileServiceStateChanged(this, BluetoothAdapter.STATE_ON);
- }
-
- /** stop the profile and inform AdapterService */
- @VisibleForTesting
- public void doStop() {
- Log.v(mName, "doStop");
- if (mAdapterService == null) {
- Log.w(mName, "Unexpectedly do Stop, don't stop.");
- return;
- }
- if (!mProfileStarted) {
- Log.w(mName, "doStop() called, but the profile is not running.");
- return;
- }
- mProfileStarted = false;
- if (mAdapterService != null) {
- mAdapterService.onProfileServiceStateChanged(this, BluetoothAdapter.STATE_OFF);
- }
- stop();
- if (mAdapterService != null) {
- mAdapterService.removeProfile(this);
- }
- cleanup();
- mBinder.cleanup();
- }
}
diff --git a/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java b/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java
index 5e39712..6a4d9e7 100644
--- a/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java
+++ b/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java
@@ -47,7 +47,7 @@
import com.android.bluetooth.R;
import com.android.bluetooth.Utils;
import com.android.bluetooth.bas.BatteryService;
-import com.android.bluetooth.flags.FeatureFlagsImpl;
+import com.android.bluetooth.flags.Flags;
import com.android.bluetooth.hfp.HeadsetHalConstants;
import com.android.internal.annotations.VisibleForTesting;
@@ -70,7 +70,6 @@
private BluetoothAdapter mAdapter;
private AdapterService mAdapterService;
- private FeatureFlagsImpl mFeatureFlags;
private ArrayList<BluetoothDevice> mSdpTracker;
private final Object mObject = new Object();
@@ -155,7 +154,6 @@
RemoteDevices(AdapterService service, Looper looper) {
mAdapter = ((Context) service).getSystemService(BluetoothManager.class).getAdapter();
mAdapterService = service;
- mFeatureFlags = new FeatureFlagsImpl();
mSdpTracker = new ArrayList<BluetoothDevice>();
mDevices = new HashMap<String, DeviceProperties>();
mDualDevicesMap = new HashMap<String, String>();
@@ -1259,7 +1257,7 @@
Log.d(TAG, "keyMissingCallback device: " + bluetoothDevice);
if (bluetoothDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
- if (!mFeatureFlags.keyMissingBroadcast()) {
+ if (!Flags.keyMissingBroadcast()) {
Log.d(TAG, "flag not set - don't send key missing broadcast");
return;
}
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 f9db3f7..cf23cf7 100644
--- a/android/app/src/com/android/bluetooth/btservice/storage/DatabaseManager.java
+++ b/android/app/src/com/android/bluetooth/btservice/storage/DatabaseManager.java
@@ -42,7 +42,7 @@
import com.android.bluetooth.BluetoothStatsLog;
import com.android.bluetooth.Utils;
import com.android.bluetooth.btservice.AdapterService;
-import com.android.bluetooth.flags.FeatureFlags;
+import com.android.bluetooth.flags.Flags;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
@@ -68,7 +68,6 @@
private static final String TAG = "BluetoothDatabase";
private final AdapterService mAdapterService;
- private final FeatureFlags mFeatureFlags;
private HandlerThread mHandlerThread = null;
private Handler mHandler = null;
private final Object mDatabaseLock = new Object();
@@ -114,9 +113,8 @@
LEGACY_HEARING_AID_PRIORITY_PREFIX = "bluetooth_hearing_aid_priority_";
/** Constructor of the DatabaseManager */
- public DatabaseManager(AdapterService service, FeatureFlags featureFlags) {
+ public DatabaseManager(AdapterService service) {
mAdapterService = Objects.requireNonNull(service, "Adapter service cannot be null");
- mFeatureFlags = Objects.requireNonNull(featureFlags, "Feature Flags cannot be null");
mMetadataChangedLog = EvictingQueue.create(METADATA_CHANGED_LOG_MAX_SIZE);
}
@@ -648,7 +646,7 @@
if (isA2dpDevice) {
resetActiveA2dpDevice();
}
- if (isHfpDevice && !mFeatureFlags.autoConnectOnMultipleHfpWhenNoA2dpDevice()) {
+ if (isHfpDevice && !Flags.autoConnectOnMultipleHfpWhenNoA2dpDevice()) {
resetActiveHfpDevice();
}
diff --git a/android/app/src/com/android/bluetooth/content_profiles/ContentProfileErrorReportUtils.java b/android/app/src/com/android/bluetooth/content_profiles/ContentProfileErrorReportUtils.java
index ec20d27..e8a67ac 100644
--- a/android/app/src/com/android/bluetooth/content_profiles/ContentProfileErrorReportUtils.java
+++ b/android/app/src/com/android/bluetooth/content_profiles/ContentProfileErrorReportUtils.java
@@ -21,12 +21,10 @@
import android.util.Log;
import com.android.bluetooth.BluetoothStatsLog;
-import com.android.bluetooth.flags.Flags;
import com.android.internal.annotations.VisibleForTesting;
/**
- * Utility method to report exceptions and error/warn logs in content profiles. Will be no-op if
- * {@link Flags#contentProfilesErrorsMetrics()} is not enabled.
+ * Utility method to report exceptions and error/warn logs in content profiles.
*/
public class ContentProfileErrorReportUtils {
private static final String TAG = ContentProfileErrorReportUtils.class.getSimpleName();
@@ -52,10 +50,6 @@
* @return true if successfully wrote the error, false otherwise
*/
public static synchronized boolean report(int profile, int fileNameEnum, int type, int tag) {
- if (!Flags.contentProfilesErrorsMetrics()) {
- return false;
- }
-
if (isTooFrequentReport()) {
Log.w(
TAG,
diff --git a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java
index ff234d9..9494b10 100644
--- a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java
+++ b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java
@@ -123,7 +123,7 @@
}
@Override
- protected void start() {
+ public void start() {
if (DBG) {
Log.d(TAG, "start()");
}
@@ -166,7 +166,7 @@
}
@Override
- protected void stop() {
+ public void stop() {
if (DBG) {
Log.d(TAG, "stop()");
}
@@ -222,7 +222,7 @@
}
@Override
- protected void cleanup() {
+ public void cleanup() {
if (DBG) {
Log.d(TAG, "cleanup()");
}
diff --git a/android/app/src/com/android/bluetooth/gatt/ContextMap.java b/android/app/src/com/android/bluetooth/gatt/ContextMap.java
index 5d12569..f8f7ca8 100644
--- a/android/app/src/com/android/bluetooth/gatt/ContextMap.java
+++ b/android/app/src/com/android/bluetooth/gatt/ContextMap.java
@@ -211,7 +211,7 @@
private final Object mConnectionsLock = new Object();
/** Add an entry to the application context list. */
- App add(
+ protected App add(
UUID uuid,
WorkSource workSource,
C callback,
@@ -292,7 +292,7 @@
/**
* Remove the context for a given application ID.
*/
- void remove(int id) {
+ protected void remove(int id) {
boolean find = false;
synchronized (mAppsLock) {
Iterator<App> i = mApps.iterator();
@@ -312,7 +312,7 @@
}
}
- List<Integer> getAllAppsIds() {
+ protected List<Integer> getAllAppsIds() {
List<Integer> appIds = new ArrayList();
synchronized (mAppsLock) {
Iterator<App> i = mApps.iterator();
@@ -370,7 +370,7 @@
/**
* Get an application context by ID.
*/
- App getById(int id) {
+ protected App getById(int id) {
synchronized (mAppsLock) {
Iterator<App> i = mApps.iterator();
while (i.hasNext()) {
@@ -387,7 +387,7 @@
/**
* Get an application context by UUID.
*/
- App getByUuid(UUID uuid) {
+ protected App getByUuid(UUID uuid) {
synchronized (mAppsLock) {
Iterator<App> i = mApps.iterator();
while (i.hasNext()) {
@@ -421,7 +421,7 @@
/**
* Get an application context by the context info object.
*/
- App getByContextInfo(T contextInfo) {
+ protected App getByContextInfo(T contextInfo) {
synchronized (mAppsLock) {
Iterator<App> i = mApps.iterator();
while (i.hasNext()) {
@@ -438,7 +438,7 @@
/**
* Get Logging info by ID
*/
- AppScanStats getAppScanStatsById(int id) {
+ protected AppScanStats getAppScanStatsById(int id) {
App temp = getById(id);
if (temp != null) {
return temp.appScanStats;
@@ -674,7 +674,7 @@
/**
* Erases all application context entries.
*/
- void clear() {
+ protected void clear() {
synchronized (mAppsLock) {
Iterator<App> i = mApps.iterator();
while (i.hasNext()) {
@@ -713,7 +713,7 @@
/**
* Logs debug information.
*/
- void dump(StringBuilder sb) {
+ protected void dump(StringBuilder sb) {
sb.append(" Entries: " + mAppScanStats.size() + "\n\n");
Iterator<Map.Entry<Integer, AppScanStats>> it = mAppScanStats.entrySet().iterator();
diff --git a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java
index 6a3e2b3..25133fd 100644
--- a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java
+++ b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java
@@ -31,12 +31,12 @@
import com.android.bluetooth.btservice.AdapterService;
import com.android.internal.annotations.VisibleForTesting;
-import java.util.HashSet;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArraySet;
/**
- * Manages distnace measurement operations and interacts with Gabeldorsche stack.
+ * Manages distance measurement operations and interacts with Gabeldorsche stack.
*
* @hide
*/
@@ -52,12 +52,10 @@
private final AdapterService mAdapterService;
private HandlerThread mHandlerThread;
DistanceMeasurementNativeInterface mDistanceMeasurementNativeInterface;
- private ConcurrentHashMap<String, HashSet<DistanceMeasurementTracker>> mRssiTrackers =
- new ConcurrentHashMap<>();
+ private final ConcurrentHashMap<String, CopyOnWriteArraySet<DistanceMeasurementTracker>>
+ mRssiTrackers = new ConcurrentHashMap<>();
- /**
- * Constructor of {@link DistanceMeasurementManager}.
- */
+ /** Constructor of {@link DistanceMeasurementManager}. */
DistanceMeasurementManager(AdapterService adapterService) {
mAdapterService = adapterService;
@@ -111,14 +109,13 @@
}
private synchronized void startRssiTracker(DistanceMeasurementTracker tracker) {
- mRssiTrackers.putIfAbsent(tracker.mIdentityAddress,
- new HashSet<DistanceMeasurementTracker>());
- HashSet<DistanceMeasurementTracker> set = mRssiTrackers.get(tracker.mIdentityAddress);
- if (set.contains(tracker)) {
+ mRssiTrackers.putIfAbsent(tracker.mIdentityAddress, new CopyOnWriteArraySet<>());
+ CopyOnWriteArraySet<DistanceMeasurementTracker> set =
+ mRssiTrackers.get(tracker.mIdentityAddress);
+ if (!set.add(tracker)) {
Log.w(TAG, "Already registered");
return;
}
- set.add(tracker);
mDistanceMeasurementNativeInterface.startDistanceMeasurement(tracker.mIdentityAddress,
tracker.mFrequency, DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI);
}
@@ -151,7 +148,7 @@
private synchronized int stopRssiTracker(UUID uuid, String identityAddress,
boolean timeout) {
- HashSet<DistanceMeasurementTracker> set = mRssiTrackers.get(identityAddress);
+ CopyOnWriteArraySet<DistanceMeasurementTracker> set = mRssiTrackers.get(identityAddress);
if (set == null) {
Log.w(TAG, "Can't find rssi tracker");
return BluetoothStatusCodes.ERROR_DISTANCE_MEASUREMENT_INTERNAL;
@@ -231,7 +228,7 @@
}
void handleRssiStarted(String address) {
- HashSet<DistanceMeasurementTracker> set = mRssiTrackers.get(address);
+ CopyOnWriteArraySet<DistanceMeasurementTracker> set = mRssiTrackers.get(address);
if (set == null) {
Log.w(TAG, "Can't find rssi tracker");
return;
@@ -262,7 +259,7 @@
}
void handleRssiStartFail(String address, int reason) {
- HashSet<DistanceMeasurementTracker> set = mRssiTrackers.get(address);
+ CopyOnWriteArraySet<DistanceMeasurementTracker> set = mRssiTrackers.get(address);
if (set == null) {
Log.w(TAG, "Can't find rssi tracker");
return;
@@ -272,9 +269,7 @@
invokeStartFail(tracker.mCallback, tracker.mDevice, reason);
}
}
- synchronized (set) {
- set.removeIf(tracker -> !tracker.mStarted);
- }
+ set.removeIf(tracker -> !tracker.mStarted);
}
void onDistanceMeasurementStopped(String address, int reason, int method) {
@@ -290,7 +285,7 @@
}
void handleRssiStopped(String address, int reason) {
- HashSet<DistanceMeasurementTracker> set = mRssiTrackers.get(address);
+ CopyOnWriteArraySet<DistanceMeasurementTracker> set = mRssiTrackers.get(address);
if (set == null) {
Log.w(TAG, "Can't find rssi tracker");
return;
@@ -301,9 +296,7 @@
invokeOnStopped(tracker.mCallback, tracker.mDevice, reason);
}
}
- synchronized (set) {
- set.removeIf(tracker -> tracker.mStarted);
- }
+ set.removeIf(tracker -> tracker.mStarted);
}
void onDistanceMeasurementResult(String address, int centimeter, int errorCentimeter,
@@ -323,7 +316,7 @@
}
void handleRssiResult(String address, DistanceMeasurementResult result) {
- HashSet<DistanceMeasurementTracker> set = mRssiTrackers.get(address);
+ CopyOnWriteArraySet<DistanceMeasurementTracker> set = mRssiTrackers.get(address);
if (set == null) {
Log.w(TAG, "Can't find rssi tracker");
return;
diff --git a/android/app/src/com/android/bluetooth/gatt/GattObjectsFactory.java b/android/app/src/com/android/bluetooth/gatt/GattObjectsFactory.java
index 8d6e2d5..3cc02b8 100644
--- a/android/app/src/com/android/bluetooth/gatt/GattObjectsFactory.java
+++ b/android/app/src/com/android/bluetooth/gatt/GattObjectsFactory.java
@@ -22,7 +22,6 @@
import com.android.bluetooth.Utils;
import com.android.bluetooth.btservice.AdapterService;
import com.android.bluetooth.btservice.BluetoothAdapterProxy;
-import com.android.bluetooth.flags.FeatureFlags;
import com.android.bluetooth.le_scan.PeriodicScanManager;
import com.android.bluetooth.le_scan.ScanManager;
import com.android.bluetooth.le_scan.ScanNativeInterface;
@@ -86,10 +85,8 @@
GattService service,
AdapterService adapterService,
BluetoothAdapterProxy bluetoothAdapterProxy,
- Looper looper,
- FeatureFlags featureFlags) {
- return new ScanManager(
- service, adapterService, bluetoothAdapterProxy, looper, featureFlags);
+ Looper looper) {
+ return new ScanManager(service, adapterService, bluetoothAdapterProxy, looper);
}
public PeriodicScanManager createPeriodicScanManager(AdapterService adapterService) {
diff --git a/android/app/src/com/android/bluetooth/gatt/GattService.java b/android/app/src/com/android/bluetooth/gatt/GattService.java
index b3d5667..1ef61f3 100644
--- a/android/app/src/com/android/bluetooth/gatt/GattService.java
+++ b/android/app/src/com/android/bluetooth/gatt/GattService.java
@@ -93,13 +93,12 @@
import com.android.bluetooth.btservice.CompanionManager;
import com.android.bluetooth.btservice.MetricsLogger;
import com.android.bluetooth.btservice.ProfileService;
-import com.android.bluetooth.flags.FeatureFlags;
-import com.android.bluetooth.flags.FeatureFlagsImpl;
import com.android.bluetooth.flags.Flags;
import com.android.bluetooth.le_scan.AppScanStats;
import com.android.bluetooth.le_scan.PeriodicScanManager;
import com.android.bluetooth.le_scan.ScanClient;
import com.android.bluetooth.le_scan.ScanManager;
+import com.android.bluetooth.le_scan.TransitionalScanHelper;
import com.android.bluetooth.util.NumberUtils;
import com.android.internal.annotations.VisibleForTesting;
import com.android.modules.utils.SynchronousResultReceiver;
@@ -213,7 +212,7 @@
/**
* Keep the arguments passed in for the PendingIntent.
*/
- class PendingIntentInfo {
+ public static class PendingIntentInfo {
public PendingIntent intent;
public ScanSettings settings;
public List<ScanFilter> filters;
@@ -237,12 +236,7 @@
}
};
- /**
- * List of our registered scanners.
- */
- public static class ScannerMap extends ContextMap<IScannerCallback, PendingIntentInfo> {}
-
- public ScannerMap mScannerMap = new ScannerMap();
+ public final TransitionalScanHelper mTransitionalScanHelper = new TransitionalScanHelper();
/**
* List of our registered advertisers.
@@ -292,7 +286,6 @@
*/
private final HashMap<String, Integer> mPermits = new HashMap<>();
- private FeatureFlags mFeatureFlags;
private AdapterService mAdapterService;
private BluetoothAdapterProxy mBluetoothAdapterProxy;
AdvertiseManager mAdvertiseManager;
@@ -346,7 +339,7 @@
}
@Override
- protected void start() {
+ public void start() {
if (DBG) {
Log.d(TAG, "start()");
}
@@ -357,7 +350,6 @@
mNativeInterface = GattObjectsFactory.getInstance().getNativeInterface();
mNativeInterface.init(this);
mAdapterService = AdapterService.getAdapterService();
- mFeatureFlags = new FeatureFlagsImpl();
mBluetoothAdapterProxy = BluetoothAdapterProxy.getInstance();
mCompanionManager = getSystemService(CompanionDeviceManager.class);
mAppOps = getSystemService(AppOpsManager.class);
@@ -373,11 +365,7 @@
mScanManager =
GattObjectsFactory.getInstance()
.createScanManager(
- this,
- mAdapterService,
- mBluetoothAdapterProxy,
- thread.getLooper(),
- mFeatureFlags);
+ this, mAdapterService, mBluetoothAdapterProxy, thread.getLooper());
mPeriodicScanManager = GattObjectsFactory.getInstance()
.createPeriodicScanManager(mAdapterService);
@@ -390,11 +378,11 @@
}
@Override
- protected void stop() {
+ public void stop() {
if (DBG) {
Log.d(TAG, "stop()");
}
- mScannerMap.clear();
+ mTransitionalScanHelper.getScannerMap().clear();
mAdvertiserMap.clear();
mClientMap.clear();
if (Flags.gattCleanupRestrictedHandles()) {
@@ -407,7 +395,7 @@
}
@Override
- protected void cleanup() {
+ public void cleanup() {
if (DBG) {
Log.d(TAG, "cleanup()");
}
@@ -2020,7 +2008,8 @@
byte[] legacyAdvData = Arrays.copyOfRange(advData, 0, 62);
for (ScanClient client : mScanManager.getRegularScanQueue()) {
- ScannerMap.App app = mScannerMap.getById(client.scannerId);
+ TransitionalScanHelper.ScannerMap.App app =
+ mTransitionalScanHelper.getScannerMap().getById(client.scannerId);
if (app == null) {
if (VDBG) {
Log.d(TAG, "App is null; skip.");
@@ -2112,7 +2101,7 @@
if (Flags.leScanFixRemoteException()) {
handleDeadScanClient(client);
} else {
- mScannerMap.remove(client.scannerId);
+ mTransitionalScanHelper.getScannerMap().remove(client.scannerId);
mScanManager.stopScan(client.scannerId);
}
}
@@ -2161,7 +2150,8 @@
}
// First check the callback map
- ScannerMap.App cbApp = mScannerMap.getByUuid(uuid);
+ TransitionalScanHelper.ScannerMap.App cbApp =
+ mTransitionalScanHelper.getScannerMap().getByUuid(uuid);
if (cbApp != null) {
if (status == 0) {
cbApp.id = scannerId;
@@ -2173,7 +2163,7 @@
continuePiStartScan(scannerId, cbApp);
}
} else {
- mScannerMap.remove(scannerId);
+ mTransitionalScanHelper.getScannerMap().remove(scannerId);
}
if (cbApp.callback != null) {
cbApp.callback.onScannerRegistered(status, scannerId);
@@ -2802,7 +2792,8 @@
Set<ScanResult> results = parseBatchScanResults(numRecords, reportType, recordData);
if (reportType == ScanManager.SCAN_RESULT_TYPE_TRUNCATED) {
// We only support single client for truncated mode.
- ScannerMap.App app = mScannerMap.getById(scannerId);
+ TransitionalScanHelper.ScannerMap.App app =
+ mTransitionalScanHelper.getScannerMap().getById(scannerId);
if (app == null) {
return;
}
@@ -2853,7 +2844,7 @@
mScanManager.callbackDone(scannerId, status);
}
- private void sendBatchScanResults(ScannerMap.App app, ScanClient client,
+ private void sendBatchScanResults(TransitionalScanHelper.ScannerMap.App app, ScanClient client,
ArrayList<ScanResult> results) {
try {
if (app.callback != null) {
@@ -2880,7 +2871,7 @@
if (Flags.leScanFixRemoteException()) {
handleDeadScanClient(client);
} else {
- mScannerMap.remove(client.scannerId);
+ mTransitionalScanHelper.getScannerMap().remove(client.scannerId);
mScanManager.stopScan(client.scannerId);
}
}
@@ -2889,7 +2880,8 @@
// Check and deliver scan results for different scan clients.
private void deliverBatchScan(ScanClient client, Set<ScanResult> allResults)
throws RemoteException {
- ScannerMap.App app = mScannerMap.getById(client.scannerId);
+ TransitionalScanHelper.ScannerMap.App app =
+ mTransitionalScanHelper.getScannerMap().getById(client.scannerId);
if (app == null) {
return;
}
@@ -3050,7 +3042,8 @@
+ trackingInfo.getAdvState());
}
- ScannerMap.App app = mScannerMap.getById(trackingInfo.getClientIf());
+ TransitionalScanHelper.ScannerMap.App app =
+ mTransitionalScanHelper.getScannerMap().getById(trackingInfo.getClientIf());
if (app == null || (app.callback == null && app.info == null)) {
Log.e(TAG, "app or callback is null");
return;
@@ -3096,7 +3089,8 @@
}
void onScanParamSetupCompleted(int status, int scannerId) throws RemoteException {
- ScannerMap.App app = mScannerMap.getById(scannerId);
+ TransitionalScanHelper.ScannerMap.App app =
+ mTransitionalScanHelper.getScannerMap().getById(scannerId);
if (app == null || app.callback == null) {
Log.e(TAG, "Advertise app or callback is null");
return;
@@ -3108,7 +3102,8 @@
// callback from ScanManager for dispatch of errors apps.
public void onScanManagerErrorCallback(int scannerId, int errorCode) throws RemoteException {
- ScannerMap.App app = mScannerMap.getById(scannerId);
+ TransitionalScanHelper.ScannerMap.App app =
+ mTransitionalScanHelper.getScannerMap().getById(scannerId);
if (app == null || (app.callback == null && app.info == null)) {
Log.e(TAG, "App or callback is null");
return;
@@ -3225,7 +3220,8 @@
enforceImpersonatationPermissionIfNeeded(workSource);
- AppScanStats app = mScannerMap.getAppScanStatsByUid(Binder.getCallingUid());
+ AppScanStats app = mTransitionalScanHelper.getScannerMap()
+ .getAppScanStatsByUid(Binder.getCallingUid());
if (app != null && app.isScanningTooFrequently()
&& !Utils.checkCallerHasPrivilegedPermission(this)) {
Log.e(TAG, "App '" + app.appName + "' is scanning too frequently");
@@ -3233,7 +3229,8 @@
return;
}
- mScannerMap.add(uuid, workSource, callback, null, this);
+ mTransitionalScanHelper
+ .getScannerMap().add(uuid, workSource, callback, null, this);
mScanManager.registerScanner(uuid);
}
@@ -3247,7 +3244,7 @@
if (DBG) {
Log.d(TAG, "unregisterScanner() - scannerId=" + scannerId);
}
- mScannerMap.remove(scannerId);
+ mTransitionalScanHelper.getScannerMap().remove(scannerId);
mScanManager.unregisterScanner(scannerId);
}
@@ -3319,8 +3316,9 @@
Utils.checkCallerHasScanWithoutLocationPermission(this);
scanClient.associatedDevices = getAssociatedDevices(callingPackage);
- AppScanStats app = mScannerMap.getAppScanStatsById(scannerId);
- ScannerMap.App cbApp = mScannerMap.getById(scannerId);
+ AppScanStats app = mTransitionalScanHelper.getScannerMap().getAppScanStatsById(scannerId);
+ TransitionalScanHelper.ScannerMap.App cbApp =
+ mTransitionalScanHelper.getScannerMap().getById(scannerId);
if (app != null) {
scanClient.stats = app;
boolean isFilteredScan = (filters != null) && !filters.isEmpty();
@@ -3367,12 +3365,13 @@
}
// Don't start scan if the Pi scan already in mScannerMap.
- if (mScannerMap.getByContextInfo(piInfo) != null) {
+ if (mTransitionalScanHelper.getScannerMap().getByContextInfo(piInfo) != null) {
Log.d(TAG, "Don't startScan(PI) since the same Pi scan already in mScannerMap.");
return;
}
- ScannerMap.App app = mScannerMap.add(uuid, null, null, piInfo, this);
+ TransitionalScanHelper.ScannerMap.App app =
+ mTransitionalScanHelper.getScannerMap().add(uuid, null, null, piInfo, this);
app.mUserHandle = UserHandle.getUserHandleForUid(Binder.getCallingUid());
mAppOps.checkPackage(Binder.getCallingUid(), callingPackage);
@@ -3412,7 +3411,7 @@
}
}
- void continuePiStartScan(int scannerId, ScannerMap.App app) {
+ void continuePiStartScan(int scannerId, TransitionalScanHelper.ScannerMap.App app) {
final PendingIntentInfo piInfo = app.info;
final ScanClient scanClient =
new ScanClient(scannerId, piInfo.settings, piInfo.filters, piInfo.callingUid);
@@ -3427,7 +3426,8 @@
scanClient.associatedDevices = app.mAssociatedDevices;
scanClient.hasDisavowedLocation = app.mHasDisavowedLocation;
- AppScanStats scanStats = mScannerMap.getAppScanStatsById(scannerId);
+ AppScanStats scanStats =
+ mTransitionalScanHelper.getScannerMap().getAppScanStatsById(scannerId);
if (scanStats != null) {
scanClient.stats = scanStats;
boolean isFilteredScan = (piInfo.filters != null) && !piInfo.filters.isEmpty();
@@ -3463,7 +3463,7 @@
}
AppScanStats app = null;
- app = mScannerMap.getAppScanStatsById(scannerId);
+ app = mTransitionalScanHelper.getScannerMap().getAppScanStatsById(scannerId);
if (app != null) {
app.recordScanStop(scannerId);
}
@@ -3479,7 +3479,8 @@
}
PendingIntentInfo pii = new PendingIntentInfo();
pii.intent = intent;
- ScannerMap.App app = mScannerMap.getByContextInfo(pii);
+ TransitionalScanHelper.ScannerMap.App app =
+ mTransitionalScanHelper.getScannerMap().getByContextInfo(pii);
if (VDBG) {
Log.d(TAG, "stopScan(PendingIntent): app found = " + app);
}
@@ -5102,8 +5103,9 @@
void dumpRegisterId(StringBuilder sb) {
sb.append(" Scanner:\n");
- for (Integer appId : mScannerMap.getAllAppsIds()) {
- println(sb, " app_if: " + appId + ", appName: " + mScannerMap.getById(appId).name);
+ for (Integer appId : mTransitionalScanHelper.getScannerMap().getAllAppsIds()) {
+ println(sb, " app_if: " + appId + ", appName: " +
+ mTransitionalScanHelper.getScannerMap().getById(appId).name);
}
sb.append(" Client:\n");
for (Integer appId : mClientMap.getAllAppsIds()) {
@@ -5130,7 +5132,7 @@
dumpRegisterId(sb);
sb.append("GATT Scanner Map\n");
- mScannerMap.dump(sb);
+ mTransitionalScanHelper.getScannerMap().dump(sb);
sb.append("GATT Advertiser Map\n");
mAdvertiserMap.dumpAdvertiser(sb);
diff --git a/android/app/src/com/android/bluetooth/hap/HapClientService.java b/android/app/src/com/android/bluetooth/hap/HapClientService.java
index b4fabb8..dc8159f 100644
--- a/android/app/src/com/android/bluetooth/hap/HapClientService.java
+++ b/android/app/src/com/android/bluetooth/hap/HapClientService.java
@@ -33,7 +33,6 @@
import android.bluetooth.IBluetoothHapClient;
import android.bluetooth.IBluetoothHapClientCallback;
import android.content.AttributionSource;
-import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
@@ -51,8 +50,7 @@
import com.android.bluetooth.btservice.ServiceFactory;
import com.android.bluetooth.btservice.storage.DatabaseManager;
import com.android.bluetooth.csip.CsipSetCoordinatorService;
-import com.android.bluetooth.flags.FeatureFlags;
-import com.android.bluetooth.flags.FeatureFlagsImpl;
+import com.android.bluetooth.flags.Flags;
import com.android.internal.annotations.VisibleForTesting;
import com.android.modules.utils.SynchronousResultReceiver;
@@ -90,7 +88,6 @@
private final Map<BluetoothDevice, Integer> mDeviceFeaturesMap = new HashMap<>();
private final Map<BluetoothDevice, List<BluetoothHapPresetInfo>> mPresetsMap =
new HashMap<>();
- private final FeatureFlags mFeatureFlags;
@VisibleForTesting
RemoteCallbackList<IBluetoothHapClientCallback> mCallbacks;
@@ -127,13 +124,13 @@
return sHapClient;
}
- public HapClientService(Context ctx) {
- super(ctx);
- mFeatureFlags = new FeatureFlagsImpl();
+ public HapClientService(AdapterService adapterService) {
+ super(adapterService);
+ mAdapterService = Objects.requireNonNull(adapterService);
}
@Override
- protected void cleanup() {
+ public void cleanup() {
if (DBG) {
Log.d(TAG, "cleanup()");
}
@@ -145,7 +142,7 @@
}
@Override
- protected void start() {
+ public void start() {
if (DBG) {
Log.d(TAG, "start()");
}
@@ -154,12 +151,12 @@
throw new IllegalStateException("start() called twice");
}
- // Get AdapterService, HapClientNativeInterface, DatabaseManager, AudioManager.
+ // Get HapClientNativeInterface, DatabaseManager, AudioManager.
// None of them can be null.
- mAdapterService = Objects.requireNonNull(AdapterService.getAdapterService(),
- "AdapterService cannot be null when HapClientService starts");
- mDatabaseManager = Objects.requireNonNull(mAdapterService.getDatabase(),
- "DatabaseManager cannot be null when HapClientService starts");
+ mDatabaseManager =
+ Objects.requireNonNull(
+ mAdapterService.getDatabase(),
+ "DatabaseManager cannot be null when HapClientService starts");
mHapClientNativeInterface = Objects.requireNonNull(
HapClientNativeInterface.getInstance(),
"HapClientNativeInterface cannot be null when HapClientService starts");
@@ -180,7 +177,7 @@
}
@Override
- protected void stop() {
+ public void stop() {
if (DBG) {
Log.d(TAG, "stop()");
}
@@ -229,9 +226,6 @@
if (mCallbacks != null) {
mCallbacks.kill();
}
-
- // Clear AdapterService
- mAdapterService = null;
}
/** Process a change in the bonding state for a device */
@@ -443,7 +437,7 @@
removeStateMachine(device);
}
}
- if (!mFeatureFlags.audioRoutingCentralization()) {
+ if (!Flags.audioRoutingCentralization()) {
ActiveDeviceManager adManager = mAdapterService.getActiveDeviceManager();
if (adManager != null) {
adManager.profileConnectionStateChanged(
diff --git a/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java b/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java
index 0da9e19..5937b07 100644
--- a/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java
+++ b/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java
@@ -51,8 +51,7 @@
import com.android.bluetooth.btservice.ProfileService;
import com.android.bluetooth.btservice.ServiceFactory;
import com.android.bluetooth.btservice.storage.DatabaseManager;
-import com.android.bluetooth.flags.FeatureFlags;
-import com.android.bluetooth.flags.FeatureFlagsImpl;
+import com.android.bluetooth.flags.Flags;
import com.android.internal.annotations.VisibleForTesting;
import com.android.modules.utils.SynchronousResultReceiver;
@@ -78,7 +77,6 @@
private static final int MAX_HEARING_AID_STATE_MACHINES = 10;
private static HearingAidService sHearingAidService;
- private FeatureFlags mFeatureFlags = new FeatureFlagsImpl();
private AdapterService mAdapterService;
private DatabaseManager mDatabaseManager;
private HandlerThread mStateMachinesThread;
@@ -119,7 +117,7 @@
}
@Override
- protected void start() {
+ public void start() {
if (DBG) {
Log.d(TAG, "start()");
}
@@ -155,7 +153,7 @@
}
@Override
- protected void stop() {
+ public void stop() {
if (DBG) {
Log.d(TAG, "stop()");
}
@@ -209,7 +207,7 @@
}
@Override
- protected void cleanup() {
+ public void cleanup() {
if (DBG) {
Log.d(TAG, "cleanup()");
}
@@ -721,11 +719,6 @@
sendBroadcast(intent, BLUETOOTH_CONNECT);
}
- @VisibleForTesting
- void setFeatureFlags(FeatureFlags featureFlags) {
- mFeatureFlags = featureFlags;
- }
-
/* Notifications of audio device disconnection events. */
private class AudioManagerOnAudioDevicesRemovedCallback extends AudioDeviceCallback {
@Override
@@ -1062,7 +1055,7 @@
try {
HearingAidService service = getService(source);
if (service != null) {
- if (service.mFeatureFlags.audioRoutingCentralization()) {
+ if (Flags.audioRoutingCentralization()) {
((AudioRoutingManager) service.mAdapterService.getActiveDeviceManager())
.activateDeviceProfile(
device, BluetoothProfile.HEARING_AID, receiver);
diff --git a/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java b/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java
index ac4620c..d4872cc 100644
--- a/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java
+++ b/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java
@@ -169,24 +169,24 @@
}
public void handleCscsCommand(String atString, int type, BluetoothDevice device) {
- log("handleCscsCommand - atString = " + atString);
+ Log.d(TAG, "handleCscsCommand - atString = " + atString);
// Select Character Set
int atCommandResult = HeadsetHalConstants.AT_RESPONSE_ERROR;
int atCommandErrorCode = -1;
String atCommandResponse = null;
switch (type) {
case TYPE_READ: // Read
- log("handleCscsCommand - Read Command");
+ Log.d(TAG, "handleCscsCommand - Read Command");
atCommandResponse = "+CSCS: \"" + mCharacterSet + "\"";
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
break;
case TYPE_TEST: // Test
- log("handleCscsCommand - Test Command");
+ Log.d(TAG, "handleCscsCommand - Test Command");
atCommandResponse = ("+CSCS: (\"UTF-8\",\"IRA\",\"GSM\")");
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
break;
case TYPE_SET: // Set
- log("handleCscsCommand - Set Command");
+ Log.d(TAG, "handleCscsCommand - Set Command");
String[] args = atString.split("=");
if (args.length < 2 || args[1] == null) {
mNativeInterface.atResponseCode(device, atCommandResult, atCommandErrorCode);
@@ -204,7 +204,7 @@
break;
case TYPE_UNKNOWN:
default:
- log("handleCscsCommand - Invalid chars");
+ Log.d(TAG, "handleCscsCommand - Invalid chars");
atCommandErrorCode = BluetoothCmeError.TEXT_HAS_INVALID_CHARS;
}
if (atCommandResponse != null) {
@@ -215,13 +215,13 @@
public void handleCpbsCommand(String atString, int type, BluetoothDevice device) {
// Select PhoneBook memory Storage
- log("handleCpbsCommand - atString = " + atString);
+ Log.d(TAG, "handleCpbsCommand - atString = " + atString);
int atCommandResult = HeadsetHalConstants.AT_RESPONSE_ERROR;
int atCommandErrorCode = -1;
String atCommandResponse = null;
switch (type) {
case TYPE_READ: // Read
- log("handleCpbsCommand - read command");
+ Log.d(TAG, "handleCpbsCommand - read command");
// Return current size and max size
if ("SM".equals(mCurrentPhonebook)) {
atCommandResponse = "+CPBS: \"SM\",0," + getMaxPhoneBookSize(0);
@@ -242,12 +242,12 @@
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
break;
case TYPE_TEST: // Test
- log("handleCpbsCommand - test command");
+ Log.d(TAG, "handleCpbsCommand - test command");
atCommandResponse = ("+CPBS: (\"ME\",\"SM\",\"DC\",\"RC\",\"MC\")");
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
break;
case TYPE_SET: // Set
- log("handleCpbsCommand - set command");
+ Log.d(TAG, "handleCpbsCommand - set command");
String[] args = atString.split("=");
// Select phonebook memory
if (args.length < 2 || args[1] == null) {
@@ -263,7 +263,7 @@
}
if (getPhonebookResult(pb, false) == null && !"SM".equals(pb)) {
if (DBG) {
- log("Dont know phonebook: '" + pb + "'");
+ Log.d(TAG, "Dont know phonebook: '" + pb + "'");
}
atCommandErrorCode = BluetoothCmeError.OPERATION_NOT_ALLOWED;
break;
@@ -273,7 +273,7 @@
break;
case TYPE_UNKNOWN:
default:
- log("handleCpbsCommand - invalid chars");
+ Log.d(TAG, "handleCpbsCommand - invalid chars");
atCommandErrorCode = BluetoothCmeError.TEXT_HAS_INVALID_CHARS;
}
if (atCommandResponse != null) {
@@ -283,7 +283,7 @@
}
void handleCpbrCommand(String atString, int type, BluetoothDevice remoteDevice) {
- log("handleCpbrCommand - atString = " + atString);
+ Log.d(TAG, "handleCpbrCommand - atString = " + atString);
int atCommandResult = HeadsetHalConstants.AT_RESPONSE_ERROR;
int atCommandErrorCode = -1;
String atCommandResponse = null;
@@ -294,7 +294,7 @@
* Parrot CK3300. So instead send just the range of currently
* valid index's.
*/
- log("handleCpbrCommand - test command");
+ Log.d(TAG, "handleCpbrCommand - test command");
int size;
if ("SM".equals(mCurrentPhonebook)) {
size = 0;
@@ -307,7 +307,7 @@
break;
}
size = pbr.cursor.getCount();
- log("handleCpbrCommand - size = " + size);
+ Log.d(TAG, "handleCpbrCommand - size = " + size);
pbr.cursor.close();
pbr.cursor = null;
}
@@ -325,7 +325,7 @@
case TYPE_SET: // Set & read
// Phone Book Read Request
// AT+CPBR=<index1>[,<index2>]
- log("handleCpbrCommand - set/read command");
+ Log.d(TAG, "handleCpbrCommand - set/read command");
if (mCpbrIndex1 != -1) {
/* handling a CPBR at the moment, reject this CPBR command */
atCommandErrorCode = BluetoothCmeError.OPERATION_NOT_ALLOWED;
@@ -355,7 +355,7 @@
index2 = Integer.parseInt(indices[1]);
}
} catch (Exception e) {
- log("handleCpbrCommand - exception - invalid chars: " + e.toString());
+ Log.d(TAG, "handleCpbrCommand - exception - invalid chars: " + e.toString());
atCommandErrorCode = BluetoothCmeError.TEXT_HAS_INVALID_CHARS;
mNativeInterface.atResponseCode(remoteDevice, atCommandResult,
atCommandErrorCode);
@@ -386,7 +386,7 @@
break;
case TYPE_UNKNOWN:
default:
- log("handleCpbrCommand - invalid chars");
+ Log.d(TAG, "handleCpbrCommand - invalid chars");
atCommandErrorCode = BluetoothCmeError.TEXT_HAS_INVALID_CHARS;
mNativeInterface.atResponseCode(remoteDevice, atCommandResult, atCommandErrorCode);
}
@@ -505,7 +505,7 @@
// process CPBR command after permission check
/*package*/ int processCpbrCommand(BluetoothDevice device) {
- log("processCpbrCommand");
+ Log.d(TAG, "processCpbrCommand");
int atCommandResult = HeadsetHalConstants.AT_RESPONSE_ERROR;
int atCommandErrorCode = -1;
String atCommandResponse = null;
@@ -546,7 +546,7 @@
atCommandResult = HeadsetHalConstants.AT_RESPONSE_OK;
int errorDetected = -1; // no error
pbr.cursor.moveToPosition(mCpbrIndex1 - 1);
- log("mCpbrIndex1 = " + mCpbrIndex1 + " and mCpbrIndex2 = " + mCpbrIndex2);
+ Log.d(TAG, "mCpbrIndex1 = " + mCpbrIndex1 + " and mCpbrIndex2 = " + mCpbrIndex2);
for (int index = mCpbrIndex1; index <= mCpbrIndex2; index++) {
String number = pbr.cursor.getString(pbr.numberColumn);
String name = null;
@@ -573,14 +573,16 @@
}
c.close();
}
- if (DBG && name == null) {
- log("Caller ID lookup failed for " + number);
+ if (name == null) {
+ if (DBG) {
+ Log.d(TAG, "Caller ID lookup failed for " + number);
+ }
}
} else if (pbr.nameColumn != -1) {
name = pbr.cursor.getString(pbr.nameColumn);
} else {
- log("processCpbrCommand: empty name and number");
+ Log.d(TAG, "processCpbrCommand: empty name and number");
}
if (name == null) {
name = "";
@@ -652,11 +654,11 @@
*/
@VisibleForTesting
int checkAccessPermission(BluetoothDevice remoteDevice) {
- log("checkAccessPermission");
+ Log.d(TAG, "checkAccessPermission");
int permission = remoteDevice.getPhonebookAccessPermission();
if (permission == BluetoothDevice.ACCESS_UNKNOWN) {
- log("checkAccessPermission - ACTION_CONNECTION_ACCESS_REQUEST");
+ Log.d(TAG, "checkAccessPermission - ACTION_CONNECTION_ACCESS_REQUEST");
Intent intent = new Intent(BluetoothDevice.ACTION_CONNECTION_ACCESS_REQUEST);
intent.setPackage(mPairingPackage);
intent.putExtra(BluetoothDevice.EXTRA_ACCESS_REQUEST_TYPE,
@@ -690,8 +692,4 @@
return "O";
}
}
-
- private static void log(String msg) {
- Log.d(TAG, msg);
- }
}
diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java b/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java
index cc7e385..8bb016f 100644
--- a/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java
@@ -22,6 +22,7 @@
import com.android.bluetooth.Utils;
import com.android.bluetooth.btservice.AdapterService;
+import com.android.bluetooth.flags.Flags;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
@@ -91,7 +92,11 @@
// Set bt_stack's active device to default if java layer set active device to null
return Utils.getBytesFromAddress("00:00:00:00:00:00");
}
- return mAdapterService.getByteIdentityAddress(device);
+ if (Flags.identityAddressNullIfUnknown()) {
+ return Utils.getByteBrEdrAddress(device);
+ } else {
+ return mAdapterService.getByteIdentityAddress(device);
+ }
}
void onConnectionStateChanged(int state, byte[] address) {
diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetService.java b/android/app/src/com/android/bluetooth/hfp/HeadsetService.java
index ef989ea..d6354dd 100644
--- a/android/app/src/com/android/bluetooth/hfp/HeadsetService.java
+++ b/android/app/src/com/android/bluetooth/hfp/HeadsetService.java
@@ -60,8 +60,7 @@
import com.android.bluetooth.btservice.ProfileService;
import com.android.bluetooth.btservice.ServiceFactory;
import com.android.bluetooth.btservice.storage.DatabaseManager;
-import com.android.bluetooth.flags.FeatureFlags;
-import com.android.bluetooth.flags.FeatureFlagsImpl;
+import com.android.bluetooth.flags.Flags;
import com.android.bluetooth.hfpclient.HeadsetClientService;
import com.android.bluetooth.hfpclient.HeadsetClientStateMachine;
import com.android.bluetooth.le_audio.LeAudioService;
@@ -126,7 +125,6 @@
// Timeout for state machine thread join, to prevent potential ANR.
private static final int SM_THREAD_JOIN_TIMEOUT_MS = 1000;
- private FeatureFlags mFeatureFlags = new FeatureFlagsImpl();
private int mMaxHeadsetConnections = 1;
private BluetoothDevice mActiveDevice;
private AdapterService mAdapterService;
@@ -170,7 +168,7 @@
}
@Override
- protected void start() {
+ public void start() {
Log.i(TAG, "start()");
if (mStarted) {
throw new IllegalStateException("start() called twice");
@@ -213,7 +211,7 @@
}
@Override
- protected void stop() {
+ public void stop() {
Log.i(TAG, "stop()");
if (!mStarted) {
Log.w(TAG, "stop() called before start()");
@@ -283,7 +281,7 @@
}
@Override
- protected void cleanup() {
+ public void cleanup() {
Log.i(TAG, "cleanup");
}
@@ -851,7 +849,7 @@
try {
HeadsetService service = getService(source);
if (service != null) {
- if (service.mFeatureFlags.audioRoutingCentralization()) {
+ if (Flags.audioRoutingCentralization()) {
((AudioRoutingManager) service.mAdapterService.getActiveDeviceManager())
.activateDeviceProfile(device, BluetoothProfile.HEADSET, receiver);
} else {
diff --git a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java
index cccdbd5..0de2e09 100644
--- a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java
+++ b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java
@@ -101,7 +101,7 @@
}
@Override
- protected void start() {
+ public void start() {
synchronized (mStartStopLock) {
if (DBG) {
Log.d(TAG, "start()");
@@ -155,7 +155,7 @@
}
@Override
- protected void stop() {
+ public void stop() {
synchronized (mStartStopLock) {
synchronized (HeadsetClientService.class) {
if (sHeadsetClientService == null) {
diff --git a/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java b/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java
index 347a534..f50405f 100644
--- a/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java
+++ b/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java
@@ -38,10 +38,11 @@
// Lifecycle of a Device Block is managed entirely by the Service which creates it. In essence it
// has only the active state otherwise the block should be GCed.
public class HfpClientDeviceBlock {
- private static final String KEY_SCO_STATE = "com.android.bluetooth.hfpclient.SCO_STATE";
+ private static final String TAG = "HfpClientDeviceBlock";
private static final boolean DBG = false;
- private final String mTAG;
+ private static final String KEY_SCO_STATE = "com.android.bluetooth.hfpclient.SCO_STATE";
+
private final BluetoothDevice mDevice;
private final PhoneAccount mPhoneAccount;
private final Map<UUID, HfpClientConnection> mConnections = new HashMap<>();
@@ -56,7 +57,6 @@
mDevice = device;
mConnServ = connServ;
mServiceInterface = serviceInterface;
- mTAG = "HfpClientDeviceBlock." + mDevice;
mPhoneAccount = mConnServ.createAccount(device);
mTelecomManager = mConnServ.getSystemService(TelecomManager.class);
@@ -66,20 +66,16 @@
mTelecomManager.setUserSelectedOutgoingPhoneAccount(mPhoneAccount.getAccountHandle());
mScoState = getScoStateFromDevice(device);
- if (DBG) {
- Log.d(mTAG, "SCO state = " + mScoState);
- }
+ debug("SCO state = " + mScoState);
List<HfpClientCall> calls = mServiceInterface.getCurrentCalls(mDevice);
- if (DBG) {
- Log.d(mTAG, "Got calls " + calls);
- }
+ debug("Got calls " + calls);
if (calls == null) {
// We can get null as a return if we are not connected. Hence there may
// be a race in getting the broadcast and HFP Client getting
// disconnected before broadcast gets delivered.
- Log.w(mTAG, "Got connected but calls were null, ignoring the broadcast");
+ warn("Got connected but calls were null, ignoring the broadcast");
return;
}
@@ -106,7 +102,7 @@
connection.onAdded();
return connection;
} else {
- Log.e(mTAG, "Call " + callUuid + " ignored: connection does not exist");
+ error("Call " + callUuid + " ignored: connection does not exist");
return null;
}
}
@@ -120,9 +116,7 @@
}
synchronized void onAudioStateChange(int newState, int oldState) {
- if (DBG) {
- Log.d(mTAG, "Call audio state changed " + oldState + " -> " + newState);
- }
+ debug("Call audio state changed " + oldState + " -> " + newState);
mScoState.putInt(KEY_SCO_STATE, newState);
for (HfpClientConnection connection : mConnections.values()) {
@@ -140,7 +134,7 @@
connection.onAdded();
return connection;
} else {
- Log.e(mTAG, "Call " + callUuid + " ignored: connection does not exist");
+ error("Call " + callUuid + " ignored: connection does not exist");
return null;
}
}
@@ -164,16 +158,14 @@
// Remove existing calls and the phone account associated, the object will get garbage
// collected soon
synchronized void cleanup() {
- Log.d(mTAG, "Resetting state for device " + mDevice);
+ debug("Resetting state for device " + mDevice);
disconnectAll();
mTelecomManager.unregisterPhoneAccount(mPhoneAccount.getAccountHandle());
}
// Handle call change
synchronized void handleCall(HfpClientCall call) {
- if (DBG) {
- Log.d(mTAG, "Got call " + call.toString());
- }
+ debug("Got call " + call.toString());
HfpClientConnection connection = findConnectionKey(call);
@@ -217,9 +209,7 @@
mTelecomManager.addNewIncomingCall(mPhoneAccount.getAccountHandle(), b);
}
} else if (call.getState() == HfpClientCall.CALL_STATE_TERMINATED) {
- if (DBG) {
- Log.d(mTAG, "Removing call " + call);
- }
+ debug("Removing call " + call);
mConnections.remove(call.getUUID());
}
@@ -228,9 +218,7 @@
// Find the connection specified by the key, also update the key with ID if present.
private synchronized HfpClientConnection findConnectionKey(HfpClientCall call) {
- if (DBG) {
- Log.d(mTAG, "findConnectionKey local key set " + mConnections.toString());
- }
+ debug("findConnectionKey local key set " + mConnections.toString());
return mConnections.get(call.getUUID());
}
@@ -250,9 +238,7 @@
private boolean isDisconnectingToActive(HfpClientConnection prevConn,
HfpClientCall newCall) {
- if (DBG) {
- Log.d(mTAG, "prevConn " + prevConn.isClosing() + " new call " + newCall.getState());
- }
+ debug("prevConn " + prevConn.isClosing() + " new call " + newCall.getState());
if (prevConn.isClosing() && prevConn.getCall().getState() != newCall.getState()
&& newCall.getState() != HfpClientCall.CALL_STATE_TERMINATED) {
return true;
@@ -263,21 +249,18 @@
private synchronized HfpClientConnection buildConnection(HfpClientCall call,
Uri number) {
if (call == null && number == null) {
- Log.e(mTAG, "Both call and number cannot be null.");
+ error("Both call and number cannot be null.");
return null;
}
- if (DBG) {
- Log.d(mTAG, "Creating connection on " + mDevice + " for " + call + "/" + number);
- }
+ debug("Creating connection on " + mDevice + " for " + call + "/" + number);
HfpClientConnection connection = (call != null
? new HfpClientConnection(mDevice, call, mConnServ, mServiceInterface)
: new HfpClientConnection(mDevice, number, mConnServ, mServiceInterface));
connection.setExtras(mScoState);
- if (DBG) {
- Log.d(mTAG, "Connection extras = " + connection.getExtras().toString());
- }
+
+ debug("Connection extras = " + connection.getExtras().toString());
if (connection.getState() != Connection.STATE_DISCONNECTED) {
mConnections.put(connection.getUUID(), connection);
@@ -289,19 +272,14 @@
// Updates any conferencable connections.
private void updateConferenceableConnections() {
boolean addConf = false;
- if (DBG) {
- Log.d(mTAG, "Existing connections: " + mConnections + " existing conference "
- + mConference);
- }
+ debug("Existing connections: " + mConnections + " existing conference " + mConference);
// If we have an existing conference call then loop through all connections and update any
// connections that may have switched from conference -> non-conference.
if (mConference != null) {
for (Connection confConn : mConference.getConnections()) {
if (!((HfpClientConnection) confConn).inConference()) {
- if (DBG) {
- Log.d(mTAG, "Removing connection " + confConn + " from conference.");
- }
+ debug("Removing connection " + confConn + " from conference.");
mConference.removeConnection(confConn);
}
}
@@ -319,9 +297,7 @@
mConference.setExtras(mScoState);
}
if (mConference.addConnection(otherConn)) {
- if (DBG) {
- Log.d(mTAG, "Adding connection " + otherConn + " to conference.");
- }
+ debug("Adding connection " + otherConn + " to conference.");
addConf = true;
}
}
@@ -329,9 +305,7 @@
// If we have no connections in the conference we should simply end it.
if (mConference != null && mConference.getConnections().size() == 0) {
- if (DBG) {
- Log.d(mTAG, "Conference has no connection, destroying");
- }
+ debug("Conference has no connection, destroying");
mConference.setDisconnected(new DisconnectCause(DisconnectCause.LOCAL));
mConference.destroy();
mConference = null;
@@ -339,9 +313,7 @@
// If we have a valid conference and not previously added then add it.
if (mConference != null && addConf) {
- if (DBG) {
- Log.d(mTAG, "Adding conference to stack.");
- }
+ debug("Adding conference to stack.");
mConnServ.addConference(mConference);
}
}
@@ -407,4 +379,20 @@
}
}
+
+ // Per-Device logging
+
+ public void debug(String message) {
+ if (DBG) {
+ Log.d(TAG, "[device=" + mDevice + "] " + message);
+ }
+ }
+
+ public void warn(String message) {
+ Log.w(TAG, "[device=" + mDevice + "] " + message);
+ }
+
+ public void error(String message) {
+ Log.e(TAG, "[device=" + mDevice + "] " + message);
+ }
}
diff --git a/android/app/src/com/android/bluetooth/hfpclient/NativeInterface.java b/android/app/src/com/android/bluetooth/hfpclient/NativeInterface.java
index 4ef93e7..a152a61 100644
--- a/android/app/src/com/android/bluetooth/hfpclient/NativeInterface.java
+++ b/android/app/src/com/android/bluetooth/hfpclient/NativeInterface.java
@@ -23,7 +23,9 @@
import android.bluetooth.BluetoothDevice;
import android.util.Log;
+import com.android.bluetooth.Utils;
import com.android.bluetooth.btservice.AdapterService;
+import com.android.bluetooth.flags.Flags;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
@@ -339,7 +341,11 @@
}
private byte[] getByteAddress(BluetoothDevice device) {
- return mAdapterService.getByteIdentityAddress(device);
+ if (Flags.identityAddressNullIfUnknown()) {
+ return Utils.getByteBrEdrAddress(device);
+ } else {
+ return mAdapterService.getByteIdentityAddress(device);
+ }
}
// Callbacks from the native back into the java framework. All callbacks are routed via the
diff --git a/android/app/src/com/android/bluetooth/hid/HidDeviceNativeInterface.java b/android/app/src/com/android/bluetooth/hid/HidDeviceNativeInterface.java
index 5aa7d24..d7e1ec5 100644
--- a/android/app/src/com/android/bluetooth/hid/HidDeviceNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/hid/HidDeviceNativeInterface.java
@@ -26,7 +26,9 @@
import android.bluetooth.BluetoothDevice;
import android.util.Log;
+import com.android.bluetooth.Utils;
import com.android.bluetooth.btservice.AdapterService;
+import com.android.bluetooth.flags.Flags;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
@@ -261,7 +263,11 @@
}
private byte[] getByteAddress(BluetoothDevice device) {
- return mAdapterService.getByteIdentityAddress(device);
+ if (Flags.identityAddressNullIfUnknown()) {
+ return Utils.getByteBrEdrAddress(device);
+ } else {
+ return mAdapterService.getByteIdentityAddress(device);
+ }
}
private native void initNative();
diff --git a/android/app/src/com/android/bluetooth/hid/HidDeviceService.java b/android/app/src/com/android/bluetooth/hid/HidDeviceService.java
index d54f92b..99f2beb 100644
--- a/android/app/src/com/android/bluetooth/hid/HidDeviceService.java
+++ b/android/app/src/com/android/bluetooth/hid/HidDeviceService.java
@@ -773,7 +773,7 @@
}
@Override
- protected void start() {
+ public void start() {
if (DBG) {
Log.d(TAG, "start()");
}
@@ -792,7 +792,7 @@
}
@Override
- protected void stop() {
+ public void stop() {
if (DBG) {
Log.d(TAG, "stop()");
}
diff --git a/android/app/src/com/android/bluetooth/hid/HidHostService.java b/android/app/src/com/android/bluetooth/hid/HidHostService.java
index a2f9446..433ab30 100644
--- a/android/app/src/com/android/bluetooth/hid/HidHostService.java
+++ b/android/app/src/com/android/bluetooth/hid/HidHostService.java
@@ -46,6 +46,7 @@
import com.android.bluetooth.btservice.MetricsLogger;
import com.android.bluetooth.btservice.ProfileService;
import com.android.bluetooth.btservice.storage.DatabaseManager;
+import com.android.bluetooth.flags.Flags;
import com.android.modules.utils.SynchronousResultReceiver;
import java.util.ArrayList;
@@ -103,7 +104,7 @@
}
@Override
- protected void start() {
+ public void start() {
mDatabaseManager =
requireNonNull(
AdapterService.getAdapterService().getDatabase(),
@@ -120,14 +121,14 @@
}
@Override
- protected void stop() {
+ public void stop() {
if (DBG) {
Log.d(TAG, "Stopping Bluetooth HidHostService");
}
}
@Override
- protected void cleanup() {
+ public void cleanup() {
if (DBG) Log.d(TAG, "Stopping Bluetooth HidHostService");
if (mNativeAvailable) {
mNativeInterface.cleanup();
@@ -154,7 +155,11 @@
return Utils.getByteAddress(device);
} else {
// if only classic HID is available, force usage of BREDR address
- return mAdapterService.getByteIdentityAddress(device);
+ if (Flags.identityAddressNullIfUnknown()) {
+ return Utils.getByteBrEdrAddress(device);
+ } else {
+ return mAdapterService.getByteIdentityAddress(device);
+ }
}
}
@@ -478,6 +483,43 @@
}
}
+ @Override
+ public void setPreferredTransport(
+ BluetoothDevice device,
+ int transport,
+ AttributionSource source,
+ SynchronousResultReceiver receiver) {
+ try {
+ HidHostService service = getService(source);
+ boolean defaultValue = false;
+ if (service != null) {
+ enforceBluetoothPrivilegedPermission(service);
+ defaultValue = service.setPreferredTransport(device, transport);
+ }
+ receiver.send(defaultValue);
+ } catch (RuntimeException e) {
+ receiver.propagateException(e);
+ }
+ }
+
+ @Override
+ public void getPreferredTransport(
+ BluetoothDevice device,
+ AttributionSource source,
+ SynchronousResultReceiver receiver) {
+ try {
+ HidHostService service = getService(source);
+ int defaultValue = BluetoothDevice.TRANSPORT_AUTO;
+ if (service != null) {
+ enforceBluetoothPrivilegedPermission(service);
+ defaultValue = service.getPreferredTransport(device);
+ }
+ receiver.send(defaultValue);
+ } catch (RuntimeException e) {
+ receiver.propagateException(e);
+ }
+ }
+
/* The following APIs regarding test app for compliance */
@Override
public void getProtocolMode(BluetoothDevice device, AttributionSource source,
@@ -708,6 +750,37 @@
}
/**
+ * @see BluetoothHidHost#setPreferredTransport
+ */
+ boolean setPreferredTransport(BluetoothDevice device, int transport) {
+ if (DBG) {
+ Log.i(TAG, "setPreferredTransport: " + device + " transport: " + transport);
+ }
+
+ if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
+ Log.w(TAG, "Device not bonded" + device);
+ return false;
+ }
+
+ boolean hidSupported = Utils.arrayContains(device.getUuids(), BluetoothUuid.HID);
+ boolean hogpSupported = Utils.arrayContains(device.getUuids(), BluetoothUuid.HOGP);
+ if (transport == BluetoothDevice.TRANSPORT_BREDR && !hidSupported) {
+ Log.w(TAG, "HID not supported: " + device);
+ return false;
+ } else if (transport == BluetoothDevice.TRANSPORT_LE && !hogpSupported) {
+ Log.w(TAG, "HOGP not supported: " + device);
+ return false;
+ }
+
+ /* TODO: b/324094542 - Implement setPreferredTransport API
+ * Save transport preference in the persistent storage
+ * If connection policy allows connection, ensure that the preferred transport is
+ * connected and not the other one.
+ */
+ return false;
+ }
+
+ /**
* Get the connection policy of the profile.
*
* <p> The connection policy can be any of:
@@ -727,6 +800,18 @@
.getProfileConnectionPolicy(device, BluetoothProfile.HID_HOST);
}
+ /**
+ * @see BluetoothHidHost#getPreferredTransport
+ */
+ int getPreferredTransport(BluetoothDevice device) {
+ if (DBG) {
+ Log.d(TAG, "getPreferredTransport: " + device);
+ }
+
+ // TODO: b/324094542 - Implement getPreferredTransport API
+ return BluetoothDevice.TRANSPORT_AUTO;
+ }
+
/* The following APIs regarding test app for compliance */
boolean getProtocolMode(BluetoothDevice device) {
if (DBG) {
@@ -924,6 +1009,9 @@
intent.putExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, prevState);
intent.putExtra(BluetoothProfile.EXTRA_STATE, newState);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
+ /* TODO: b/324094542 - Set correct transport as EXTRA_TRANSPORT
+ * intent.putExtra(BluetoothDevice.EXTRA_TRANSPORT, BluetoothDevice.TRANSPORT_AUTO);
+ */
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_CONNECT,
Utils.getTempAllowlistBroadcastOptions());
diff --git a/android/app/src/com/android/bluetooth/le_audio/LeAudioNativeInterface.java b/android/app/src/com/android/bluetooth/le_audio/LeAudioNativeInterface.java
index 0f3994a..95a6b8b 100644
--- a/android/app/src/com/android/bluetooth/le_audio/LeAudioNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioNativeInterface.java
@@ -272,6 +272,19 @@
sendMessageToService(event);
}
+ @VisibleForTesting
+ void onGroupStreamStatus(int groupId, int groupStreamStatus) {
+ LeAudioStackEvent event =
+ new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_GROUP_STREAM_STATUS_CHANGED);
+ event.valueInt1 = groupId;
+ event.valueInt2 = groupStreamStatus;
+
+ if (DBG) {
+ Log.d(TAG, "onGroupStreamStatus: " + event);
+ }
+ sendMessageToService(event);
+ }
+
/**
* Initializes the native interface.
*
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 ea9e8bf..120ec42 100644
--- a/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java
+++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java
@@ -111,8 +111,6 @@
// Timeout for state machine thread join, to prevent potential ANR.
private static final int SM_THREAD_JOIN_TIMEOUT_MS = 1000;
- // Upper limit of all LeAudio devices: Bonded or Connected
- private static final int MAX_LE_AUDIO_DEVICES = 10;
private static LeAudioService sLeAudioService;
/**
@@ -142,6 +140,7 @@
private HandlerThread mStateMachinesThread;
private volatile BluetoothDevice mActiveAudioOutDevice;
private volatile BluetoothDevice mActiveAudioInDevice;
+ private volatile BluetoothDevice mActiveBroadcastAudioDevice;
private BluetoothDevice mExposedActiveDevice;
private LeAudioCodecConfig mLeAudioCodecConfig;
private final Object mGroupLock = new Object();
@@ -313,7 +312,7 @@
}
@Override
- protected void start() {
+ public void start() {
Log.i(TAG, "start()");
if (sLeAudioService != null) {
throw new IllegalStateException("start() called twice");
@@ -372,8 +371,7 @@
mAudioManager.registerAudioDeviceCallback(mAudioManagerAudioDeviceCallback,
mHandler);
- // clear mUnicastGroupIdDeactivatedForBroadcastTransition to default
- updateFallbackUnicastGroupIdForBroadcast(LE_AUDIO_GROUP_ID_INVALID);
+
// Mark service as started
setLeAudioService(this);
@@ -404,7 +402,7 @@
}
@Override
- protected void stop() {
+ public void stop() {
Log.i(TAG, "stop()");
if (sLeAudioService == null) {
Log.w(TAG, "stop() called before start()");
@@ -500,8 +498,7 @@
}
mAudioManager.unregisterAudioDeviceCallback(mAudioManagerAudioDeviceCallback);
- // clear mUnicastGroupIdDeactivatedForBroadcastTransition to default
- updateFallbackUnicastGroupIdForBroadcast(LE_AUDIO_GROUP_ID_INVALID);
+
mAdapterService = null;
mAudioManager = null;
mMcpService = null;
@@ -512,7 +509,7 @@
}
@Override
- protected void cleanup() {
+ public void cleanup() {
Log.i(TAG, "cleanup()");
}
@@ -574,14 +571,6 @@
boolean isInbandRingtoneEnabled) {
LeAudioDeviceDescriptor descriptor = mDeviceDescriptors.get(device);
if (descriptor == null) {
-
- // Limit the maximum number of devices to avoid DoS attack
- if (mDeviceDescriptors.size() >= MAX_LE_AUDIO_DEVICES) {
- Log.e(TAG, "Maximum number of LeAudio state machines reached: "
- + MAX_LE_AUDIO_DEVICES);
- return null;
- }
-
mDeviceDescriptors.put(device, new LeAudioDeviceDescriptor(isInbandRingtoneEnabled));
descriptor = mDeviceDescriptors.get(device);
Log.d(TAG, "Created descriptor for device: " + device);
@@ -664,6 +653,7 @@
+ " : no state machine");
return false;
}
+
sm.sendMessage(LeAudioStateMachine.DISCONNECT);
}
@@ -1150,6 +1140,16 @@
}
}
+ /** Return true if device is primary - is active or was active before switch to broadcast */
+ public boolean isPrimaryDevice(BluetoothDevice device) {
+ LeAudioDeviceDescriptor descriptor = mDeviceDescriptors.get(device);
+ if (descriptor == null) {
+ return false;
+ }
+
+ return descriptor.mGroupId == mUnicastGroupIdDeactivatedForBroadcastTransition;
+ }
+
private boolean areBroadcastsAllStopped() {
if (mBroadcastDescriptors == null) {
Log.e(TAG, "areBroadcastsAllStopped: Invalid Broadcast Descriptors");
@@ -1601,11 +1601,14 @@
* @param newDevice new supported broadcast audio device
* @param previousDevice previous no longer supported broadcast audio device
*/
+ /* TODO implement unicast overlap with connected unicast device */
private void updateBroadcastActiveDevice(
- BluetoothDevice newDevice, BluetoothDevice previousDevice) {
- mActiveAudioOutDevice = newDevice;
+ BluetoothDevice newDevice,
+ BluetoothDevice previousDevice,
+ boolean suppressNoisyIntent) {
+ mActiveBroadcastAudioDevice = newDevice;
mAudioManager.handleBluetoothActiveDeviceChanged(
- newDevice, previousDevice, getBroadcastProfile(true));
+ newDevice, previousDevice, getBroadcastProfile(suppressNoisyIntent));
}
/*
@@ -2177,6 +2180,22 @@
}
}
+ private void notifyGroupStreamStatusChanged(int groupId, int groupStreamStatus) {
+ if (mLeAudioCallbacks != null) {
+ int n = mLeAudioCallbacks.beginBroadcast();
+ for (int i = 0; i < n; i++) {
+ try {
+ mLeAudioCallbacks
+ .getBroadcastItem(i)
+ .onGroupStreamStatusChanged(groupId, groupStreamStatus);
+ } catch (RemoteException e) {
+ continue;
+ }
+ }
+ mLeAudioCallbacks.finishBroadcast();
+ }
+ }
+
@VisibleForTesting
void handleGroupIdleDuringCall() {
if (mHfpHandoverDevice == null) {
@@ -2365,10 +2384,16 @@
BluetoothDevice unicastDevice =
getLeadDeviceForTheGroup(mUnicastGroupIdDeactivatedForBroadcastTransition);
if (unicastDevice == null) {
- Log.e(TAG, "EVENT_TYPE_BROADCAST_DESTROYED: No valid unicast device for group ID: "
- + mUnicastGroupIdDeactivatedForBroadcastTransition);
+ /* All devices from group were disconnected in meantime */
+ Log.w(
+ TAG,
+ "transitionFromBroadcastToUnicast: No valid unicast device for group ID: "
+ + mUnicastGroupIdDeactivatedForBroadcastTransition);
updateFallbackUnicastGroupIdForBroadcast(LE_AUDIO_GROUP_ID_INVALID);
+ updateBroadcastActiveDevice(null, mActiveBroadcastAudioDevice, false);
return;
+ } else {
+ updateBroadcastActiveDevice(null, mActiveBroadcastAudioDevice, true);
}
if (DBG) {
@@ -2692,19 +2717,21 @@
notifyPlaybackStopped(broadcastId,
BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST);
- // Notify audio manager
- if (mBroadcastDescriptors.values().stream()
- .noneMatch(
- d ->
- d.mState.equals(
- LeAudioStackEvent.BROADCAST_STATE_STREAMING))) {
- updateBroadcastActiveDevice(null, mActiveAudioOutDevice);
- }
/* Restore the Unicast stream from before the Broadcast was started. */
if (mUnicastGroupIdDeactivatedForBroadcastTransition
!= LE_AUDIO_GROUP_ID_INVALID) {
transitionFromBroadcastToUnicast();
+ } else {
+ // Notify audio manager
+ if (mBroadcastDescriptors.values().stream()
+ .noneMatch(
+ d ->
+ d.mState.equals(
+ LeAudioStackEvent
+ .BROADCAST_STATE_STREAMING))) {
+ updateBroadcastActiveDevice(null, mActiveBroadcastAudioDevice, false);
+ }
}
destroyBroadcast(broadcastId);
break;
@@ -2728,7 +2755,7 @@
}
// Notify audio manager
- updateBroadcastActiveDevice(null, mActiveAudioOutDevice);
+ updateBroadcastActiveDevice(null, mActiveBroadcastAudioDevice, true);
/* Restore the Unicast stream from before the Broadcast was started. */
transitionFromBroadcastToUnicast();
@@ -2755,8 +2782,8 @@
d ->
d.mState.equals(
LeAudioStackEvent.BROADCAST_STATE_STREAMING))) {
- if (!Objects.equals(device, mActiveAudioOutDevice)) {
- updateBroadcastActiveDevice(device, mActiveAudioOutDevice);
+ if (!Objects.equals(device, mActiveBroadcastAudioDevice)) {
+ updateBroadcastActiveDevice(device, mActiveBroadcastAudioDevice, true);
}
}
break;
@@ -2764,6 +2791,13 @@
Log.e(TAG, "Invalid state of broadcast: " + descriptor.mState);
break;
}
+
+ // Notify broadcast assistant
+ if (mFeatureFlags.leaudioBroadcastAudioHandoverPolicies()) {
+ if (bassClientService != null) {
+ bassClientService.notifyBroadcastStateChanged(descriptor.mState, broadcastId);
+ }
+ }
} else if (stackEvent.type == LeAudioStackEvent.EVENT_TYPE_BROADCAST_METADATA_CHANGED) {
int broadcastId = stackEvent.valueInt1;
if (stackEvent.broadcastMetadata == null) {
@@ -2791,6 +2825,8 @@
}
} else if (stackEvent.type == LeAudioStackEvent.EVENT_TYPE_UNICAST_MONITOR_MODE_STATUS) {
handleUnicastStreamStatusChange(stackEvent.valueInt1, stackEvent.valueInt2);
+ } else if (stackEvent.type == LeAudioStackEvent.EVENT_TYPE_GROUP_STREAM_STATUS_CHANGED) {
+ notifyGroupStreamStatusChanged(stackEvent.valueInt1, stackEvent.valueInt2);
}
}
@@ -2951,26 +2987,26 @@
* Process a change for disconnection of a device.
*/
public synchronized void deviceDisconnected(BluetoothDevice device, boolean hasFallbackDevice) {
- LeAudioDeviceDescriptor deviceDescriptor = getDeviceDescriptor(device);
- if (deviceDescriptor == null) {
- Log.e(TAG, "deviceDisconnected: No valid descriptor for device: " + device);
- return;
- }
-
- int bondState = mAdapterService.getBondState(device);
- if (bondState == BluetoothDevice.BOND_NONE) {
- if (DBG) {
- Log.d(TAG, device + " is unbond. Remove state machine");
- }
- removeStateMachine(device);
- removeAuthorizationInfoForRelatedProfiles(device);
- }
-
- if (!isScannerNeeded()) {
- stopAudioServersBackgroundScan();
- }
-
synchronized (mGroupLock) {
+ LeAudioDeviceDescriptor deviceDescriptor = getDeviceDescriptor(device);
+ if (deviceDescriptor == null) {
+ Log.e(TAG, "deviceDisconnected: No valid descriptor for device: " + device);
+ return;
+ }
+
+ int bondState = mAdapterService.getBondState(device);
+ if (bondState == BluetoothDevice.BOND_NONE) {
+ if (DBG) {
+ Log.d(TAG, device + " is unbond. Remove state machine");
+ }
+ removeStateMachine(device);
+ removeAuthorizationInfoForRelatedProfiles(device);
+ }
+
+ if (!isScannerNeeded()) {
+ stopAudioServersBackgroundScan();
+ }
+
LeAudioGroupDescriptor descriptor = getGroupDescriptor(deviceDescriptor.mGroupId);
if (descriptor == null) {
Log.e(TAG, "deviceDisconnected: no descriptors for group: "
diff --git a/android/app/src/com/android/bluetooth/le_audio/LeAudioStackEvent.java b/android/app/src/com/android/bluetooth/le_audio/LeAudioStackEvent.java
index 0a4e027..a9d3f39 100644
--- a/android/app/src/com/android/bluetooth/le_audio/LeAudioStackEvent.java
+++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioStackEvent.java
@@ -42,8 +42,9 @@
public static final int EVENT_TYPE_HEALTH_BASED_DEV_RECOMMENDATION = 10;
public static final int EVENT_TYPE_HEALTH_BASED_GROUP_RECOMMENDATION = 11;
public static final int EVENT_TYPE_UNICAST_MONITOR_MODE_STATUS = 12;
+ public static final int EVENT_TYPE_GROUP_STREAM_STATUS_CHANGED = 13;
// -------- DO NOT PUT ANY NEW UNICAST EVENTS BELOW THIS LINE-------------
- public static final int EVENT_TYPE_UNICAST_MAX = 13;
+ public static final int EVENT_TYPE_UNICAST_MAX = 14;
// Broadcast related events
public static final int EVENT_TYPE_BROADCAST_CREATED = EVENT_TYPE_UNICAST_MAX + 1;
@@ -90,6 +91,9 @@
static final int DIRECTION_SINK = 1;
static final int DIRECTION_SOURCE = 2;
+ static final int GROUP_STREAM_STATUS_IDLE = 0;
+ static final int GROUP_STREAM_STATUS_STREAMING = 1;
+
public int type = EVENT_TYPE_NONE;
public BluetoothDevice device;
public int valueInt1 = 0;
@@ -185,6 +189,8 @@
return "EVENT_TYPE_HEALTH_BASED_GROUP_RECOMMENDATION";
case EVENT_TYPE_UNICAST_MONITOR_MODE_STATUS:
return "EVENT_TYPE_UNICAST_MONITOR_MODE_STATUS";
+ case EVENT_TYPE_GROUP_STREAM_STATUS_CHANGED:
+ return "EVENT_TYPE_GROUP_STREAM_STATUS_CHANGED";
default:
return "EVENT_TYPE_UNKNOWN:" + type;
}
@@ -210,6 +216,8 @@
case EVENT_TYPE_AUDIO_GROUP_CURRENT_CODEC_CONFIG_CHANGED:
case EVENT_TYPE_AUDIO_GROUP_SELECTABLE_CODEC_CONFIG_CHANGED:
// same as EVENT_TYPE_GROUP_STATUS_CHANGED
+ case EVENT_TYPE_GROUP_STREAM_STATUS_CHANGED:
+ // same as EVENT_TYPE_GROUP_STATUS_CHANGED
case EVENT_TYPE_GROUP_STATUS_CHANGED:
return "{group_id:" + Integer.toString(value) + "}";
case EVENT_TYPE_AUDIO_CONF_CHANGED:
@@ -300,6 +308,15 @@
default:
return "UNKNOWN";
}
+ case EVENT_TYPE_GROUP_STREAM_STATUS_CHANGED:
+ switch (value) {
+ case GROUP_STREAM_STATUS_IDLE:
+ return "GROUP_STREAM_STATUS_IDLE";
+ case GROUP_STREAM_STATUS_STREAMING:
+ return "GROUP_STREAM_STATUS_STREAMING";
+ default:
+ return "UNKNOWN";
+ }
default:
break;
}
diff --git a/android/app/src/com/android/bluetooth/le_scan/ScanManager.java b/android/app/src/com/android/bluetooth/le_scan/ScanManager.java
index 662e0fa..f39115a 100644
--- a/android/app/src/com/android/bluetooth/le_scan/ScanManager.java
+++ b/android/app/src/com/android/bluetooth/le_scan/ScanManager.java
@@ -46,7 +46,7 @@
import com.android.bluetooth.Utils;
import com.android.bluetooth.btservice.AdapterService;
import com.android.bluetooth.btservice.BluetoothAdapterProxy;
-import com.android.bluetooth.flags.FeatureFlags;
+import com.android.bluetooth.flags.Flags;
import com.android.bluetooth.gatt.FilterParams;
import com.android.bluetooth.gatt.GattObjectsFactory;
import com.android.bluetooth.gatt.GattService;
@@ -123,7 +123,6 @@
@GuardedBy("mCurUsedTrackableAdvertisementsLock")
private int mCurUsedTrackableAdvertisements = 0;
- private final FeatureFlags mFeatureFlags;
private final GattService mService;
private final AdapterService mAdapterService;
private BroadcastReceiver mBatchAlarmReceiver;
@@ -168,8 +167,7 @@
GattService service,
AdapterService adapterService,
BluetoothAdapterProxy bluetoothAdapterProxy,
- Looper looper,
- FeatureFlags featureFlags) {
+ Looper looper) {
mRegularScanClients =
Collections.newSetFromMap(new ConcurrentHashMap<ScanClient, Boolean>());
mBatchClients = Collections.newSetFromMap(new ConcurrentHashMap<ScanClient, Boolean>());
@@ -178,7 +176,6 @@
mService = service;
mAdapterService = adapterService;
mScanNative = new ScanNative();
- mFeatureFlags = featureFlags;
mDm = mService.getSystemService(DisplayManager.class);
mActivityManager = mService.getSystemService(ActivityManager.class);
mLocationManager = mAdapterService.getSystemService(LocationManager.class);
@@ -455,7 +452,7 @@
Message msg = obtainMessage(MSG_SCAN_TIMEOUT);
msg.obj = client;
// Only one timeout message should exist at any time
- if (mFeatureFlags.scanTimeoutReset()) {
+ if (Flags.scanTimeoutReset()) {
removeMessages(MSG_SCAN_TIMEOUT, client);
}
sendMessageDelayed(msg, mAdapterService.getScanTimeoutMillis());
@@ -1922,7 +1919,8 @@
new ActivityManager.OnUidImportanceListener() {
@Override
public void onUidImportance(final int uid, final int importance) {
- if (mService.mScannerMap.getAppScanStatsByUid(uid) != null) {
+ if (mService.mTransitionalScanHelper.getScannerMap().getAppScanStatsByUid(uid)
+ != null) {
Message message = new Message();
message.what = MSG_IMPORTANCE_CHANGE;
message.obj = new UidImportance(uid, importance);
diff --git a/android/app/src/com/android/bluetooth/le_scan/TransitionalScanHelper.java b/android/app/src/com/android/bluetooth/le_scan/TransitionalScanHelper.java
new file mode 100644
index 0000000..913cc40
--- /dev/null
+++ b/android/app/src/com/android/bluetooth/le_scan/TransitionalScanHelper.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.bluetooth.le_scan;
+
+import android.bluetooth.le.IScannerCallback;
+
+import com.android.bluetooth.gatt.ContextMap;
+import com.android.bluetooth.gatt.GattService;
+import com.android.internal.annotations.VisibleForTesting;
+
+/**
+ * A helper class which contains all scan related functions extracted from {@link
+ * com.android.bluetooth.gatt.GattService}. The purpose of this class is to preserve scan
+ * functionality within GattService and provide the same functionality in a new scan dedicated
+ * {@link com.android.bluetooth.btservice.ProfileService} when introduced.
+ *
+ * @hide
+ */
+public class TransitionalScanHelper {
+
+ /** List of our registered scanners. */
+ public static class ScannerMap
+ extends ContextMap<IScannerCallback, GattService.PendingIntentInfo> {}
+
+ private ScannerMap mScannerMap = new ScannerMap();
+
+ public ScannerMap getScannerMap() {
+ return mScannerMap;
+ }
+
+ @VisibleForTesting
+ public void setScannerMap(ScannerMap scannerMap) {
+ mScannerMap = scannerMap;
+ }
+}
diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapContent.java b/android/app/src/com/android/bluetooth/map/BluetoothMapContent.java
index 103fb04..bfdf559 100644
--- a/android/app/src/com/android/bluetooth/map/BluetoothMapContent.java
+++ b/android/app/src/com/android/bluetooth/map/BluetoothMapContent.java
@@ -3940,11 +3940,13 @@
public byte[] getEmailMessage(long id, BluetoothMapAppParams appParams,
BluetoothMapFolderElement currentFolder) throws UnsupportedEncodingException {
// Log print out of application parameters set
- if (D && appParams != null) {
- Log.d(TAG,
- "TYPE_MESSAGE (GET): Attachment = " + appParams.getAttachment() + ", Charset = "
- + appParams.getCharset() + ", FractionRequest = "
- + appParams.getFractionRequest());
+ if (D) {
+ if (appParams != null) {
+ Log.d(TAG, "TYPE_MESSAGE (GET): Attachment = " + appParams.getAttachment()
+ + ", Charset = "
+ + appParams.getCharset() + ", FractionRequest = "
+ + appParams.getFractionRequest());
+ }
}
// Throw exception if requester NATIVE charset for Email
diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapContentObserver.java b/android/app/src/com/android/bluetooth/map/BluetoothMapContentObserver.java
index 27b58e3..d79ab14 100644
--- a/android/app/src/com/android/bluetooth/map/BluetoothMapContentObserver.java
+++ b/android/app/src/com/android/bluetooth/map/BluetoothMapContentObserver.java
@@ -3334,8 +3334,10 @@
uri = Uri.parse(Mms.CONTENT_URI + "/" + handle + "/addr");
uri = mResolver.insert(uri, values);
- if (uri != null && V) {
- Log.v(TAG, " NEW URI " + uri.toString());
+ if (uri != null) {
+ if (V) {
+ Log.v(TAG, " NEW URI " + uri.toString());
+ }
}
values.clear();
@@ -3346,8 +3348,10 @@
values.put(Mms.Addr.ADDRESS, address);
uri = Uri.parse(Mms.CONTENT_URI + "/" + handle + "/addr");
uri = mResolver.insert(uri, values);
- if (uri != null && V) {
- Log.v(TAG, " NEW URI " + uri.toString());
+ if (uri != null) {
+ if (V) {
+ Log.v(TAG, " NEW URI " + uri.toString());
+ }
}
}
return handle;
@@ -3628,7 +3632,11 @@
/* Delete from DB */
Uri msgUri = ContentUris.withAppendedId(Sms.CONTENT_URI, handle);
int nRows = mResolver.delete(msgUri, null, null);
- if (V && nRows > 0) Log.v(TAG, "Deleted message with Uri = " + msgUri);
+ if (nRows > 0) {
+ if (V) {
+ Log.v(TAG, "Deleted message with Uri = " + msgUri);
+ }
+ }
}
}
}
diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapMasInstance.java b/android/app/src/com/android/bluetooth/map/BluetoothMapMasInstance.java
index b07b33f..d7e21f1 100644
--- a/android/app/src/com/android/bluetooth/map/BluetoothMapMasInstance.java
+++ b/android/app/src/com/android/bluetooth/map/BluetoothMapMasInstance.java
@@ -45,13 +45,14 @@
// Next tag value for ContentProfileErrorReportUtils.report(): 4
public class BluetoothMapMasInstance implements IObexConnectionHandler {
- @VisibleForTesting
- final String mTag;
+ private static final String TAG = "BluetoothMapMasInstance";
+ private static final boolean D = BluetoothMapService.DEBUG;
+ private static final boolean V = BluetoothMapService.VERBOSE;
+
@VisibleForTesting
static volatile int sInstanceCounter = 0;
- private static final boolean D = BluetoothMapService.DEBUG;
- private static final boolean V = BluetoothMapService.VERBOSE;
+ private final int mObjectInstanceId;
private static final int SDP_MAP_MSG_TYPE_EMAIL = 0x01;
private static final int SDP_MAP_MSG_TYPE_SMS_GSM = 0x02;
@@ -128,7 +129,7 @@
*/
public BluetoothMapMasInstance(BluetoothMapService mapService, Context context,
BluetoothMapAccountItem account, int masId, boolean enableSmsMms) {
- mTag = "BluetoothMapMasInstance" + sInstanceCounter++;
+ mObjectInstanceId = sInstanceCounter++;
mMapService = mapService;
mServiceHandler = mapService.getHandler();
mContext = context;
@@ -144,22 +145,14 @@
private void removeSdpRecord() {
SdpManagerNativeInterface nativeInterface = SdpManagerNativeInterface.getInstance();
if (mAdapter != null && mSdpHandle >= 0 && nativeInterface.isAvailable()) {
- if (V) {
- Log.d(mTag, "Removing SDP record for MAS instance: " + mMasInstanceId
- + " Object reference: " + this + "SDP handle: " + mSdpHandle);
- }
+ verbose("Removing SDP record for MAS instance: " + mMasInstanceId
+ + " Object reference: " + this + ", SDP handle: " + mSdpHandle);
boolean status = nativeInterface.removeSdpRecord(mSdpHandle);
- Log.d(mTag, "RemoveSDPrecord returns " + status);
+ debug("RemoveSDPrecord returns " + status);
mSdpHandle = -1;
}
}
- /* Needed only for test */
- @VisibleForTesting
- BluetoothMapMasInstance() {
- mTag = "BluetoothMapMasInstance" + sInstanceCounter++;
- }
-
@Override
public String toString() {
return "MasId: " + mMasInstanceId + " Uri:" + mBaseUri + " SMS/MMS:" + mEnableSmsMms;
@@ -279,21 +272,15 @@
* Start Obex Server Sockets and create the SDP record.
*/
public synchronized void startSocketListeners() {
- if (D) {
- Log.d(mTag, "Map Service startSocketListeners");
- }
+ debug("Map Service startSocketListeners");
if (mServerSession != null) {
- if (D) {
- Log.d(mTag, "mServerSession exists - shutting it down...");
- }
+ debug("mServerSession exists - shutting it down...");
mServerSession.close();
mServerSession = null;
}
if (mObserver != null) {
- if (D) {
- Log.d(mTag, "mObserver exists - shutting it down...");
- }
+ debug("mObserver exists - shutting it down...");
mObserver.deinit();
mObserver = null;
}
@@ -309,7 +296,7 @@
if (mServerSockets == null) {
// TODO: Handle - was not handled before
- Log.e(mTag, "Failed to start the listeners");
+ error("Failed to start the listeners");
ContentProfileErrorReportUtils.report(
BluetoothProfile.MAP,
BluetoothProtoEnums.BLUETOOTH_MAP_MAS_INSTANCE,
@@ -321,10 +308,8 @@
mSdpHandle = createMasSdpRecord(mServerSockets.getRfcommChannel(),
mServerSockets.getL2capPsm());
// Here we might have changed crucial data, hence reset DB identifier
- if (V) {
- Log.d(mTag, "Creating new SDP record for MAS instance: " + mMasInstanceId
- + " Object reference: " + this + "SDP handle: " + mSdpHandle);
- }
+ verbose("Creating new SDP record for MAS instance: " + mMasInstanceId
+ + " Object reference: " + this + ", SDP handle: " + mSdpHandle);
updateDbIdentifier();
}
}
@@ -398,9 +383,7 @@
* Returns true at success. */
public boolean startObexServerSession(BluetoothMnsObexClient mnsClient)
throws IOException, RemoteException {
- if (D) {
- Log.d(mTag, "Map Service startObexServerSession masid = " + mMasInstanceId);
- }
+ debug("Map Service startObexServerSession masid = " + mMasInstanceId);
if (mConnSocket != null) {
if (mServerSession != null) {
@@ -419,15 +402,11 @@
// setup transport
BluetoothObexTransport transport = new BluetoothObexTransport(mConnSocket);
mServerSession = new ServerSession(transport, mMapServer, null);
- if (D) {
- Log.d(mTag, " ServerSession started.");
- }
+ debug(" ServerSession started.");
return true;
}
- if (D) {
- Log.d(mTag, " No connection for this instance");
- }
+ debug(" No connection for this instance");
return false;
}
@@ -447,9 +426,7 @@
}
public void shutdown() {
- if (D) {
- Log.d(mTag, "MAP Service shutdown");
- }
+ debug("MAP Service shutdown");
if (mServerSession != null) {
mServerSession.close();
@@ -472,9 +449,7 @@
* Signal to the ServerSockets handler that a new connection may be accepted.
*/
public void restartObexServerSession() {
- if (D) {
- Log.d(mTag, "MAP Service restartObexServerSession()");
- }
+ debug("MAP Service restartObexServerSession()");
startSocketListeners();
}
@@ -498,7 +473,7 @@
BluetoothProtoEnums.BLUETOOTH_MAP_MAS_INSTANCE,
BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION,
1);
- Log.e(mTag, "Close Connection Socket error: ", e);
+ error("Close Connection Socket error: ", e);
} finally {
mConnSocket = null;
}
@@ -506,17 +481,13 @@
}
public void setRemoteFeatureMask(int supportedFeatures) {
- if (V) {
- Log.v(mTag, "setRemoteFeatureMask : Curr: " + mRemoteFeatureMask);
- }
+ verbose("setRemoteFeatureMask : Curr: " + mRemoteFeatureMask);
mRemoteFeatureMask = supportedFeatures & sFeatureMask;
BluetoothMapUtils.savePeerSupportUtcTimeStamp(mRemoteFeatureMask);
if (mObserver != null) {
mObserver.setObserverRemoteFeatureMask(mRemoteFeatureMask);
mMapServer.setRemoteFeatureMask(mRemoteFeatureMask);
- if (V) {
- Log.v(mTag, "setRemoteFeatureMask : set: " + mRemoteFeatureMask);
- }
+ verbose("setRemoteFeatureMask : set: " + mRemoteFeatureMask);
}
}
@@ -554,14 +525,14 @@
public synchronized void onAcceptFailed() {
mServerSockets = null; // Will cause a new to be created when calling start.
if (mShutdown) {
- Log.e(mTag, "Failed to accept incomming connection - " + "shutdown");
+ error("Failed to accept incoming connection - shutdown");
ContentProfileErrorReportUtils.report(
BluetoothProfile.MAP,
BluetoothProtoEnums.BLUETOOTH_MAP_MAS_INSTANCE,
BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__LOG_ERROR,
2);
} else {
- Log.e(mTag, "Failed to accept incomming connection - " + "restarting");
+ error("Failed to accept incoming connection - restarting");
ContentProfileErrorReportUtils.report(
BluetoothProfile.MAP,
BluetoothProtoEnums.BLUETOOTH_MAP_MAS_INSTANCE,
@@ -571,4 +542,24 @@
}
}
+ // Per-Instance logging
+ public void verbose(String message) {
+ if (V) {
+ Log.v(TAG, "[instance=" + mObjectInstanceId + "] " + message);
+ }
+ }
+
+ public void debug(String message) {
+ if (D) {
+ Log.d(TAG, "[instance=" + mObjectInstanceId + "] " + message);
+ }
+ }
+
+ public void error(String message) {
+ Log.e(TAG, "[instance=" + mObjectInstanceId + "] " + message);
+ }
+
+ public void error(String message, Exception e) {
+ Log.e(TAG, "[instance=" + mObjectInstanceId + "] " + message, e);
+ }
}
diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapObexServer.java b/android/app/src/com/android/bluetooth/map/BluetoothMapObexServer.java
index 12ceae7..69651eb 100644
--- a/android/app/src/com/android/bluetooth/map/BluetoothMapObexServer.java
+++ b/android/app/src/com/android/bluetooth/map/BluetoothMapObexServer.java
@@ -608,11 +608,7 @@
BluetoothProtoEnums.BLUETOOTH_MAP_OBEX_SERVER,
BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION,
9);
- if (D) {
- Log.e(TAG, "Exception occured while handling request", e);
- } else {
- Log.e(TAG, "Exception occured while handling request");
- }
+ Log.e(TAG, "Exception occurred while handling request", e);
if (mIsAborted) {
return ResponseCodes.OBEX_HTTP_OK;
} else {
@@ -878,7 +874,7 @@
BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION,
20);
if (D) {
- Log.e(TAG, "Exception occured: ", e);
+ Log.e(TAG, "Exception occurred: ", e);
}
if (mIsAborted) {
if (D) {
@@ -1111,11 +1107,7 @@
BluetoothProtoEnums.BLUETOOTH_MAP_OBEX_SERVER,
BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION,
32);
- if (D) {
- Log.e(TAG, "request headers error", e);
- } else {
- Log.e(TAG, "request headers error");
- }
+ Log.e(TAG, "request headers error", e);
return ResponseCodes.OBEX_HTTP_BAD_REQUEST;
}
@@ -1204,36 +1196,39 @@
}
if (type.equals(TYPE_GET_FOLDER_LISTING)) {
- if (V && appParams != null) {
- Log.d(TAG,
- "TYPE_GET_FOLDER_LISTING: MaxListCount = " + appParams.getMaxListCount()
- + ", ListStartOffset = " + appParams.getStartOffset());
+ if (V) {
+ if (appParams != null) {
+ Log.d(TAG, "TYPE_GET_FOLDER_LISTING: MaxListCount = "
+ + appParams.getMaxListCount() + ", ListStartOffset = "
+ + appParams.getStartOffset());
+ }
}
// Block until all packets have been send.
return sendFolderListingRsp(op, appParams);
} else if (type.equals(TYPE_GET_MESSAGE_LISTING)) {
name = (String) request.getHeader(HeaderSet.NAME);
- if (V && appParams != null) {
- Log.d(TAG, "TYPE_GET_MESSAGE_LISTING: folder name is: " + name
- + ", MaxListCount = " + appParams.getMaxListCount()
- + ", ListStartOffset = " + appParams.getStartOffset());
- Log.d(TAG,
- "SubjectLength = " + appParams.getSubjectLength() + ", ParameterMask = "
- + appParams.getParameterMask());
- Log.d(TAG, "FilterMessageType = " + appParams.getFilterMessageType());
- Log.d(TAG, "FilterPeriodBegin = " + appParams.getFilterPeriodBeginString()
- + ", FilterPeriodEnd = " + appParams.getFilterPeriodEndString()
- + ", FilterReadStatus = " + appParams.getFilterReadStatus());
- Log.d(TAG, "FilterRecipient = " + appParams.getFilterRecipient()
- + ", FilterOriginator = " + appParams.getFilterOriginator());
- Log.d(TAG, "FilterPriority = " + appParams.getFilterPriority());
- long tmpLong = appParams.getFilterMsgHandle();
- Log.d(TAG, "FilterMsgHandle = " + (
- (tmpLong == BluetoothMapAppParams.INVALID_VALUE_PARAMETER) ? ""
- : Long.toHexString(tmpLong)));
- SignedLongLong tmpLongLong = appParams.getFilterConvoId();
- Log.d(TAG, "FilterConvoId = " + ((tmpLongLong == null) ? ""
- : Long.toHexString(tmpLongLong.getLeastSignificantBits())));
+ if (V) {
+ if (appParams != null) {
+ Log.d(TAG, "TYPE_GET_MESSAGE_LISTING: folder name is: " + name
+ + ", MaxListCount = " + appParams.getMaxListCount()
+ + ", ListStartOffset = " + appParams.getStartOffset());
+ Log.d(TAG, "SubjectLength = " + appParams.getSubjectLength()
+ + ", ParameterMask = " + appParams.getParameterMask());
+ Log.d(TAG, "FilterMessageType = " + appParams.getFilterMessageType());
+ Log.d(TAG, "FilterPeriodBegin = " + appParams.getFilterPeriodBeginString()
+ + ", FilterPeriodEnd = " + appParams.getFilterPeriodEndString()
+ + ", FilterReadStatus = " + appParams.getFilterReadStatus());
+ Log.d(TAG, "FilterRecipient = " + appParams.getFilterRecipient()
+ + ", FilterOriginator = " + appParams.getFilterOriginator());
+ Log.d(TAG, "FilterPriority = " + appParams.getFilterPriority());
+ long tmpLong = appParams.getFilterMsgHandle();
+ Log.d(TAG, "FilterMsgHandle = " + (
+ (tmpLong == BluetoothMapAppParams.INVALID_VALUE_PARAMETER) ? ""
+ : Long.toHexString(tmpLong)));
+ SignedLongLong tmpLongLong = appParams.getFilterConvoId();
+ Log.d(TAG, "FilterConvoId = " + ((tmpLongLong == null) ? ""
+ : Long.toHexString(tmpLongLong.getLeastSignificantBits())));
+ }
}
if (!isUserUnlocked()) {
Log.e(TAG, "Storage locked, " + type + " failed");
@@ -1250,15 +1245,18 @@
} else if (type.equals(TYPE_GET_CONVO_LISTING)) {
name = (String) request.getHeader(HeaderSet.NAME);
- if (V && appParams != null) {
- Log.d(TAG, "TYPE_GET_CONVO_LISTING: name is" + name + ", MaxListCount = "
- + appParams.getMaxListCount() + ", ListStartOffset = "
- + appParams.getStartOffset());
- Log.d(TAG,
- "FilterLastActivityBegin = " + appParams.getFilterLastActivityBegin());
- Log.d(TAG, "FilterLastActivityEnd = " + appParams.getFilterLastActivityEnd());
- Log.d(TAG, "FilterReadStatus = " + appParams.getFilterReadStatus());
- Log.d(TAG, "FilterRecipient = " + appParams.getFilterRecipient());
+ if (V) {
+ if (appParams != null) {
+ Log.d(TAG, "TYPE_GET_CONVO_LISTING: name is" + name + ", MaxListCount = "
+ + appParams.getMaxListCount() + ", ListStartOffset = "
+ + appParams.getStartOffset());
+ Log.d(TAG, "FilterLastActivityBegin = "
+ + appParams.getFilterLastActivityBegin());
+ Log.d(TAG, "FilterLastActivityEnd = "
+ + appParams.getFilterLastActivityEnd());
+ Log.d(TAG, "FilterReadStatus = " + appParams.getFilterReadStatus());
+ Log.d(TAG, "FilterRecipient = " + appParams.getFilterRecipient());
+ }
}
if (!isUserUnlocked()) {
Log.e(TAG, "Storage locked, " + type + " failed");
@@ -1273,18 +1271,23 @@
// Block until all packets have been send.
return sendConvoListingRsp(op, appParams);
} else if (type.equals(TYPE_GET_MAS_INSTANCE_INFORMATION)) {
- if (V && appParams != null) {
- Log.d(TAG,
- "TYPE_MESSAGE (GET): MASInstandeId = " + appParams.getMasInstanceId());
+ if (V) {
+ if (appParams != null) {
+ Log.d(TAG, "TYPE_MESSAGE (GET): MASInstandeId = "
+ + appParams.getMasInstanceId());
+ }
}
// Block until all packets have been send.
return sendMASInstanceInformationRsp(op, appParams);
} else if (type.equals(TYPE_MESSAGE)) {
name = (String) request.getHeader(HeaderSet.NAME);
- if (V && appParams != null) {
- Log.d(TAG, "TYPE_MESSAGE (GET): name is" + name + ", Attachment = "
- + appParams.getAttachment() + ", Charset = " + appParams.getCharset()
- + ", FractionRequest = " + appParams.getFractionRequest());
+ if (V) {
+ if (appParams != null) {
+ Log.d(TAG, "TYPE_MESSAGE (GET): name is" + name + ", Attachment = "
+ + appParams.getAttachment() + ", Charset = "
+ + appParams.getCharset() + ", FractionRequest = "
+ + appParams.getFractionRequest());
+ }
}
if (!isUserUnlocked()) {
Log.e(TAG, "Storage locked, " + type + " failed");
@@ -1330,11 +1333,7 @@
BluetoothProtoEnums.BLUETOOTH_MAP_OBEX_SERVER,
BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION,
39);
- if (D) {
- Log.e(TAG, "Exception occured while handling request", e);
- } else {
- Log.e(TAG, "Exception occured while handling request");
- }
+ Log.e(TAG, "Exception occurred while handling request", e);
if (mIsAborted) {
if (D) {
Log.d(TAG, "onGet Operation Aborted");
@@ -2180,8 +2179,10 @@
BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION,
69);
// We were probably aborted or disconnected
- if (D && e.getMessage().equals("Abort Received")) {
- Log.w(TAG, "getMessage() Aborted...", e);
+ if (e.getMessage().equals("Abort Received")) {
+ if (D) {
+ Log.d(TAG, "getMessage() Aborted...", e);
+ }
}
} finally {
if (outStream != null) {
@@ -2274,11 +2275,7 @@
BluetoothProtoEnums.BLUETOOTH_MAP_OBEX_SERVER,
BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION,
73);
- if (D) {
- Log.e(TAG, "Exception occured while handling request", e);
- } else {
- Log.e(TAG, "Exception occured while handling request");
- }
+ Log.e(TAG, "Exception occurred while handling request", e);
if (mIsAborted) {
return ResponseCodes.OBEX_HTTP_OK;
} else {
diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapService.java b/android/app/src/com/android/bluetooth/map/BluetoothMapService.java
index 2e0ebf3..f1499c6 100644
--- a/android/app/src/com/android/bluetooth/map/BluetoothMapService.java
+++ b/android/app/src/com/android/bluetooth/map/BluetoothMapService.java
@@ -717,7 +717,7 @@
}
@Override
- protected void start() {
+ public void start() {
if (DEBUG) {
Log.d(TAG, "start()");
}
@@ -945,7 +945,7 @@
}
@Override
- protected void stop() {
+ public void stop() {
if (DEBUG) {
Log.d(TAG, "stop()");
}
diff --git a/android/app/src/com/android/bluetooth/mapclient/MapClientService.java b/android/app/src/com/android/bluetooth/mapclient/MapClientService.java
index 2a31ea4..cc25909 100644
--- a/android/app/src/com/android/bluetooth/mapclient/MapClientService.java
+++ b/android/app/src/com/android/bluetooth/mapclient/MapClientService.java
@@ -310,7 +310,7 @@
}
@Override
- protected synchronized void start() {
+ public synchronized void start() {
Log.e(TAG, "start()");
mAdapterService = AdapterService.getAdapterService();
@@ -329,7 +329,7 @@
}
@Override
- protected synchronized void stop() {
+ public synchronized void stop() {
if (DBG) {
Log.d(TAG, "stop()");
}
@@ -353,7 +353,7 @@
}
@Override
- protected void cleanup() {
+ public void cleanup() {
if (DBG) {
Log.d(TAG, "in Cleanup");
}
diff --git a/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java b/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java
index 444eb63..f1a4844 100644
--- a/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java
+++ b/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java
@@ -66,6 +66,7 @@
import com.android.bluetooth.btservice.AdapterService;
import com.android.bluetooth.btservice.MetricsLogger;
import com.android.bluetooth.btservice.ProfileService;
+import com.android.bluetooth.flags.Flags;
import com.android.bluetooth.map.BluetoothMapbMessageMime;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.State;
@@ -863,7 +864,15 @@
mMasClient.makeRequest(new RequestGetMessage(event.getHandle(),
MasClient.CharsetType.UTF_8, false));
break;
+ case DELIVERY_FAILURE:
+ // fall through
+ case SENDING_FAILURE:
+ if (!Flags.handleDeliverySendingFailureEvents()) {
+ break;
+ }
+ // fall through
case DELIVERY_SUCCESS:
+ // fall through
case SENDING_SUCCESS:
notifySentMessageStatus(event.getHandle(), event.getType());
break;
@@ -873,6 +882,10 @@
case MESSAGE_DELETED:
mDatabase.deleteMessage(event.getHandle());
break;
+ default:
+ if (DBG) {
+ Log.d(TAG, "processNotification: ignoring event type=" + event.getType());
+ }
}
}
diff --git a/android/app/src/com/android/bluetooth/mapclient/obex/BmessageParser.java b/android/app/src/com/android/bluetooth/mapclient/obex/BmessageParser.java
index 6442e9fe..0c5ef67 100644
--- a/android/app/src/com/android/bluetooth/mapclient/obex/BmessageParser.java
+++ b/android/app/src/com/android/bluetooth/mapclient/obex/BmessageParser.java
@@ -293,8 +293,10 @@
* 2020-06-01: we could now expect MMS to be more than text, e.g., image-only, so charset
* not always UTF-8, downgrading log message from ERROR to DEBUG.
*/
- if (DBG && !"UTF-8".equals(mBmsg.mBbodyCharset)) {
- Log.d(TAG, "The charset was not set to charset UTF-8: " + mBmsg.mBbodyCharset);
+ if (!"UTF-8".equals(mBmsg.mBbodyCharset)) {
+ if (DBG) {
+ Log.d(TAG, "The charset was not set to charset UTF-8: " + mBmsg.mBbodyCharset);
+ }
}
/*
diff --git a/android/app/src/com/android/bluetooth/mcp/McpService.java b/android/app/src/com/android/bluetooth/mcp/McpService.java
index 8661eb3..dd56a34 100644
--- a/android/app/src/com/android/bluetooth/mcp/McpService.java
+++ b/android/app/src/com/android/bluetooth/mcp/McpService.java
@@ -101,7 +101,7 @@
}
@Override
- protected void start() {
+ public void start() {
if (DBG) {
Log.d(TAG, "start()");
}
@@ -133,7 +133,7 @@
}
@Override
- protected void stop() {
+ public void stop() {
if (DBG) {
Log.d(TAG, "stop()");
}
@@ -161,7 +161,7 @@
}
@Override
- protected void cleanup() {
+ public void cleanup() {
if (DBG) {
Log.d(TAG, "cleanup()");
}
diff --git a/android/app/src/com/android/bluetooth/notification/NotificationHelperService.java b/android/app/src/com/android/bluetooth/notification/NotificationHelperService.java
index b411565..07bb45e 100644
--- a/android/app/src/com/android/bluetooth/notification/NotificationHelperService.java
+++ b/android/app/src/com/android/bluetooth/notification/NotificationHelperService.java
@@ -23,7 +23,9 @@
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
+import android.bluetooth.BluetoothManager;
import android.content.Intent;
+import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.IBinder;
import android.provider.Settings;
@@ -45,10 +47,22 @@
private static final String APM_BT_NOTIFICATION = "apm_bt_notification";
// Keeps track of whether user enabling bt notification was shown
private static final String APM_BT_ENABLED_NOTIFICATION = "apm_bt_enabled_notification";
+ // Keeps track of whether auto on enabling bt notification was shown
+ private static final String AUTO_ON_BT_ENABLED_NOTIFICATION = "auto_on_bt_enabled_notification";
private static final String NOTIFICATION_TAG = "com.android.bluetooth";
private static final String NOTIFICATION_CHANNEL = "notification_toggle_channel";
- private static final String NOTIFICATION_GROUP = "notification_toggle_group";
+ private static final int NOTIFICATION_GROUP = R.string.bluetooth_notification_group;
+
+ private static final String NOTIFICATION_ACTION =
+ "android.bluetooth.notification.action.SEND_TOGGLE_NOTIFICATION";
+ private static final String NOTIFICATION_EXTRA =
+ "android.bluetooth.notification.extra.NOTIFICATION_REASON";
+
+ private static final String AUTO_ON_USER_ACTION =
+ "android.bluetooth.notification.action.AUTO_ON_USER_ACTION";
+ private static final String AUTO_ON_USER_EXTRA =
+ "android.bluetooth.notification.extra.AUTO_ON_DISABLE";
private static final Map<String, Pair<Integer /* titleId */, Integer /* messageId */>>
NOTIFICATION_MAP =
@@ -64,7 +78,11 @@
APM_BT_ENABLED_NOTIFICATION,
Pair.create(
R.string.bluetooth_enabled_apm_title,
- R.string.bluetooth_enabled_apm_message));
+ R.string.bluetooth_enabled_apm_message),
+ AUTO_ON_BT_ENABLED_NOTIFICATION,
+ Pair.create(
+ R.string.bluetooth_enabled_auto_on_title,
+ R.string.bluetooth_enabled_auto_on_message));
@Override
public IBinder onBind(Intent intent) {
@@ -73,8 +91,14 @@
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
- sendToggleNotification(
- intent.getStringExtra("android.bluetooth.notification.extra.NOTIFICATION_REASON"));
+ switch (intent.getAction()) {
+ case NOTIFICATION_ACTION -> {
+ sendToggleNotification(intent.getStringExtra(NOTIFICATION_EXTRA));
+ }
+ case AUTO_ON_USER_ACTION -> {
+ autoOnUserAction(intent.getBooleanExtra(AUTO_ON_USER_EXTRA, false));
+ }
+ }
return Service.START_NOT_STICKY;
}
@@ -96,46 +120,74 @@
NotificationManager notificationManager =
requireNonNull(getSystemService(NotificationManager.class));
+ String tag = NOTIFICATION_TAG + "/" + notificationReason;
for (StatusBarNotification notification : notificationManager.getActiveNotifications()) {
- if (NOTIFICATION_TAG.equals(notification.getTag())) {
- notificationManager.cancel(NOTIFICATION_TAG, notification.getId());
+ if (tag.equals(notification.getTag())) {
+ notificationManager.cancel(tag, notification.getId());
}
}
notificationManager.createNotificationChannel(
new NotificationChannel(
NOTIFICATION_CHANNEL,
- NOTIFICATION_GROUP,
+ getString(NOTIFICATION_GROUP),
NotificationManager.IMPORTANCE_HIGH));
String title = getString(notificationContent.first);
String message = getString(notificationContent.second);
- String helpLinkUrl = getString(R.string.config_apmLearnMoreLink);
- notificationManager.notify(
- NOTIFICATION_TAG,
- SystemMessage.ID.NOTE_BT_APM_NOTIFICATION_VALUE,
+ Notification.Builder builder =
new Notification.Builder(this, NOTIFICATION_CHANNEL)
.setAutoCancel(true)
.setLocalOnly(true)
.setContentTitle(title)
.setContentText(message)
- .setContentIntent(
- PendingIntent.getActivity(
- this,
- PendingIntent.FLAG_UPDATE_CURRENT,
- new Intent(Intent.ACTION_VIEW)
- .setData(Uri.parse(helpLinkUrl))
- .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
- PendingIntent.FLAG_IMMUTABLE))
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setStyle(new Notification.BigTextStyle().bigText(message))
- .setSmallIcon(android.R.drawable.stat_sys_data_bluetooth)
- .build());
+ .setSmallIcon(android.R.drawable.stat_sys_data_bluetooth);
+
+ if (!notificationReason.equals(AUTO_ON_BT_ENABLED_NOTIFICATION)) {
+ // Do not display airplane link when the notification is due to auto_on feature
+ String helpLinkUrl = getString(R.string.config_apmLearnMoreLink);
+ builder.setContentIntent(
+ PendingIntent.getActivity(
+ this,
+ PendingIntent.FLAG_UPDATE_CURRENT,
+ new Intent(Intent.ACTION_VIEW)
+ .setData(Uri.parse(helpLinkUrl))
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
+ PendingIntent.FLAG_IMMUTABLE));
+ } else {
+ Intent baseIntent =
+ new Intent()
+ .setAction(AUTO_ON_USER_ACTION)
+ .setClass(this, NotificationHelperService.class);
+ PendingIntent disablePendingIntent =
+ PendingIntent.getService(
+ this,
+ 0,
+ new Intent(baseIntent).putExtra(AUTO_ON_USER_EXTRA, true),
+ PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_ONE_SHOT);
+ builder.addAction(
+ new Notification.Action.Builder(
+ Icon.createWithResource(this, R.drawable.ic_bluetooth_settings),
+ getString(R.string.bluetooth_disable_auto_on),
+ disablePendingIntent)
+ .build());
+ }
+
+ notificationManager.notify(
+ tag, SystemMessage.ID.NOTE_BT_APM_NOTIFICATION_VALUE, builder.build());
}
/** Return whether the notification has been shown */
private boolean isFirstTimeNotification(String name) {
return Settings.Secure.getInt(getContentResolver(), name, 0) == 0;
}
+
+ private void autoOnUserAction(boolean disableAutoOn) {
+ if (disableAutoOn) {
+ getSystemService(BluetoothManager.class).getAdapter().setAutoOnEnabled(false);
+ }
+ }
}
diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java
index eaaa258..895437f 100644
--- a/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java
+++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java
@@ -1,17 +1,33 @@
/*
- * Copyright (C) 2024 The Android Open Source Project
+ * Copyright (c) 2008-2009, Motorola, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * All rights reserved.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
*
- * 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.
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
*/
package com.android.bluetooth.opp;
diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiver.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiver.java
index 6db2dad..889ce80 100644
--- a/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiver.java
+++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiver.java
@@ -1,17 +1,33 @@
/*
- * Copyright (C) 2024 The Android Open Source Project
+ * Copyright (c) 2008-2009, Motorola, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * All rights reserved.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
*
- * 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.
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
*/
package com.android.bluetooth.opp;
diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppService.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppService.java
index 3b35ac7..268fb8d 100644
--- a/android/app/src/com/android/bluetooth/opp/BluetoothOppService.java
+++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppService.java
@@ -601,7 +601,7 @@
}
@Override
- protected void cleanup() {
+ public void cleanup() {
if (V) {
Log.v(TAG, "onDestroy");
}
diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppTransferHistory.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppTransferHistory.java
index 2918138..8ff0043 100644
--- a/android/app/src/com/android/bluetooth/opp/BluetoothOppTransferHistory.java
+++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppTransferHistory.java
@@ -1,17 +1,33 @@
/*
- * Copyright (C) 2024 The Android Open Source Project
+ * Copyright (c) 2008-2009, Motorola, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * All rights reserved.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
*
- * 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.
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
*/
package com.android.bluetooth.opp;
diff --git a/android/app/src/com/android/bluetooth/opp/Constants.java b/android/app/src/com/android/bluetooth/opp/Constants.java
index b214655..606d34c 100644
--- a/android/app/src/com/android/bluetooth/opp/Constants.java
+++ b/android/app/src/com/android/bluetooth/opp/Constants.java
@@ -1,17 +1,33 @@
/*
- * Copyright (C) 2024 The Android Open Source Project
+ * Copyright (c) 2008-2009, Motorola, Inc.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * All rights reserved.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
*
- * 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.
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * - Neither the name of the Motorola, Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
*/
package com.android.bluetooth.opp;
diff --git a/android/app/src/com/android/bluetooth/pan/PanService.java b/android/app/src/com/android/bluetooth/pan/PanService.java
index f10338a..e7fa79e 100644
--- a/android/app/src/com/android/bluetooth/pan/PanService.java
+++ b/android/app/src/com/android/bluetooth/pan/PanService.java
@@ -47,6 +47,7 @@
import com.android.bluetooth.btservice.MetricsLogger;
import com.android.bluetooth.btservice.ProfileService;
import com.android.bluetooth.btservice.storage.DatabaseManager;
+import com.android.bluetooth.flags.Flags;
import com.android.internal.annotations.VisibleForTesting;
import com.android.modules.utils.HandlerExecutor;
import com.android.modules.utils.SynchronousResultReceiver;
@@ -148,7 +149,7 @@
}
@Override
- protected void start() {
+ public void start() {
mAdapterService = Objects.requireNonNull(AdapterService.getAdapterService(),
"AdapterService cannot be null when PanService starts");
mDatabaseManager = Objects.requireNonNull(AdapterService.getAdapterService().getDatabase(),
@@ -178,7 +179,7 @@
}
@Override
- protected void stop() {
+ public void stop() {
if (!mStarted) {
Log.w(TAG, "stop() called before start()");
return;
@@ -192,7 +193,7 @@
}
@Override
- protected void cleanup() {
+ public void cleanup() {
// TODO(b/72948646): this should be moved to stop()
setPanService(null);
@@ -224,7 +225,10 @@
case MESSAGE_CONNECT:
BluetoothDevice connectDevice = (BluetoothDevice) msg.obj;
if (!mNativeInterface.connect(
- mAdapterService.getByteIdentityAddress(connectDevice))) {
+ Flags.identityAddressNullIfUnknown()
+ ? Utils.getByteBrEdrAddress(connectDevice)
+ : mAdapterService.getByteIdentityAddress(
+ connectDevice))) {
handlePanDeviceStateChange(
connectDevice,
null,
@@ -242,7 +246,10 @@
case MESSAGE_DISCONNECT:
BluetoothDevice disconnectDevice = (BluetoothDevice) msg.obj;
if (!mNativeInterface.disconnect(
- mAdapterService.getByteIdentityAddress(disconnectDevice))) {
+ Flags.identityAddressNullIfUnknown()
+ ? Utils.getByteBrEdrAddress(disconnectDevice)
+ : mAdapterService.getByteIdentityAddress(
+ disconnectDevice))) {
handlePanDeviceStateChange(
disconnectDevice,
mPanIfName,
diff --git a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java
index 69ece29..f87e345 100644
--- a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java
+++ b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java
@@ -725,7 +725,7 @@
}
@Override
- protected void start() {
+ public void start() {
if (VERBOSE) {
Log.v(TAG, "start()");
}
@@ -791,7 +791,7 @@
}
@Override
- protected void stop() {
+ public void stop() {
if (VERBOSE) {
Log.v(TAG, "stop()");
}
diff --git a/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java b/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java
index 2239194..abd92ee 100644
--- a/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java
+++ b/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java
@@ -134,7 +134,7 @@
}
@Override
- protected void start() {
+ public void start() {
if (VDBG) {
Log.v(TAG, "onStart");
}
@@ -163,7 +163,7 @@
}
@Override
- protected void stop() {
+ public void stop() {
setPbapClientService(null);
cleanUpSdpRecord();
try {
diff --git a/android/app/src/com/android/bluetooth/sap/SapMessage.java b/android/app/src/com/android/bluetooth/sap/SapMessage.java
index c88b61b..b1f947c 100644
--- a/android/app/src/com/android/bluetooth/sap/SapMessage.java
+++ b/android/app/src/com/android/bluetooth/sap/SapMessage.java
@@ -1187,67 +1187,63 @@
public static String getMsgTypeName(int msgType) {
- if (DEBUG || VERBOSE) {
- switch (msgType) {
- case ID_CONNECT_REQ:
- return "ID_CONNECT_REQ";
- case ID_CONNECT_RESP:
- return "ID_CONNECT_RESP";
- case ID_DISCONNECT_REQ:
- return "ID_DISCONNECT_REQ";
- case ID_DISCONNECT_RESP:
- return "ID_DISCONNECT_RESP";
- case ID_DISCONNECT_IND:
- return "ID_DISCONNECT_IND";
- case ID_TRANSFER_APDU_REQ:
- return "ID_TRANSFER_APDU_REQ";
- case ID_TRANSFER_APDU_RESP:
- return "ID_TRANSFER_APDU_RESP";
- case ID_TRANSFER_ATR_REQ:
- return "ID_TRANSFER_ATR_REQ";
- case ID_TRANSFER_ATR_RESP:
- return "ID_TRANSFER_ATR_RESP";
- case ID_POWER_SIM_OFF_REQ:
- return "ID_POWER_SIM_OFF_REQ";
- case ID_POWER_SIM_OFF_RESP:
- return "ID_POWER_SIM_OFF_RESP";
- case ID_POWER_SIM_ON_REQ:
- return "ID_POWER_SIM_ON_REQ";
- case ID_POWER_SIM_ON_RESP:
- return "ID_POWER_SIM_ON_RESP";
- case ID_RESET_SIM_REQ:
- return "ID_RESET_SIM_REQ";
- case ID_RESET_SIM_RESP:
- return "ID_RESET_SIM_RESP";
- case ID_TRANSFER_CARD_READER_STATUS_REQ:
- return "ID_TRANSFER_CARD_READER_STATUS_REQ";
- case ID_TRANSFER_CARD_READER_STATUS_RESP:
- return "ID_TRANSFER_CARD_READER_STATUS_RESP";
- case ID_STATUS_IND:
- return "ID_STATUS_IND";
- case ID_ERROR_RESP:
- return "ID_ERROR_RESP";
- case ID_SET_TRANSPORT_PROTOCOL_REQ:
- return "ID_SET_TRANSPORT_PROTOCOL_REQ";
- case ID_SET_TRANSPORT_PROTOCOL_RESP:
- return "ID_SET_TRANSPORT_PROTOCOL_RESP";
- case ID_RIL_UNSOL_CONNECTED:
- return "ID_RIL_UNSOL_CONNECTED";
- case ID_RIL_UNSOL_DISCONNECT_IND:
- return "ID_RIL_UNSOL_DISCONNECT_IND";
- case ID_RIL_UNKNOWN:
- return "ID_RIL_UNKNOWN";
- case ID_RIL_GET_SIM_STATUS_REQ:
- return "ID_RIL_GET_SIM_STATUS_REQ";
- case ID_RIL_SIM_ACCESS_TEST_REQ:
- return "ID_RIL_SIM_ACCESS_TEST_REQ";
- case ID_RIL_SIM_ACCESS_TEST_RESP:
- return "ID_RIL_SIM_ACCESS_TEST_RESP";
- default:
- return "Unknown Message Type (" + msgType + ")";
- }
- } else {
- return null;
+ switch (msgType) {
+ case ID_CONNECT_REQ:
+ return "ID_CONNECT_REQ";
+ case ID_CONNECT_RESP:
+ return "ID_CONNECT_RESP";
+ case ID_DISCONNECT_REQ:
+ return "ID_DISCONNECT_REQ";
+ case ID_DISCONNECT_RESP:
+ return "ID_DISCONNECT_RESP";
+ case ID_DISCONNECT_IND:
+ return "ID_DISCONNECT_IND";
+ case ID_TRANSFER_APDU_REQ:
+ return "ID_TRANSFER_APDU_REQ";
+ case ID_TRANSFER_APDU_RESP:
+ return "ID_TRANSFER_APDU_RESP";
+ case ID_TRANSFER_ATR_REQ:
+ return "ID_TRANSFER_ATR_REQ";
+ case ID_TRANSFER_ATR_RESP:
+ return "ID_TRANSFER_ATR_RESP";
+ case ID_POWER_SIM_OFF_REQ:
+ return "ID_POWER_SIM_OFF_REQ";
+ case ID_POWER_SIM_OFF_RESP:
+ return "ID_POWER_SIM_OFF_RESP";
+ case ID_POWER_SIM_ON_REQ:
+ return "ID_POWER_SIM_ON_REQ";
+ case ID_POWER_SIM_ON_RESP:
+ return "ID_POWER_SIM_ON_RESP";
+ case ID_RESET_SIM_REQ:
+ return "ID_RESET_SIM_REQ";
+ case ID_RESET_SIM_RESP:
+ return "ID_RESET_SIM_RESP";
+ case ID_TRANSFER_CARD_READER_STATUS_REQ:
+ return "ID_TRANSFER_CARD_READER_STATUS_REQ";
+ case ID_TRANSFER_CARD_READER_STATUS_RESP:
+ return "ID_TRANSFER_CARD_READER_STATUS_RESP";
+ case ID_STATUS_IND:
+ return "ID_STATUS_IND";
+ case ID_ERROR_RESP:
+ return "ID_ERROR_RESP";
+ case ID_SET_TRANSPORT_PROTOCOL_REQ:
+ return "ID_SET_TRANSPORT_PROTOCOL_REQ";
+ case ID_SET_TRANSPORT_PROTOCOL_RESP:
+ return "ID_SET_TRANSPORT_PROTOCOL_RESP";
+ case ID_RIL_UNSOL_CONNECTED:
+ return "ID_RIL_UNSOL_CONNECTED";
+ case ID_RIL_UNSOL_DISCONNECT_IND:
+ return "ID_RIL_UNSOL_DISCONNECT_IND";
+ case ID_RIL_UNKNOWN:
+ return "ID_RIL_UNKNOWN";
+ case ID_RIL_GET_SIM_STATUS_REQ:
+ return "ID_RIL_GET_SIM_STATUS_REQ";
+ case ID_RIL_SIM_ACCESS_TEST_REQ:
+ return "ID_RIL_SIM_ACCESS_TEST_REQ";
+ case ID_RIL_SIM_ACCESS_TEST_RESP:
+ return "ID_RIL_SIM_ACCESS_TEST_RESP";
+ default:
+ return "Unknown Message Type (" + msgType + ")";
}
}
}
diff --git a/android/app/src/com/android/bluetooth/sap/SapService.java b/android/app/src/com/android/bluetooth/sap/SapService.java
index 4a9c420..68dfc15 100644
--- a/android/app/src/com/android/bluetooth/sap/SapService.java
+++ b/android/app/src/com/android/bluetooth/sap/SapService.java
@@ -680,7 +680,7 @@
}
@Override
- protected void start() {
+ public void start() {
Log.v(TAG, "start()");
IntentFilter filter = new IntentFilter();
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
@@ -702,7 +702,7 @@
}
@Override
- protected void stop() {
+ public void stop() {
Log.v(TAG, "stop()");
if (!mIsRegistered) {
Log.i(TAG, "Avoid unregister when receiver it is not registered");
diff --git a/android/app/src/com/android/bluetooth/sdp/SdpManager.java b/android/app/src/com/android/bluetooth/sdp/SdpManager.java
index 9ce9037..93cb228 100644
--- a/android/app/src/com/android/bluetooth/sdp/SdpManager.java
+++ b/android/app/src/com/android/bluetooth/sdp/SdpManager.java
@@ -34,6 +34,7 @@
import com.android.bluetooth.Utils;
import com.android.bluetooth.btservice.AbstractionLayer;
import com.android.bluetooth.btservice.AdapterService;
+import com.android.bluetooth.flags.Flags;
import java.util.ArrayList;
import java.util.Arrays;
@@ -436,7 +437,9 @@
inst.startSearch(); // Trigger timeout message
mNativeInterface.sdpSearch(
- sAdapterService.getByteIdentityAddress(inst.getDevice()),
+ Flags.identityAddressNullIfUnknown()
+ ? Utils.getByteBrEdrAddress(inst.getDevice())
+ : sAdapterService.getByteIdentityAddress(inst.getDevice()),
Utils.uuidToByteArray(inst.getUuid()));
} else { // Else queue is empty.
if (D) {
diff --git a/android/app/src/com/android/bluetooth/tbs/TbsService.java b/android/app/src/com/android/bluetooth/tbs/TbsService.java
index 43f5591..6769588 100644
--- a/android/app/src/com/android/bluetooth/tbs/TbsService.java
+++ b/android/app/src/com/android/bluetooth/tbs/TbsService.java
@@ -65,7 +65,7 @@
}
@Override
- protected void start() {
+ public void start() {
if (DBG) {
Log.d(TAG, "start()");
@@ -81,7 +81,7 @@
}
@Override
- protected void stop() {
+ public void stop() {
if (DBG) {
Log.d(TAG, "stop()");
}
@@ -99,7 +99,7 @@
}
@Override
- protected void cleanup() {
+ public void cleanup() {
if (DBG) {
Log.d(TAG, "cleanup()");
}
diff --git a/android/app/src/com/android/bluetooth/vc/VolumeControlService.java b/android/app/src/com/android/bluetooth/vc/VolumeControlService.java
index 81699c6..388bb93 100644
--- a/android/app/src/com/android/bluetooth/vc/VolumeControlService.java
+++ b/android/app/src/com/android/bluetooth/vc/VolumeControlService.java
@@ -124,24 +124,6 @@
return true;
}
- int getFirstOffsetValue() {
- if (size() == 0) {
- return 0;
- }
- Descriptor[] descriptors = mVolumeOffsets.values().toArray(new Descriptor[size()]);
-
- if (DBG) {
- Log.d(
- TAG,
- "Number of offsets: "
- + size()
- + ", first offset value: "
- + descriptors[0].mValue);
- }
-
- return descriptors[0].mValue;
- }
-
int getValue(int id) {
Descriptor d = mVolumeOffsets.get(id);
if (d == null) {
@@ -239,7 +221,7 @@
}
@Override
- protected void start() {
+ public void start() {
if (DBG) {
Log.d(TAG, "start()");
}
@@ -280,7 +262,7 @@
}
@Override
- protected void stop() {
+ public void stop() {
if (DBG) {
Log.d(TAG, "stop()");
}
@@ -338,7 +320,7 @@
}
@Override
- protected void cleanup() {
+ public void cleanup() {
if (DBG) {
Log.d(TAG, "cleanup()");
}
@@ -576,21 +558,46 @@
return true;
}
- void setVolumeOffset(BluetoothDevice device, int volumeOffset) {
+ int getNumberOfVolumeOffsetInstances(BluetoothDevice device) {
+ VolumeControlOffsetDescriptor offsets = mAudioOffsets.get(device);
+ if (offsets == null) {
+ Log.i(TAG, " There is no offset service for device: " + device);
+ return 0;
+ }
+
+ int numberOfInstances = offsets.size();
+
+ Log.i(TAG, "Number of VOCS: " + numberOfInstances + ", for device: " + device);
+ return numberOfInstances;
+ }
+
+ void setVolumeOffset(BluetoothDevice device, int instanceId, int volumeOffset) {
VolumeControlOffsetDescriptor offsets = mAudioOffsets.get(device);
if (offsets == null) {
Log.e(TAG, " There is no offset service for device: " + device);
return;
}
- /* Use first offset always */
- int value = offsets.getValue(1);
+ int numberOfInstances = offsets.size();
+ if (instanceId > numberOfInstances) {
+ Log.e(
+ TAG,
+ "Selected VOCS instance ID: "
+ + instanceId
+ + ", exceed available IDs: "
+ + numberOfInstances
+ + ", for device: "
+ + device);
+ return;
+ }
+
+ int value = offsets.getValue(instanceId);
if (value == volumeOffset) {
/* Nothing to do - offset already applied */
return;
}
- mVolumeControlNativeInterface.setExtAudioOutVolumeOffset(device, 1, volumeOffset);
+ mVolumeControlNativeInterface.setExtAudioOutVolumeOffset(device, instanceId, volumeOffset);
}
void setDeviceVolume(BluetoothDevice device, int volume, boolean isGroupOp) {
@@ -708,7 +715,8 @@
Boolean groupMute = getGroupMute(groupId);
if (groupVolume != IBluetoothVolumeControl.VOLUME_CONTROL_UNKNOWN_VOLUME) {
- updateGroupCacheAndAudioSystem(groupId, groupVolume, groupMute);
+ /* Don't need to show volume when activating known device. */
+ updateGroupCacheAndAudioSystem(groupId, groupVolume, groupMute, /* showInUI*/ false);
}
}
@@ -775,23 +783,51 @@
for (Map.Entry<BluetoothDevice, VolumeControlOffsetDescriptor> entry :
mAudioOffsets.entrySet()) {
VolumeControlOffsetDescriptor descriptor = entry.getValue();
- if (descriptor.size() == 0) {
- continue;
- }
- BluetoothDevice device = entry.getKey();
- int offset = descriptor.getFirstOffsetValue();
+ for (int id = 1; id <= descriptor.size(); id++) {
+ BluetoothDevice device = entry.getKey();
+ int offset = descriptor.getValue(id);
+ int location = descriptor.getLocation(id);
+ String description = descriptor.getDescription(id);
- if (DBG) {
- Log.d(
- TAG,
- "notifyNewCallbackOfKnownVolumeInfo offset: " + device + ", " + offset);
- }
+ if (DBG) {
+ Log.d(
+ TAG,
+ "notifyNewCallbackOfKnownVolumeInfo, device: "
+ + device
+ + ", id: "
+ + id
+ + ", offset: "
+ + offset
+ + ", location: "
+ + location
+ + ", description: "
+ + description);
+ }
- try {
- tempCallbackList.getBroadcastItem(i).onVolumeOffsetChanged(device, offset);
- } catch (RemoteException e) {
- continue;
+ try {
+ tempCallbackList
+ .getBroadcastItem(i)
+ .onVolumeOffsetChanged(device, id, offset);
+ } catch (RemoteException e) {
+ // Not every callback had to be defined; just continue
+ }
+ if (mFeatureFlags.leaudioMultipleVocsInstancesApi()) {
+ try {
+ tempCallbackList
+ .getBroadcastItem(i)
+ .onVolumeOffsetAudioLocationChanged(device, id, location);
+ } catch (RemoteException e) {
+ // Not every callback had to be defined; just continue
+ }
+ try {
+ tempCallbackList
+ .getBroadcastItem(i)
+ .onVolumeOffsetAudioDescriptionChanged(device, id, description);
+ } catch (RemoteException e) {
+ // Not every callback had to be defined; just continue
+ }
+ }
}
}
}
@@ -867,7 +903,7 @@
}
}
- void updateGroupCacheAndAudioSystem(int groupId, int volume, boolean mute) {
+ void updateGroupCacheAndAudioSystem(int groupId, int volume, boolean mute, boolean showInUI) {
Log.d(
TAG,
" updateGroupCacheAndAudioSystem: groupId: "
@@ -875,7 +911,9 @@
+ ", vol: "
+ volume
+ ", mute: "
- + mute);
+ + mute
+ + ", showInUI"
+ + showInUI);
mGroupVolumeCache.put(groupId, volume);
mGroupMuteCache.put(groupId, mute);
@@ -898,7 +936,11 @@
}
int streamType = getBluetoothContextualVolumeStream();
- int flags = AudioManager.FLAG_SHOW_UI | AudioManager.FLAG_BLUETOOTH_ABS_VOLUME;
+ int flags = AudioManager.FLAG_BLUETOOTH_ABS_VOLUME;
+ if (showInUI) {
+ flags |= AudioManager.FLAG_SHOW_UI;
+ }
+
mAudioManager.setStreamVolume(streamType, getAudioDeviceVolume(streamType, volume), flags);
if (mAudioManager.isStreamMute(streamType) != mute) {
@@ -955,8 +997,9 @@
/* We are here, because system was just started and LeAudio device just connected.
* In such case, we take Volume stored on remote device and apply it to our cache and
* audio system.
+ * Note, to match BR/EDR behavior, don't show volume change in UI here
*/
- updateGroupCacheAndAudioSystem(groupId, volume, mute);
+ updateGroupCacheAndAudioSystem(groupId, volume, mute, false);
return;
}
@@ -1001,7 +1044,7 @@
}
} else {
/* Received group notification for autonomous change. Update cache and audio system. */
- updateGroupCacheAndAudioSystem(groupId, volume, mute);
+ updateGroupCacheAndAudioSystem(groupId, volume, mute, true);
}
}
@@ -1031,10 +1074,23 @@
// Copied from AudioService.getBluetoothContextualVolumeStream() and modified it.
int getBluetoothContextualVolumeStream() {
int mode = mAudioManager.getMode();
+
+ if (DBG) {
+ Log.d(TAG, "Volume mode: " + mode + "0: normal, 1: ring, 2,3: call");
+ }
+
switch (mode) {
case AudioManager.MODE_IN_COMMUNICATION:
case AudioManager.MODE_IN_CALL:
return AudioManager.STREAM_VOICE_CALL;
+ case AudioManager.MODE_RINGTONE:
+ if (mFeatureFlags.leaudioVolumeChangeOnRingtoneFix()) {
+ if (DBG) {
+ Log.d(TAG, " Update during ringtone applied to voice call");
+ }
+ return AudioManager.STREAM_VOICE_CALL;
+ }
+ // fall through
case AudioManager.MODE_NORMAL:
default:
// other conditions will influence the stream type choice, read on...
@@ -1063,6 +1119,7 @@
for (int i = 1; i <= numberOfExternalOutputs; i++) {
offsets.add(i);
mVolumeControlNativeInterface.getExtAudioOutVolumeOffset(device, i);
+ mVolumeControlNativeInterface.getExtAudioOutLocation(device, i);
mVolumeControlNativeInterface.getExtAudioOutDescription(device, i);
}
}
@@ -1085,7 +1142,7 @@
int n = mCallbacks.beginBroadcast();
for (int i = 0; i < n; i++) {
try {
- mCallbacks.getBroadcastItem(i).onVolumeOffsetChanged(device, value);
+ mCallbacks.getBroadcastItem(i).onVolumeOffsetChanged(device, id, value);
} catch (RemoteException e) {
continue;
}
@@ -1105,10 +1162,28 @@
return;
}
offsets.setLocation(id, location);
+
+ if (mFeatureFlags.leaudioMultipleVocsInstancesApi()) {
+ if (mCallbacks == null) {
+ return;
+ }
+
+ int n = mCallbacks.beginBroadcast();
+ for (int i = 0; i < n; i++) {
+ try {
+ mCallbacks
+ .getBroadcastItem(i)
+ .onVolumeOffsetAudioLocationChanged(device, id, location);
+ } catch (RemoteException e) {
+ continue;
+ }
+ }
+ mCallbacks.finishBroadcast();
+ }
}
- void handleDeviceExtAudioDescriptionChanged(BluetoothDevice device, int id,
- String description) {
+ void handleDeviceExtAudioDescriptionChanged(
+ BluetoothDevice device, int id, String description) {
if (DBG) {
Log.d(TAG, " device: " + device + " offset_id: "
+ id + " description: " + description);
@@ -1120,6 +1195,24 @@
return;
}
offsets.setDescription(id, description);
+
+ if (mFeatureFlags.leaudioMultipleVocsInstancesApi()) {
+ if (mCallbacks == null) {
+ return;
+ }
+
+ int n = mCallbacks.beginBroadcast();
+ for (int i = 0; i < n; i++) {
+ try {
+ mCallbacks
+ .getBroadcastItem(i)
+ .onVolumeOffsetAudioDescriptionChanged(device, id, description);
+ } catch (RemoteException e) {
+ continue;
+ }
+ }
+ mCallbacks.finishBroadcast();
+ }
}
void messageFromNative(VolumeControlStackEvent stackEvent) {
@@ -1556,8 +1649,10 @@
}
@Override
- public void isVolumeOffsetAvailable(BluetoothDevice device,
- AttributionSource source, SynchronousResultReceiver receiver) {
+ public void isVolumeOffsetAvailable(
+ BluetoothDevice device,
+ AttributionSource source,
+ SynchronousResultReceiver receiver) {
try {
Objects.requireNonNull(device, "device cannot be null");
Objects.requireNonNull(source, "source cannot be null");
@@ -1576,8 +1671,34 @@
}
@Override
- public void setVolumeOffset(BluetoothDevice device, int volumeOffset,
- AttributionSource source, SynchronousResultReceiver receiver) {
+ public void getNumberOfVolumeOffsetInstances(
+ BluetoothDevice device,
+ AttributionSource source,
+ SynchronousResultReceiver receiver) {
+ try {
+ Objects.requireNonNull(device, "device cannot be null");
+ Objects.requireNonNull(source, "source cannot be null");
+ Objects.requireNonNull(receiver, "receiver cannot be null");
+
+ int defaultValue = 0;
+ VolumeControlService service = getService(source);
+ if (service != null) {
+ enforceBluetoothPrivilegedPermission(service);
+ defaultValue = service.getNumberOfVolumeOffsetInstances(device);
+ }
+ receiver.send(defaultValue);
+ } catch (RuntimeException e) {
+ receiver.propagateException(e);
+ }
+ }
+
+ @Override
+ public void setVolumeOffset(
+ BluetoothDevice device,
+ int instanceId,
+ int volumeOffset,
+ AttributionSource source,
+ SynchronousResultReceiver receiver) {
try {
Objects.requireNonNull(device, "device cannot be null");
Objects.requireNonNull(source, "source cannot be null");
@@ -1586,7 +1707,7 @@
VolumeControlService service = getService(source);
if (service != null) {
enforceBluetoothPrivilegedPermission(service);
- service.setVolumeOffset(device, volumeOffset);
+ service.setVolumeOffset(device, instanceId, volumeOffset);
}
receiver.send(null);
} catch (RuntimeException e) {
diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceBinderTest.java
index ae1d4af..58655f6 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceBinderTest.java
@@ -57,7 +57,6 @@
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
@Mock private A2dpService mA2dpService;
- @Mock private A2dpNativeInterface mNativeInterface;
@Mock private AudioRoutingManager mAudioRoutingManager;
@Mock private PackageManager mPackageManager;
@@ -66,12 +65,13 @@
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
+ doReturn(mAudioRoutingManager).when(mA2dpService).getActiveDeviceManager();
doReturn(mPackageManager).when(mA2dpService).getPackageManager();
ApplicationInfo appInfo = new ApplicationInfo();
appInfo.targetSdkVersion = android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
doReturn(appInfo).when(mPackageManager).getApplicationInfo(any(), anyInt());
- mBinder = new A2dpService.BluetoothA2dpBinder(mA2dpService, mAudioRoutingManager);
+ mBinder = new A2dpService.BluetoothA2dpBinder(mA2dpService);
}
@After
diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceTest.java
index 4200598..6dacf8f 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceTest.java
@@ -108,7 +108,8 @@
doReturn(mSilenceDeviceManager).when(mAdapterService).getSilenceDeviceManager();
mA2dpService = new A2dpService(mContext, mMockNativeInterface);
- mA2dpService.doStart();
+ mA2dpService.start();
+ mA2dpService.setAvailable(true);
// Override the timeout value to speed up the test
A2dpStateMachine.sConnectTimeoutMs = (int) TIMEOUT.toMillis();
@@ -124,7 +125,7 @@
@After
public void tearDown() throws Exception {
- mA2dpService.doStop();
+ mA2dpService.stop();
TestUtils.clearAdapterService(mAdapterService);
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceTest.java
index a48b5be..6f546da 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceTest.java
@@ -103,7 +103,7 @@
doReturn(true).when(mNativeInterface).setActiveDevice(any());
mService = new A2dpSinkService(mTargetContext, mNativeInterface, mLooper.getLooper());
- mService.doStart();
+ mService.start();
assertThat(mLooper.nextMessage()).isNull();
}
@@ -111,7 +111,7 @@
public void tearDown() throws Exception {
assertThat(mLooper.nextMessage()).isNull();
- mService.doStop();
+ mService.stop();
assertThat(A2dpSinkService.getA2dpSinkService()).isNull();
TestUtils.clearAdapterService(mAdapterService);
}
@@ -295,6 +295,26 @@
assertThat(config).isEqualTo(expected);
}
+ /** Make sure we ignore audio configuration changes for disconnected/unknown devices */
+ @Test
+ public void testOnAudioConfigChanged_withNullDevice_eventDropped() {
+ StackEvent audioConfigChanged =
+ StackEvent.audioConfigChanged(null, TEST_SAMPLE_RATE, TEST_CHANNEL_COUNT);
+ mService.messageFromNative(audioConfigChanged);
+ assertThat(mService.getAudioConfig(null)).isNull();
+ }
+
+ /** Make sure we ignore audio configuration changes for disconnected/unknown devices */
+ @Test
+ public void testOnAudioConfigChanged_withUnknownDevice_eventDropped() {
+ assertThat(mService.getConnectionState(mDevice1))
+ .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ StackEvent audioConfigChanged =
+ StackEvent.audioConfigChanged(mDevice1, TEST_SAMPLE_RATE, TEST_CHANNEL_COUNT);
+ mService.messageFromNative(audioConfigChanged);
+ assertThat(mService.getAudioConfig(mDevice1)).isNull();
+ }
+
/**
* Getting an audio config for a device that hasn't received one yet should return null
*/
diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStreamHandlerTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStreamHandlerTest.java
index c801935..4b25bbb 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStreamHandlerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStreamHandlerTest.java
@@ -84,7 +84,7 @@
TestUtils.setAdapterService(mAdapterService);
AvrcpControllerNativeInterface.setInstance(mMockAvrcpControllerNativeInterface);
mService = new AvrcpControllerService(mTargetContext, mMockAvrcpControllerNativeInterface);
- mService.doStart();
+ mService.start();
final Intent bluetoothBrowserMediaServiceStartIntent =
TestUtils.prepareIntentToStartBluetoothBrowserMediaService();
mBluetoothBrowserMediaServiceTestRule.startService(bluetoothBrowserMediaServiceStartIntent);
@@ -111,7 +111,7 @@
@After
public void tearDown() throws Exception {
- mService.doStop();
+ mService.stop();
AvrcpControllerNativeInterface.setInstance(null);
TestUtils.clearAdapterService(mAdapterService);
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClientTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClientTest.java
index f748dad..e3dd565 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClientTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClientTest.java
@@ -19,8 +19,6 @@
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.doReturn;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
@@ -68,7 +66,7 @@
TestUtils.setAdapterService(mAdapterService);
AvrcpControllerNativeInterface.setInstance(mNativeInterface);
mService = new AvrcpControllerService(targetContext, mNativeInterface);
- mService.doStart();
+ mService.start();
final Intent bluetoothBrowserMediaServiceStartIntent =
TestUtils.prepareIntentToStartBluetoothBrowserMediaService();
mBluetoothBrowserMediaServiceTestRule.startService(bluetoothBrowserMediaServiceStartIntent);
@@ -86,7 +84,7 @@
@After
public void tearDown() throws Exception {
- mService.doStop();
+ mService.stop();
AvrcpControllerNativeInterface.setInstance(null);
mService = AvrcpControllerService.getAvrcpControllerService();
assertThat(mService).isNull();
diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceTest.java
index 5ad1408..19b8f6c 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceTest.java
@@ -18,9 +18,7 @@
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.atLeastOnce;
-import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -82,7 +80,7 @@
TestUtils.setAdapterService(mAdapterService);
AvrcpControllerNativeInterface.setInstance(mNativeInterface);
mService = new AvrcpControllerService(targetContext, mNativeInterface);
- mService.doStart();
+ mService.start();
// Try getting the Bluetooth adapter
mAdapter = BluetoothAdapter.getDefaultAdapter();
assertThat(mAdapter).isNotNull();
@@ -95,7 +93,7 @@
@After
public void tearDown() throws Exception {
- mService.doStop();
+ mService.stop();
AvrcpControllerNativeInterface.setInstance(null);
mService = AvrcpControllerService.getAvrcpControllerService();
assertThat(mService).isNull();
diff --git a/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryServiceTest.java
index fbee892..64753a4 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/bas/BatteryServiceTest.java
@@ -17,7 +17,6 @@
package com.android.bluetooth.bas;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
@@ -95,11 +94,12 @@
private void startService() throws TimeoutException {
mService = new BatteryService(mTargetContext);
- mService.doStart();
+ mService.start();
+ mService.setAvailable(true);
}
private void stopService() throws TimeoutException {
- mService.doStop();
+ mService.stop();
mService = BatteryService.getBatteryService();
Assert.assertNull(mService);
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientServiceTest.java
index a554946..520e991 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientServiceTest.java
@@ -247,7 +247,8 @@
mFakeFlagsImpl.setFlag(Flags.FLAG_LEAUDIO_BROADCAST_AUDIO_HANDOVER_POLICIES, false);
mBassClientService = new BassClientService(mTargetContext, mFakeFlagsImpl);
- mBassClientService.doStart();
+ mBassClientService.start();
+ mBassClientService.setAvailable(true);
mBassClientService.mServiceFactory = mServiceFactory;
doReturn(mCsipService).when(mServiceFactory).getCsipSetCoordinatorService();
@@ -276,7 +277,7 @@
}
mBassClientService.unregisterCallback(mCallback);
- mBassClientService.doStop();
+ mBassClientService.stop();
mBassClientService = BassClientService.getBassClientService();
assertThat(mBassClientService).isNull();
mStateMachines.clear();
@@ -1562,4 +1563,248 @@
}
}
}
+
+ private void prepareTwoSynchronizedDevices() {
+ BluetoothLeBroadcastMetadata meta = createBroadcastMetadata(TEST_BROADCAST_ID);
+
+ doReturn(new ArrayList<BluetoothLeBroadcastMetadata>(Arrays.asList(meta)))
+ .when(mLeAudioService)
+ .getAllBroadcastMetadata();
+ prepareConnectedDeviceGroup();
+
+ verifyAddSourceForGroup(meta);
+ for (BassClientStateMachine sm : mStateMachines.values()) {
+ if (sm.getDevice().equals(mCurrentDevice)) {
+ injectRemoteSourceStateSourceAdded(
+ sm,
+ meta,
+ TEST_SOURCE_ID,
+ BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE,
+ meta.isEncrypted()
+ ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING
+ : BluetoothLeBroadcastReceiveState
+ .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED,
+ null);
+ // verify source id
+ try {
+ verify(mCallback, timeout(TIMEOUT_MS).atLeastOnce())
+ .onSourceAdded(
+ eq(mCurrentDevice),
+ eq(TEST_SOURCE_ID),
+ eq(BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST));
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ } else if (sm.getDevice().equals(mCurrentDevice1)) {
+ injectRemoteSourceStateSourceAdded(
+ sm,
+ meta,
+ TEST_SOURCE_ID + 1,
+ BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE,
+ meta.isEncrypted()
+ ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING
+ : BluetoothLeBroadcastReceiveState
+ .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED,
+ null);
+ // verify source id
+ try {
+ verify(mCallback, timeout(TIMEOUT_MS).atLeastOnce())
+ .onSourceAdded(
+ eq(mCurrentDevice1),
+ eq(TEST_SOURCE_ID + 1),
+ eq(BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST));
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testPrivateBroadcastIntentionalDisconnection() {
+ prepareTwoSynchronizedDevices();
+
+ /* Imitate broadcast being active */
+ doReturn(true).when(mLeAudioService).isPlaying(TEST_BROADCAST_ID);
+ /* Imitate devices being primary */
+ doReturn(true).when(mLeAudioService).isPrimaryDevice(mCurrentDevice);
+ doReturn(true).when(mLeAudioService).isPrimaryDevice(mCurrentDevice1);
+
+ /* Imitate device 1/2 disconnection from StateMachine context */
+ mBassClientService.handleDeviceDisconnection(mCurrentDevice, true);
+
+ /* After first device disconnection and de-synchronization expect not stopping broadcast */
+ verify(mLeAudioService, times(0)).stopBroadcast(eq(TEST_BROADCAST_ID));
+
+ /* Imitate first device being in disconnected state */
+ doReturn(BluetoothProfile.STATE_DISCONNECTED)
+ .when(mStateMachines.get(mCurrentDevice))
+ .getConnectionState();
+
+ /* Imitate device 2/2 disconnection from StateMachine context */
+ mBassClientService.handleDeviceDisconnection(mCurrentDevice1, true);
+
+ /* After second device disconnection and de-synchronization expect stopping broadcast */
+ verify(mLeAudioService, times(1)).stopBroadcast(eq(TEST_BROADCAST_ID));
+ }
+
+ @Test
+ public void testPrivateBroadcastUnintentionalDisconnection() {
+ prepareTwoSynchronizedDevices();
+
+ /* Imitate broadcast being active */
+ doReturn(true).when(mLeAudioService).isPlaying(TEST_BROADCAST_ID);
+ /* Imitate devices being primary */
+ doReturn(true).when(mLeAudioService).isPrimaryDevice(mCurrentDevice);
+ doReturn(true).when(mLeAudioService).isPrimaryDevice(mCurrentDevice1);
+
+ /* Imitate device 1/2 disconnection from StateMachine context */
+ mBassClientService.handleDeviceDisconnection(mCurrentDevice, false);
+
+ /* After first device disconnection and de-synchronization expect not stopping broadcast */
+ verify(mLeAudioService, times(0)).stopBroadcast(eq(TEST_BROADCAST_ID));
+
+ /* Imitate first device being in disconnected state */
+ doReturn(BluetoothProfile.STATE_DISCONNECTED)
+ .when(mStateMachines.get(mCurrentDevice))
+ .getConnectionState();
+
+ /* Imitate device 2/2 disconnection from StateMachine context */
+ mBassClientService.handleDeviceDisconnection(mCurrentDevice1, false);
+
+ /* After second device disconnection and de-synchronization expect stopping broadcast */
+ verify(mLeAudioService, times(1)).stopBroadcast(eq(TEST_BROADCAST_ID));
+ }
+
+ @Test
+ public void testAudioSharingIntentionalDisconnection() {
+ prepareTwoSynchronizedDevices();
+
+ /* Imitate broadcast being active */
+ doReturn(true).when(mLeAudioService).isPlaying(TEST_BROADCAST_ID);
+ /* Imitate devices being primary */
+ doReturn(true).when(mLeAudioService).isPrimaryDevice(mCurrentDevice);
+ doReturn(false).when(mLeAudioService).isPrimaryDevice(mCurrentDevice1);
+
+ /* Imitate device 1/2 disconnection from StateMachine context */
+ mBassClientService.handleDeviceDisconnection(mCurrentDevice, true);
+
+ /* After first device disconnection and de-synchronization expect stopping broadcast */
+ verify(mLeAudioService, times(1)).stopBroadcast(eq(TEST_BROADCAST_ID));
+
+ /* Imitate first device being in disconnected state */
+ doReturn(BluetoothProfile.STATE_DISCONNECTED)
+ .when(mStateMachines.get(mCurrentDevice))
+ .getConnectionState();
+
+ /* Imitate device 2/2 disconnection from StateMachine context */
+ mBassClientService.handleDeviceDisconnection(mCurrentDevice1, true);
+
+ /* After second device disconnection and de-synchronization expect not stopping broadcast */
+ verify(mLeAudioService, times(1)).stopBroadcast(eq(TEST_BROADCAST_ID));
+ }
+
+ @Test
+ public void testAudioSharingUnintentionalDisconnection() {
+ prepareTwoSynchronizedDevices();
+
+ /* Imitate broadcast being active */
+ doReturn(true).when(mLeAudioService).isPlaying(TEST_BROADCAST_ID);
+ /* Imitate devices being primary */
+ doReturn(true).when(mLeAudioService).isPrimaryDevice(mCurrentDevice);
+ doReturn(false).when(mLeAudioService).isPrimaryDevice(mCurrentDevice1);
+
+ /* Imitate device 1/2 disconnection from StateMachine context */
+ mBassClientService.handleDeviceDisconnection(mCurrentDevice, false);
+
+ /* After first device disconnection and de-synchronization expect not stopping broadcast */
+ verify(mLeAudioService, times(0)).stopBroadcast(eq(TEST_BROADCAST_ID));
+
+ /* Imitate first device being in disconnected state */
+ doReturn(BluetoothProfile.STATE_DISCONNECTED)
+ .when(mStateMachines.get(mCurrentDevice))
+ .getConnectionState();
+
+ /* Imitate device 2/2 disconnection from StateMachine context */
+ mBassClientService.handleDeviceDisconnection(mCurrentDevice1, false);
+
+ /* After second device disconnection and de-synchronization timeout to be fired */
+ verify(mLeAudioService, times(0)).stopBroadcast(eq(TEST_BROADCAST_ID));
+ }
+
+ @Test
+ public void testNotifyBroadcastStateChangedStopped() {
+ BluetoothLeBroadcastMetadata meta = createBroadcastMetadata(TEST_BROADCAST_ID);
+
+ doReturn(new ArrayList<BluetoothLeBroadcastMetadata>(Arrays.asList(meta)))
+ .when(mLeAudioService)
+ .getAllBroadcastMetadata();
+ prepareConnectedDeviceGroup();
+
+ verifyAddSourceForGroup(meta);
+ for (BassClientStateMachine sm : mStateMachines.values()) {
+ if (sm.getDevice().equals(mCurrentDevice)) {
+ injectRemoteSourceStateSourceAdded(
+ sm,
+ meta,
+ TEST_SOURCE_ID,
+ BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE,
+ meta.isEncrypted()
+ ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING
+ : BluetoothLeBroadcastReceiveState
+ .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED,
+ null);
+ // verify source id
+ try {
+ verify(mCallback, timeout(TIMEOUT_MS).atLeastOnce())
+ .onSourceAdded(
+ eq(mCurrentDevice),
+ eq(TEST_SOURCE_ID),
+ eq(BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST));
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ } else if (sm.getDevice().equals(mCurrentDevice1)) {
+ injectRemoteSourceStateSourceAdded(
+ sm,
+ meta,
+ TEST_SOURCE_ID + 1,
+ BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_IDLE,
+ meta.isEncrypted()
+ ? BluetoothLeBroadcastReceiveState.BIG_ENCRYPTION_STATE_DECRYPTING
+ : BluetoothLeBroadcastReceiveState
+ .BIG_ENCRYPTION_STATE_NOT_ENCRYPTED,
+ null);
+ // verify source id
+ try {
+ verify(mCallback, timeout(TIMEOUT_MS).atLeastOnce())
+ .onSourceAdded(
+ eq(mCurrentDevice1),
+ eq(TEST_SOURCE_ID + 1),
+ eq(BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST));
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+ }
+
+ /* Imitate broadcast being not active */
+ doReturn(false).when(mLeAudioService).isPlaying(TEST_BROADCAST_ID);
+
+ mBassClientService.notifyBroadcastStateChanged(
+ 0 /* BROADCAST_STATE_STOPPED */, TEST_BROADCAST_ID);
+
+ /* Imitiate scenario when if there would be broadcast - stop would be called */
+ mBassClientService.handleDeviceDisconnection(mCurrentDevice, true);
+ mBassClientService.handleDeviceDisconnection(mCurrentDevice1, true);
+
+ /* Imitate first device being in disconnected state */
+ doReturn(BluetoothProfile.STATE_DISCONNECTED)
+ .when(mStateMachines.get(mCurrentDevice))
+ .getConnectionState();
+
+ /* After second device disconnection and de-synchronization expect not calling broadcast to
+ * stop due to previous broadcast stream stopped */
+ verify(mLeAudioService, times(0)).stopBroadcast(eq(TEST_BROADCAST_ID));
+ }
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientStateMachineTest.java
index 7751cfe..6b27bb9 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
@@ -137,6 +137,7 @@
mAdapter = BluetoothAdapter.getDefaultAdapter();
mFakeFlagsImpl = new FakeFeatureFlagsImpl();
mFakeFlagsImpl.setFlag(Flags.FLAG_LEAUDIO_BROADCAST_MONITOR_SOURCE_SYNC_STATUS, false);
+ mFakeFlagsImpl.setFlag(Flags.FLAG_LEAUDIO_BROADCAST_AUDIO_HANDOVER_POLICIES, false);
BluetoothMethodProxy.setInstanceForTesting(mMethodProxy);
doNothing().when(mMethodProxy).periodicAdvertisingManagerTransferSync(
any(), any(), anyInt(), anyInt());
@@ -763,7 +764,8 @@
value[BassConstants.BCAST_RCVR_STATE_SRC_ADDR_START_IDX + i] = 0x00;
}
when(mBassClientService.getPeriodicAdvertisementResult(any(), anyInt())).thenReturn(null);
- when(mBassClientService.isLocalBroadcast(any())).thenReturn(true);
+ when(mBassClientService.isLocalBroadcast(any(BluetoothLeBroadcastMetadata.class)))
+ .thenReturn(true);
when(characteristic.getValue()).thenReturn(value);
mBassClientStateMachine.mPendingSourceToSwitch = mBassClientStateMachine.mPendingMetadata;
@@ -1179,7 +1181,8 @@
BluetoothLeBroadcastMetadata metadata = createBroadcastMetadata();
// verify local broadcast doesn't require active synced source
- when(mBassClientService.isLocalBroadcast(any())).thenReturn(true);
+ when(mBassClientService.isLocalBroadcast(any(BluetoothLeBroadcastMetadata.class)))
+ .thenReturn(true);
mBassClientStateMachine.sendMessage(ADD_BCAST_SOURCE, metadata);
TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper());
@@ -1666,7 +1669,8 @@
BluetoothLeBroadcastMetadata metadata = createBroadcastMetadata();
// verify local broadcast doesn't require active synced source
- when(mBassClientService.isLocalBroadcast(any())).thenReturn(true);
+ when(mBassClientService.isLocalBroadcast(any(BluetoothLeBroadcastMetadata.class)))
+ .thenReturn(true);
mBassClientStateMachine.sendMessage(ADD_BCAST_SOURCE, metadata);
TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper());
@@ -1700,7 +1704,8 @@
BluetoothLeBroadcastMetadata metadata = createBroadcastMetadata();
// verify local broadcast doesn't require active synced source
- when(mBassClientService.isLocalBroadcast(any())).thenReturn(true);
+ when(mBassClientService.isLocalBroadcast(any(BluetoothLeBroadcastMetadata.class)))
+ .thenReturn(true);
mBassClientStateMachine.sendMessage(ADD_BCAST_SOURCE, metadata);
TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper());
@@ -1778,7 +1783,8 @@
when(mBassClientService.getCallbacks()).thenReturn(callbacks);
BluetoothLeBroadcastMetadata metadata = createBroadcastMetadata();
- when(mBassClientService.isLocalBroadcast(any())).thenReturn(false);
+ when(mBassClientService.isLocalBroadcast(any(BluetoothLeBroadcastMetadata.class)))
+ .thenReturn(false);
when(mBassClientService.getActiveSyncedSources(any())).thenReturn(null);
when(mBassClientService.getCachedBroadcast(anyInt())).thenReturn(null);
mBassClientStateMachine.sendMessage(ADD_BCAST_SOURCE, metadata);
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 0546ff4..7cc9aec 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
@@ -41,6 +41,7 @@
import android.content.Context;
import android.media.AudioManager;
import android.os.test.TestLooper;
+import android.platform.test.flag.junit.SetFlagsRule;
import android.util.ArrayMap;
import android.util.SparseIntArray;
@@ -52,8 +53,6 @@
import com.android.bluetooth.Utils;
import com.android.bluetooth.a2dp.A2dpService;
import com.android.bluetooth.btservice.storage.DatabaseManager;
-import com.android.bluetooth.flags.FakeFeatureFlagsImpl;
-import com.android.bluetooth.flags.FeatureFlags;
import com.android.bluetooth.flags.Flags;
import com.android.bluetooth.hearingaid.HearingAidService;
import com.android.bluetooth.hfp.HeadsetService;
@@ -63,6 +62,7 @@
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
@@ -98,7 +98,7 @@
private boolean mOriginalDualModeAudioState;
private TestDatabaseManager mDatabaseManager;
private TestLooper mTestLooper;
- private FakeFeatureFlagsImpl mFakeFlagsImpl;
+ @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
@Mock private AdapterService mAdapterService;
@Mock private ServiceFactory mServiceFactory;
@@ -120,9 +120,7 @@
mTestLooper.startAutoDispatch();
TestUtils.setAdapterService(mAdapterService);
- mFakeFlagsImpl = new FakeFeatureFlagsImpl();
- mFakeFlagsImpl.setFlag(Flags.FLAG_LEAUDIO_BROADCAST_AUDIO_HANDOVER_POLICIES, false);
- mDatabaseManager = new TestDatabaseManager(mAdapterService, mFakeFlagsImpl);
+ mDatabaseManager = new TestDatabaseManager(mAdapterService);
when(mAdapterService.getSystemService(Context.AUDIO_SERVICE)).thenReturn(mAudioManager);
when(mAdapterService.getSystemServiceName(AudioManager.class))
@@ -133,8 +131,7 @@
when(mServiceFactory.getHearingAidService()).thenReturn(mHearingAidService);
when(mServiceFactory.getLeAudioService()).thenReturn(mLeAudioService);
- mActiveDeviceManager =
- new ActiveDeviceManager(mAdapterService, mServiceFactory, mFakeFlagsImpl);
+ mActiveDeviceManager = new ActiveDeviceManager(mAdapterService, mServiceFactory);
mActiveDeviceManager.start();
mAdapter = BluetoothAdapter.getDefaultAdapter();
@@ -160,6 +157,11 @@
when(mLeAudioService.setActiveDevice(any())).thenReturn(true);
when(mLeAudioService.removeActiveDevice(anyBoolean())).thenReturn(true);
+ when(mLeAudioService.getLeadDevice(mLeAudioDevice)).thenReturn(mLeAudioDevice);
+ when(mLeAudioService.getLeadDevice(mLeAudioDevice2)).thenReturn(mLeAudioDevice2);
+ when(mLeAudioService.getLeadDevice(mDualModeAudioDevice)).thenReturn(mDualModeAudioDevice);
+ when(mLeAudioService.getLeadDevice(mLeHearingAidDevice)).thenReturn(mLeHearingAidDevice);
+
List<BluetoothDevice> connectedHearingAidDevices = new ArrayList<>();
connectedHearingAidDevices.add(mHearingAidDevice);
when(mHearingAidService.getHiSyncId(mHearingAidDevice)).thenReturn(mHearingAidHiSyncId);
@@ -742,11 +744,11 @@
leAudioConnected(mLeAudioDevice);
verify(mLeAudioService, timeout(TIMEOUT_MS)).setActiveDevice(mLeAudioDevice);
- leAudioConnected(mSecondaryAudioDevice);
- verify(mLeAudioService, timeout(TIMEOUT_MS)).setActiveDevice(mSecondaryAudioDevice);
+ leAudioConnected(mLeAudioDevice2);
+ verify(mLeAudioService, timeout(TIMEOUT_MS)).setActiveDevice(mLeAudioDevice2);
Mockito.clearInvocations(mLeAudioService);
- leAudioDisconnected(mSecondaryAudioDevice);
+ leAudioDisconnected(mLeAudioDevice2);
verify(mLeAudioService, timeout(TIMEOUT_MS)).setActiveDevice(mLeAudioDevice);
}
@@ -905,6 +907,35 @@
verify(mLeAudioService, timeout(TIMEOUT_MS)).deviceDisconnected(mLeAudioDevice2, true);
}
+ @Test
+ public void leAudioSetConnectedGroupThenDisconnected_noFallback() {
+ mSetFlagsRule.enableFlags(Flags.FLAG_LEAUDIO_ACTIVE_DEVICE_MANAGER_GROUP_HANDLING_FIX);
+ when(mAudioManager.getMode()).thenReturn(AudioManager.MODE_NORMAL);
+
+ leAudioConnected(mLeAudioDevice);
+ TestUtils.waitForLooperToFinishScheduledTask(mActiveDeviceManager.getHandlerLooper());
+ verify(mLeAudioService, timeout(TIMEOUT_MS)).setActiveDevice(mLeAudioDevice);
+
+ Mockito.clearInvocations(mLeAudioService);
+
+ when(mLeAudioService.getLeadDevice(mLeAudioDevice2)).thenReturn(mLeAudioDevice);
+ leAudioConnected(mLeAudioDevice2);
+ TestUtils.waitForLooperToFinishScheduledTask(mActiveDeviceManager.getHandlerLooper());
+ verify(mLeAudioService, never()).setActiveDevice(any());
+
+ Mockito.clearInvocations(mLeAudioService);
+
+ leAudioDisconnected(mLeAudioDevice2);
+ TestUtils.waitForLooperToFinishScheduledTask(mActiveDeviceManager.getHandlerLooper());
+ verify(mLeAudioService, never()).setActiveDevice(any());
+ verify(mLeAudioService, never()).removeActiveDevice(anyBoolean());
+
+ leAudioDisconnected(mLeAudioDevice);
+ TestUtils.waitForLooperToFinishScheduledTask(mActiveDeviceManager.getHandlerLooper());
+ verify(mLeAudioService, timeout(TIMEOUT_MS)).removeActiveDevice(false);
+ verify(mLeAudioService, timeout(TIMEOUT_MS)).deviceDisconnected(mLeAudioDevice2, false);
+ }
+
/**
* An A2DP connected. An LE Audio connected. The LE Audio disconnected.
* Then the A2DP should be the active one.
@@ -1089,15 +1120,24 @@
when(mLeAudioService.setActiveDevice(any())).thenReturn(true);
when(mLeAudioService.removeActiveDevice(anyBoolean())).thenReturn(true);
+ when(mLeAudioService.getLeadDevice(mDualModeAudioDevice)).thenReturn(mDualModeAudioDevice);
+
+ Mockito.clearInvocations(mLeAudioService);
// Ensure we make LEA active after all supported classic profiles are active
a2dpActiveDeviceChanged(mDualModeAudioDevice);
TestUtils.waitForLooperToFinishScheduledTask(mActiveDeviceManager.getHandlerLooper());
+
when(mAdapterService.isAllSupportedClassicAudioProfilesActive(mDualModeAudioDevice))
.thenReturn(true);
headsetActiveDeviceChanged(mDualModeAudioDevice);
TestUtils.waitForLooperToFinishScheduledTask(mActiveDeviceManager.getHandlerLooper());
- verify(mLeAudioService, times(2)).setActiveDevice(mDualModeAudioDevice);
+
+ // When A2DP device is getting active, first LeAudio device is removed from active devices
+ // and later added
+ verify(mLeAudioService, times(1)).removeActiveDevice(anyBoolean());
+ verify(mLeAudioService, times(1)).setActiveDevice(mDualModeAudioDevice);
+
Assert.assertEquals(mDualModeAudioDevice, mActiveDeviceManager.getA2dpActiveDevice());
Assert.assertEquals(mDualModeAudioDevice, mActiveDeviceManager.getHfpActiveDevice());
Assert.assertEquals(mDualModeAudioDevice, mActiveDeviceManager.getLeAudioActiveDevice());
@@ -1187,7 +1227,7 @@
*/
@Test
public void a2dpConnectedWhenBroadcasting_notSetA2dpActive() {
- mFakeFlagsImpl.setFlag(Flags.FLAG_LEAUDIO_BROADCAST_AUDIO_HANDOVER_POLICIES, true);
+ mSetFlagsRule.enableFlags(Flags.FLAG_LEAUDIO_BROADCAST_AUDIO_HANDOVER_POLICIES);
final List<BluetoothLeBroadcastMetadata> metadataList = mock(List.class);
when(mLeAudioService.getAllBroadcastMetadata()).thenReturn(metadataList);
a2dpConnected(mA2dpDevice, false);
@@ -1202,7 +1242,7 @@
*/
@Test
public void headsetConnectedWhenBroadcasting_notSetHeadsetActive() {
- mFakeFlagsImpl.setFlag(Flags.FLAG_LEAUDIO_BROADCAST_AUDIO_HANDOVER_POLICIES, true);
+ mSetFlagsRule.enableFlags(Flags.FLAG_LEAUDIO_BROADCAST_AUDIO_HANDOVER_POLICIES);
final List<BluetoothLeBroadcastMetadata> metadataList = mock(List.class);
when(mLeAudioService.getAllBroadcastMetadata()).thenReturn(metadataList);
headsetConnected(mHeadsetDevice, false);
@@ -1217,7 +1257,7 @@
*/
@Test
public void hearingAidConnectedWhenBroadcasting_notSetHearingAidActive() {
- mFakeFlagsImpl.setFlag(Flags.FLAG_LEAUDIO_BROADCAST_AUDIO_HANDOVER_POLICIES, true);
+ mSetFlagsRule.enableFlags(Flags.FLAG_LEAUDIO_BROADCAST_AUDIO_HANDOVER_POLICIES);
final List<BluetoothLeBroadcastMetadata> metadataList = mock(List.class);
when(mLeAudioService.getAllBroadcastMetadata()).thenReturn(metadataList);
hearingAidConnected(mHearingAidDevice);
@@ -1230,7 +1270,7 @@
*/
@Test
public void leHearingAidConnectedWhenBroadcasting_notSetLeHearingAidActive() {
- mFakeFlagsImpl.setFlag(Flags.FLAG_LEAUDIO_BROADCAST_AUDIO_HANDOVER_POLICIES, true);
+ mSetFlagsRule.enableFlags(Flags.FLAG_LEAUDIO_BROADCAST_AUDIO_HANDOVER_POLICIES);
final List<BluetoothLeBroadcastMetadata> metadataList = mock(List.class);
when(mLeAudioService.getAllBroadcastMetadata()).thenReturn(metadataList);
leHearingAidConnected(mLeHearingAidDevice);
@@ -1434,8 +1474,8 @@
private class TestDatabaseManager extends DatabaseManager {
ArrayMap<BluetoothDevice, SparseIntArray> mProfileConnectionPolicy;
- TestDatabaseManager(AdapterService service, FeatureFlags featureFlags) {
- super(service, featureFlags);
+ TestDatabaseManager(AdapterService service) {
+ super(service);
mProfileConnectionPolicy = new ArrayMap<>();
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/AudioRoutingManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/AudioRoutingManagerTest.java
index 362c953..d294c33 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/btservice/AudioRoutingManagerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/AudioRoutingManagerTest.java
@@ -49,8 +49,6 @@
import com.android.bluetooth.Utils;
import com.android.bluetooth.a2dp.A2dpService;
import com.android.bluetooth.btservice.storage.DatabaseManager;
-import com.android.bluetooth.flags.FakeFeatureFlagsImpl;
-import com.android.bluetooth.flags.FeatureFlags;
import com.android.bluetooth.hearingaid.HearingAidService;
import com.android.bluetooth.hfp.HeadsetService;
import com.android.bluetooth.le_audio.LeAudioService;
@@ -92,7 +90,6 @@
private boolean mOriginalDualModeAudioState;
private TestDatabaseManager mDatabaseManager;
private TestLooper mTestLooper;
- private FakeFeatureFlagsImpl mFakeFlagsImpl;
@Mock private AdapterService mAdapterService;
@Mock private ServiceFactory mServiceFactory;
@@ -116,8 +113,7 @@
doNothing().when(mMethodProxy).threadStart(any());
TestUtils.setAdapterService(mAdapterService);
- mFakeFlagsImpl = new FakeFeatureFlagsImpl();
- mDatabaseManager = new TestDatabaseManager(mAdapterService, mFakeFlagsImpl);
+ mDatabaseManager = new TestDatabaseManager(mAdapterService);
when(mAdapterService.getSystemService(Context.AUDIO_SERVICE)).thenReturn(mAudioManager);
when(mAdapterService.getSystemServiceName(AudioManager.class))
@@ -128,8 +124,7 @@
when(mServiceFactory.getHearingAidService()).thenReturn(mHearingAidService);
when(mServiceFactory.getLeAudioService()).thenReturn(mLeAudioService);
- mAudioRoutingManager =
- new AudioRoutingManager(mAdapterService, mServiceFactory, mFakeFlagsImpl);
+ mAudioRoutingManager = new AudioRoutingManager(mAdapterService, mServiceFactory);
mAudioRoutingManager.start();
mAdapter = BluetoothAdapter.getDefaultAdapter();
@@ -1291,8 +1286,8 @@
private class TestDatabaseManager extends DatabaseManager {
ArrayMap<BluetoothDevice, SparseIntArray> mProfileConnectionPolicy;
- TestDatabaseManager(AdapterService service, FeatureFlags featureFlags) {
- super(service, featureFlags);
+ TestDatabaseManager(AdapterService service) {
+ super(service);
mProfileConnectionPolicy = new ArrayMap<>();
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/PhonePolicyTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/PhonePolicyTest.java
index 95e2d70..f088861 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/btservice/PhonePolicyTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/PhonePolicyTest.java
@@ -28,6 +28,7 @@
import android.os.HandlerThread;
import android.os.ParcelUuid;
import android.os.SystemProperties;
+import android.platform.test.flag.junit.SetFlagsRule;
import androidx.room.Room;
import androidx.test.filters.MediumTest;
@@ -39,13 +40,13 @@
import com.android.bluetooth.a2dp.A2dpService;
import com.android.bluetooth.btservice.storage.DatabaseManager;
import com.android.bluetooth.btservice.storage.MetadataDatabase;
-import com.android.bluetooth.flags.FakeFeatureFlagsImpl;
import com.android.bluetooth.flags.Flags;
import com.android.bluetooth.hfp.HeadsetService;
import com.android.bluetooth.le_audio.LeAudioService;
import org.junit.After;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
@@ -64,18 +65,18 @@
private static final int CONNECT_OTHER_PROFILES_TIMEOUT_WAIT_MILLIS =
CONNECT_OTHER_PROFILES_TIMEOUT_MILLIS * 3;
+ @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
+
private HandlerThread mHandlerThread;
private BluetoothAdapter mAdapter;
private PhonePolicy mPhonePolicy;
private boolean mOriginalDualModeState;
- private FakeFeatureFlagsImpl mFakeFlagsImpl;
@Mock private AdapterService mAdapterService;
@Mock private ServiceFactory mServiceFactory;
@Mock private HeadsetService mHeadsetService;
@Mock private A2dpService mA2dpService;
@Mock private LeAudioService mLeAudioService;
-
@Mock private DatabaseManager mDatabaseManager;
@Before
@@ -104,9 +105,7 @@
mAdapter = BluetoothAdapter.getDefaultAdapter();
PhonePolicy.sConnectOtherProfilesTimeoutMillis = CONNECT_OTHER_PROFILES_TIMEOUT_MILLIS;
- mFakeFlagsImpl = new FakeFeatureFlagsImpl();
-
- mPhonePolicy = new PhonePolicy(mAdapterService, mServiceFactory, mFakeFlagsImpl);
+ mPhonePolicy = new PhonePolicy(mAdapterService, mServiceFactory);
mOriginalDualModeState = Utils.isDualModeAudioEnabled();
}
@@ -633,8 +632,8 @@
*/
@Test
public void testAutoConnectHfpOnly() {
- mFakeFlagsImpl.setFlag(Flags.FLAG_AUTO_CONNECT_ON_HFP_WHEN_NO_A2DP_DEVICE, true);
- mFakeFlagsImpl.setFlag(Flags.FLAG_AUTO_CONNECT_ON_MULTIPLE_HFP_WHEN_NO_A2DP_DEVICE, false);
+ mSetFlagsRule.enableFlags(Flags.FLAG_AUTO_CONNECT_ON_HFP_WHEN_NO_A2DP_DEVICE);
+ mSetFlagsRule.disableFlags(Flags.FLAG_AUTO_CONNECT_ON_MULTIPLE_HFP_WHEN_NO_A2DP_DEVICE);
// Return desired values from the mocked object(s)
doReturn(BluetoothAdapter.STATE_ON).when(mAdapterService).getState();
@@ -645,9 +644,9 @@
InstrumentationRegistry.getInstrumentation().getTargetContext(),
MetadataDatabase.class)
.build();
- DatabaseManager db = new DatabaseManager(mAdapterService, mFakeFlagsImpl);
+ DatabaseManager db = new DatabaseManager(mAdapterService);
doReturn(db).when(mAdapterService).getDatabase();
- PhonePolicy phonePolicy = new PhonePolicy(mAdapterService, mServiceFactory, mFakeFlagsImpl);
+ PhonePolicy phonePolicy = new PhonePolicy(mAdapterService, mServiceFactory);
db.start(mDatabase);
TestUtils.waitForLooperToFinishScheduledTask(db.getHandlerLooper());
@@ -671,8 +670,8 @@
@Test
public void autoConnect_whenMultiHfp_startConnection() {
- mFakeFlagsImpl.setFlag(Flags.FLAG_AUTO_CONNECT_ON_HFP_WHEN_NO_A2DP_DEVICE, true);
- mFakeFlagsImpl.setFlag(Flags.FLAG_AUTO_CONNECT_ON_MULTIPLE_HFP_WHEN_NO_A2DP_DEVICE, true);
+ mSetFlagsRule.enableFlags(Flags.FLAG_AUTO_CONNECT_ON_HFP_WHEN_NO_A2DP_DEVICE);
+ mSetFlagsRule.enableFlags(Flags.FLAG_AUTO_CONNECT_ON_MULTIPLE_HFP_WHEN_NO_A2DP_DEVICE);
// Return desired values from the mocked object(s)
doReturn(BluetoothAdapter.STATE_ON).when(mAdapterService).getState();
@@ -683,9 +682,9 @@
InstrumentationRegistry.getInstrumentation().getTargetContext(),
MetadataDatabase.class)
.build();
- DatabaseManager db = new DatabaseManager(mAdapterService, mFakeFlagsImpl);
+ DatabaseManager db = new DatabaseManager(mAdapterService);
doReturn(db).when(mAdapterService).getDatabase();
- PhonePolicy phonePolicy = new PhonePolicy(mAdapterService, mServiceFactory, mFakeFlagsImpl);
+ PhonePolicy phonePolicy = new PhonePolicy(mAdapterService, mServiceFactory);
db.start(mDatabase);
TestUtils.waitForLooperToFinishScheduledTask(db.getHandlerLooper());
@@ -715,8 +714,8 @@
@Test
public void autoConnect_whenMultiHfpAndDeconnection_startConnection() {
- mFakeFlagsImpl.setFlag(Flags.FLAG_AUTO_CONNECT_ON_HFP_WHEN_NO_A2DP_DEVICE, true);
- mFakeFlagsImpl.setFlag(Flags.FLAG_AUTO_CONNECT_ON_MULTIPLE_HFP_WHEN_NO_A2DP_DEVICE, true);
+ mSetFlagsRule.enableFlags(Flags.FLAG_AUTO_CONNECT_ON_MULTIPLE_HFP_WHEN_NO_A2DP_DEVICE);
+ mSetFlagsRule.enableFlags(Flags.FLAG_AUTO_CONNECT_ON_HFP_WHEN_NO_A2DP_DEVICE);
// Return desired values from the mocked object(s)
doReturn(BluetoothAdapter.STATE_ON).when(mAdapterService).getState();
@@ -727,9 +726,9 @@
InstrumentationRegistry.getInstrumentation().getTargetContext(),
MetadataDatabase.class)
.build();
- DatabaseManager db = new DatabaseManager(mAdapterService, mFakeFlagsImpl);
+ DatabaseManager db = new DatabaseManager(mAdapterService);
doReturn(db).when(mAdapterService).getDatabase();
- PhonePolicy phonePolicy = new PhonePolicy(mAdapterService, mServiceFactory, mFakeFlagsImpl);
+ PhonePolicy phonePolicy = new PhonePolicy(mAdapterService, mServiceFactory);
db.start(mDatabase);
TestUtils.waitForLooperToFinishScheduledTask(db.getHandlerLooper());
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 73d715d..679850b 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
@@ -37,6 +37,7 @@
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
+import android.platform.test.flag.junit.SetFlagsRule;
import androidx.room.Room;
import androidx.room.testing.MigrationTestHelper;
@@ -48,7 +49,6 @@
import com.android.bluetooth.TestUtils;
import com.android.bluetooth.btservice.AdapterService;
-import com.android.bluetooth.flags.FakeFeatureFlagsImpl;
import com.android.bluetooth.flags.Flags;
import com.google.common.truth.Truth;
@@ -81,7 +81,6 @@
private BluetoothDevice mTestDevice;
private BluetoothDevice mTestDevice2;
private BluetoothDevice mTestDevice3;
- private FakeFeatureFlagsImpl mFakeFlagsImpl;
private static final String LOCAL_STORAGE = "LocalStorage";
private static final String TEST_BT_ADDR = "11:22:33:44:55:66";
@@ -95,6 +94,8 @@
private static final int MAX_META_ID = 16;
private static final byte[] TEST_BYTE_ARRAY = "TEST_VALUE".getBytes();
+ @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
+
@Rule
public MigrationTestHelper testHelper = new MigrationTestHelper(
InstrumentationRegistry.getInstrumentation(),
@@ -116,9 +117,7 @@
when(mAdapterService.getPackageManager()).thenReturn(
InstrumentationRegistry.getTargetContext().getPackageManager());
- mFakeFlagsImpl = new FakeFeatureFlagsImpl();
-
- mDatabaseManager = new DatabaseManager(mAdapterService, mFakeFlagsImpl);
+ mDatabaseManager = new DatabaseManager(mAdapterService);
BluetoothDevice[] bondedDevices = {mTestDevice};
doReturn(bondedDevices).when(mAdapterService).getBondedDevices();
@@ -491,7 +490,7 @@
@Test
public void testSetConnectionHeadset() {
- mFakeFlagsImpl.setFlag(Flags.FLAG_AUTO_CONNECT_ON_MULTIPLE_HFP_WHEN_NO_A2DP_DEVICE, false);
+ mSetFlagsRule.disableFlags(Flags.FLAG_AUTO_CONNECT_ON_MULTIPLE_HFP_WHEN_NO_A2DP_DEVICE);
// Verify pre-conditions to ensure a fresh test
Assert.assertEquals(0, mDatabaseManager.mMetadataCache.size());
Assert.assertNotNull(mTestDevice);
@@ -544,7 +543,7 @@
@Test
public void testSetConnection() {
- mFakeFlagsImpl.setFlag(Flags.FLAG_AUTO_CONNECT_ON_MULTIPLE_HFP_WHEN_NO_A2DP_DEVICE, false);
+ mSetFlagsRule.disableFlags(Flags.FLAG_AUTO_CONNECT_ON_MULTIPLE_HFP_WHEN_NO_A2DP_DEVICE);
// Verify pre-conditions to ensure a fresh test
Assert.assertEquals(0, mDatabaseManager.mMetadataCache.size());
Assert.assertNotNull(mTestDevice);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/content_profiles/ContentProfileErrorReportUtilsTest.java b/android/app/tests/unit/src/com/android/bluetooth/content_profiles/ContentProfileErrorReportUtilsTest.java
index bee0c10..bdfe10d 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/content_profiles/ContentProfileErrorReportUtilsTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/content_profiles/ContentProfileErrorReportUtilsTest.java
@@ -18,13 +18,10 @@
import static com.google.common.truth.Truth.assertThat;
import android.os.SystemClock;
-import android.platform.test.flag.junit.SetFlagsRule;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
-import com.android.bluetooth.flags.Flags;
-
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -33,22 +30,8 @@
@RunWith(AndroidJUnit4.class)
public class ContentProfileErrorReportUtilsTest {
- @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
-
- @Test
- public void noOpWhenFlagIsDisabled() {
- mSetFlagsRule.disableFlags(Flags.FLAG_CONTENT_PROFILES_ERRORS_METRICS);
- long previousReportTimeMillis = ContentProfileErrorReportUtils.sLastReportTime;
-
- assertThat(ContentProfileErrorReportUtils.report(0, 0, 0, 0)).isFalse();
- // The last report time should not be changed.
- assertThat(ContentProfileErrorReportUtils.sLastReportTime)
- .isEqualTo(previousReportTimeMillis);
- }
-
@Test
public void tooFrequentErrorReportIsSkipped() {
- mSetFlagsRule.enableFlags(Flags.FLAG_CONTENT_PROFILES_ERRORS_METRICS);
// Set the last report time to the current time.
long lastReportTimeMillisToSet = SystemClock.uptimeMillis();
ContentProfileErrorReportUtils.sLastReportTime = lastReportTimeMillisToSet;
@@ -61,7 +44,6 @@
@Test
public void successfulReport() {
- mSetFlagsRule.enableFlags(Flags.FLAG_CONTENT_PROFILES_ERRORS_METRICS);
// Set the last report time to much earlier than the current time.
long lastReportTimeMillisToSet =
SystemClock.uptimeMillis()
diff --git a/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java
index 10f57c5..7c3bd07 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java
@@ -163,11 +163,12 @@
private void startService() throws TimeoutException {
mService = new CsipSetCoordinatorService(mTargetContext);
- mService.doStart();
+ mService.start();
+ mService.setAvailable(true);
}
private void stopService() throws TimeoutException {
- mService.doStop();
+ mService.stop();
mService = CsipSetCoordinatorService.getCsipSetCoordinatorService();
Assert.assertNull(mService);
}
@@ -405,6 +406,8 @@
// Send a connect request
Assert.assertTrue("Connect expected to succeed", mService.connect(mTestDevice));
+
+ TestUtils.waitForIntent(TIMEOUT_MS, mIntentQueue.get(mTestDevice));
}
/**
@@ -661,6 +664,8 @@
// add state machines for testing dump()
mService.connect(mTestDevice);
+ TestUtils.waitForIntent(TIMEOUT_MS, mIntentQueue.get(mTestDevice));
+
mService.dump(new StringBuilder());
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceTest.java
index 211e35f..edef55c 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceTest.java
@@ -45,10 +45,8 @@
import android.os.Binder;
import android.os.RemoteException;
import android.os.WorkSource;
+import android.platform.test.flag.junit.SetFlagsRule;
-import android.platform.test.annotations.RequiresFlagsEnabled;
-import android.platform.test.flag.junit.CheckFlagsRule;
-import android.platform.test.flag.junit.DeviceFlagsValueProvider;
import androidx.test.InstrumentationRegistry;
import androidx.test.filters.SmallTest;
import androidx.test.rule.ServiceTestRule;
@@ -61,11 +59,12 @@
import com.android.bluetooth.le_scan.PeriodicScanManager;
import com.android.bluetooth.le_scan.ScanClient;
import com.android.bluetooth.le_scan.ScanManager;
+import com.android.bluetooth.le_scan.TransitionalScanHelper;
import com.android.bluetooth.flags.Flags;
+
import org.junit.After;
import org.junit.Assert;
-import org.junit.Assume;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -97,8 +96,8 @@
private Context mTargetContext;
private GattService mService;
@Mock private GattService.ClientMap mClientMap;
- @Mock private GattService.ScannerMap mScannerMap;
- @Mock private GattService.ScannerMap.App mApp;
+ @Mock private TransitionalScanHelper.ScannerMap mScannerMap;
+ @Mock private TransitionalScanHelper.ScannerMap.App mApp;
@Mock private GattService.PendingIntentInfo mPiInfo;
@Mock private PeriodicScanManager mPeriodicScanManager;
@Mock private ScanManager mScanManager;
@@ -108,9 +107,7 @@
@Mock private AdvertiseManagerNativeInterface mAdvertiseManagerNativeInterface;
@Rule public final ServiceTestRule mServiceRule = new ServiceTestRule();
-
- @Rule
- public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule();
+ @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
private BluetoothDevice mDevice;
private BluetoothAdapter mAdapter;
@@ -132,7 +129,7 @@
GattObjectsFactory.setInstanceForTesting(mFactory);
doReturn(mNativeInterface).when(mFactory).getNativeInterface();
- doReturn(mScanManager).when(mFactory).createScanManager(any(), any(), any(), any(), any());
+ doReturn(mScanManager).when(mFactory).createScanManager(any(), any(), any(), any());
doReturn(mPeriodicScanManager).when(mFactory).createPeriodicScanManager(any());
doReturn(mDistanceMeasurementManager).when(mFactory)
.createDistanceMeasurementManager(any());
@@ -158,7 +155,7 @@
mService.start();
mService.mClientMap = mClientMap;
- mService.mScannerMap = mScannerMap;
+ mService.mTransitionalScanHelper.setScannerMap(mScannerMap);
mService.mReliableQueue = mReliableQueue;
mService.mServerMap = mServerMap;
}
@@ -246,7 +243,7 @@
mService.connectionParameterUpdate(clientIf, address, connectionPriority,
mAttributionSource);
- connectionPriority = BluetoothGatt.CONNECTION_PRIORITY_BALANCED;;
+ connectionPriority = BluetoothGatt.CONNECTION_PRIORITY_BALANCED;
mService.connectionParameterUpdate(clientIf, address, connectionPriority,
mAttributionSource);
@@ -500,10 +497,9 @@
verify(mScanManager).flushBatchScanResults(new ScanClient(scannerId));
}
- @RequiresFlagsEnabled(Flags.FLAG_LE_SCAN_FIX_REMOTE_EXCEPTION)
@Test
public void onScanResult_remoteException_clientDied() throws Exception {
- Assume.assumeTrue(Flags.leScanFixRemoteException());
+ mSetFlagsRule.enableFlags(Flags.FLAG_LE_SCAN_FIX_REMOTE_EXCEPTION);
int scannerId = 1;
int eventType = 0;
@@ -891,9 +887,9 @@
BluetoothProfile.STATE_CONNECTED);
}
- @RequiresFlagsEnabled(Flags.FLAG_GATT_CLEANUP_RESTRICTED_HANDLES)
@Test
public void restrictedHandles() throws Exception {
+ mSetFlagsRule.enableFlags(Flags.FLAG_GATT_CLEANUP_RESTRICTED_HANDLES);
int clientIf = 1;
int connId = 1;
ArrayList<GattDbElement> db = new ArrayList<>();
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientTest.java b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientTest.java
index 70a11c8..8fc9fbe 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientTest.java
@@ -52,9 +52,7 @@
import android.bluetooth.BluetoothUuid;
import android.bluetooth.IBluetoothHapClientCallback;
import android.content.AttributionSource;
-import android.content.Context;
import android.os.Binder;
-import android.os.Looper;
import android.os.ParcelUuid;
import android.os.RemoteException;
@@ -104,7 +102,6 @@
private HapClientService.BluetoothHapClientBinder mServiceBinder;
private AttributionSource mAttributionSource;
- @Mock private Context mContext;
@Mock private AdapterService mAdapterService;
@Mock private DatabaseManager mDatabaseManager;
@Mock private HapClientNativeInterface mNativeInterface;
@@ -122,13 +119,8 @@
// Set up mocks and test assets
MockitoAnnotations.initMocks(this);
- if (Looper.myLooper() == null) {
- Looper.prepare();
- }
-
HapClientStateMachine.sConnectTimeoutMs = TIMEOUT_MS;
- TestUtils.setAdapterService(mAdapterService);
doReturn(mDatabaseManager).when(mAdapterService).getDatabase();
mAdapter = BluetoothAdapter.getDefaultAdapter();
@@ -211,19 +203,16 @@
HapClientNativeInterface.setInstance(null);
mAdapter = null;
-
- if (mAdapterService != null) {
- TestUtils.clearAdapterService(mAdapterService);
- }
}
private void startService() throws TimeoutException {
- mService = new HapClientService(mContext);
- mService.doStart();
+ mService = new HapClientService(mAdapterService);
+ mService.start();
+ mService.setAvailable(true);
}
private void stopService() throws TimeoutException {
- mService.doStop();
+ mService.stop();
mService = HapClientService.getHapClientService();
Assert.assertNull(mService);
}
@@ -370,7 +359,7 @@
// Send a connect request
Assert.assertTrue("Connect expected to succeed", mService.connect(mDevice));
- verify(mContext, timeout(TIMEOUT_MS)).sendBroadcast(any(), any());
+ verify(mAdapterService, timeout(TIMEOUT_MS)).sendBroadcast(any(), any());
}
/**
@@ -395,7 +384,7 @@
*/
@Test
public void testOutgoingConnectTimeout() throws Exception {
- InOrder order = inOrder(mContext);
+ InOrder order = inOrder(mAdapterService);
// Update the device policy so okToConnect() returns true
when(mDatabaseManager
@@ -407,7 +396,7 @@
// Send a connect request
Assert.assertTrue("Connect failed", mService.connect(mDevice));
- order.verify(mContext, timeout(TIMEOUT_MS))
+ order.verify(mAdapterService, timeout(TIMEOUT_MS))
.sendBroadcast(
argThat(
allOf(
@@ -421,7 +410,7 @@
mService.getConnectionState(mDevice));
// Verify the connection state broadcast, and that we are in Disconnected state via binder
- order.verify(mContext, timeout(HapClientStateMachine.sConnectTimeoutMs * 2))
+ order.verify(mAdapterService, timeout(HapClientStateMachine.sConnectTimeoutMs * 2))
.sendBroadcast(
argThat(
allOf(
@@ -444,7 +433,7 @@
*/
@Test
public void testConnectTwo() throws Exception {
- InOrder order = inOrder(mContext);
+ InOrder order = inOrder(mAdapterService);
doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService)
.getRemoteUuids(any(BluetoothDevice.class));
@@ -480,7 +469,7 @@
*/
@Test
public void testGetHapGroupCoordinatedOps() throws Exception {
- InOrder order = inOrder(mContext);
+ InOrder order = inOrder(mAdapterService);
doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService)
.getRemoteUuids(any(BluetoothDevice.class));
testConnectingDevice(order, mDevice);
@@ -518,7 +507,7 @@
*/
@Test
public void testSelectPresetNative() {
- InOrder order = inOrder(mContext);
+ InOrder order = inOrder(mAdapterService);
doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService)
.getRemoteUuids(any(BluetoothDevice.class));
testConnectingDevice(order, mDevice);
@@ -544,7 +533,7 @@
*/
@Test
public void testGroupSelectActivePresetNative() {
- InOrder order = inOrder(mContext);
+ InOrder order = inOrder(mAdapterService);
doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService)
.getRemoteUuids(any(BluetoothDevice.class));
testConnectingDevice(order, mDevice3);
@@ -571,7 +560,7 @@
*/
@Test
public void testSwitchToNextPreset() {
- InOrder order = inOrder(mContext);
+ InOrder order = inOrder(mAdapterService);
doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService)
.getRemoteUuids(any(BluetoothDevice.class));
testConnectingDevice(order, mDevice);
@@ -587,7 +576,7 @@
*/
@Test
public void testSwitchToNextPresetForGroup() {
- InOrder order = inOrder(mContext);
+ InOrder order = inOrder(mAdapterService);
doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService)
.getRemoteUuids(any(BluetoothDevice.class));
testConnectingDevice(order, mDevice3);
@@ -604,7 +593,7 @@
*/
@Test
public void testSwitchToPreviousPreset() {
- InOrder order = inOrder(mContext);
+ InOrder order = inOrder(mAdapterService);
doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService)
.getRemoteUuids(any(BluetoothDevice.class));
testConnectingDevice(order, mDevice);
@@ -620,7 +609,7 @@
*/
@Test
public void testSwitchToPreviousPresetForGroup() {
- InOrder order = inOrder(mContext);
+ InOrder order = inOrder(mAdapterService);
doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService)
.getRemoteUuids(any(BluetoothDevice.class));
testConnectingDevice(order, mDevice);
@@ -639,7 +628,7 @@
*/
@Test
public void testGetActivePresetIndex() throws Exception {
- InOrder order = inOrder(mContext);
+ InOrder order = inOrder(mAdapterService);
doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService)
.getRemoteUuids(any(BluetoothDevice.class));
testConnectingDevice(order, mDevice);
@@ -659,7 +648,7 @@
*/
@Test
public void testGetPresetInfoAndActivePresetInfo() throws Exception {
- InOrder order = inOrder(mContext);
+ InOrder order = inOrder(mAdapterService);
doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService)
.getRemoteUuids(any(BluetoothDevice.class));
testConnectingDevice(order, mDevice2);
@@ -702,7 +691,7 @@
*/
@Test
public void testSetPresetNameNative() {
- InOrder order = inOrder(mContext);
+ InOrder order = inOrder(mAdapterService);
doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService)
.getRemoteUuids(any(BluetoothDevice.class));
testConnectingDevice(order, mDevice);
@@ -728,7 +717,7 @@
*/
@Test
public void testSetPresetNameForGroup() {
- InOrder order = inOrder(mContext);
+ InOrder order = inOrder(mAdapterService);
doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService)
.getRemoteUuids(any(BluetoothDevice.class));
int test_group = 0x02;
@@ -775,7 +764,7 @@
.onDeviceAvailable(any(byte[].class), anyInt());
mNativeInterface.onDeviceAvailable(getByteAddress(mDevice), 0x03);
- verify(mContext, timeout(TIMEOUT_MS))
+ verify(mAdapterService, timeout(TIMEOUT_MS))
.sendBroadcast(
argThat(
allOf(
@@ -837,7 +826,7 @@
*/
@Test
public void testStackEventOnPresetInfo() {
- InOrder order = inOrder(mContext);
+ InOrder order = inOrder(mAdapterService);
doReturn(new ParcelUuid[]{BluetoothUuid.HAS}).when(mAdapterService)
.getRemoteUuids(any(BluetoothDevice.class));
@@ -1068,7 +1057,7 @@
// Add state machine for testing dump()
mService.connect(mDevice);
- verify(mContext, timeout(TIMEOUT_MS)).sendBroadcast(any(), any());
+ verify(mAdapterService, timeout(TIMEOUT_MS)).sendBroadcast(any(), any());
mService.dump(new StringBuilder());
}
@@ -1097,7 +1086,7 @@
/** Helper function to test device connecting */
private void verifyConnectingDevice(InOrder order, BluetoothDevice device) {
// Verify the connection state broadcast, and that we are in Connecting state
- order.verify(mContext, timeout(TIMEOUT_MS))
+ order.verify(mAdapterService, timeout(TIMEOUT_MS))
.sendBroadcast(
argThat(
allOf(
@@ -1116,7 +1105,7 @@
mService.messageFromNative(evt);
// Verify the connection state broadcast, and that we are in Connected state
- order.verify(mContext, timeout(TIMEOUT_MS))
+ order.verify(mAdapterService, timeout(TIMEOUT_MS))
.sendBroadcast(
argThat(
allOf(
@@ -1132,7 +1121,7 @@
evt.valueInt1 = 0x01; // features
mService.messageFromNative(evt);
- order.verify(mContext, timeout(TIMEOUT_MS))
+ order.verify(mAdapterService, timeout(TIMEOUT_MS))
.sendBroadcast(
argThat(
allOf(
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidServiceTest.java
index 4eaf759..f690d65 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidServiceTest.java
@@ -42,6 +42,7 @@
import android.media.BluetoothProfileConnectionInfo;
import android.os.Looper;
import android.os.ParcelUuid;
+import android.platform.test.flag.junit.SetFlagsRule;
import androidx.test.filters.MediumTest;
import androidx.test.platform.app.InstrumentationRegistry;
@@ -52,7 +53,6 @@
import com.android.bluetooth.btservice.AdapterService;
import com.android.bluetooth.btservice.AudioRoutingManager;
import com.android.bluetooth.btservice.storage.DatabaseManager;
-import com.android.bluetooth.flags.FakeFeatureFlagsImpl;
import com.android.bluetooth.flags.Flags;
import com.android.bluetooth.x.com.android.modules.utils.SynchronousResultReceiver;
@@ -60,6 +60,7 @@
import org.hamcrest.core.AllOf;
import org.junit.After;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
@@ -84,12 +85,12 @@
private static final BluetoothDevice mRightDevice = TestUtils.getTestDevice(mAdapter, 1);
private static final BluetoothDevice mSingleDevice = TestUtils.getTestDevice(mAdapter, 2);
+ @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
+
private HearingAidService mService;
private HearingAidService.BluetoothHearingAidBinder mServiceBinder;
private HashMap<BluetoothDevice, LinkedBlockingQueue<Intent>> mDeviceQueueMap;
- private FakeFeatureFlagsImpl mFakeFlagsImpl;
-
@Mock private AdapterService mAdapterService;
@Mock private ActiveDeviceManager mActiveDeviceManager;
@Mock private AudioRoutingManager mAudioRoutingManager;
@@ -112,13 +113,11 @@
if (Looper.myLooper() == null) {
Looper.prepare();
}
- mFakeFlagsImpl = new FakeFeatureFlagsImpl();
- mFakeFlagsImpl.setFlag(Flags.FLAG_AUDIO_ROUTING_CENTRALIZATION, false);
TestUtils.setAdapterService(mAdapterService);
doAnswer(
invocation -> {
- if (mFakeFlagsImpl.audioRoutingCentralization()) {
+ if (Flags.audioRoutingCentralization()) {
return mAudioRoutingManager;
} else {
return mActiveDeviceManager;
@@ -153,11 +152,12 @@
private void startService() throws TimeoutException {
mService = new HearingAidService(mContext);
- mService.doStart();
+ mService.start();
+ mService.setAvailable(true);
}
private void stopService() throws TimeoutException {
- mService.doStop();
+ mService.stop();
mService = HearingAidService.getHearingAidService();
assertThat(mService).isNull();
}
@@ -968,14 +968,13 @@
assertThat(mService.getActiveDevices()).containsNoneOf(mRightDevice, mLeftDevice);
assertThat(mService.getActiveDevices()).contains(mSingleDevice);
- mService.setFeatureFlags(mFakeFlagsImpl);
SynchronousResultReceiver<Boolean> recv = SynchronousResultReceiver.get();
boolean defaultRecvValue = false;
mServiceBinder.setActiveDevice(null, null, recv);
assertThat(recv.awaitResultNoInterrupt(TIMEOUT).getValue(defaultRecvValue)).isTrue();
assertThat(mService.getActiveDevices()).doesNotContain(mSingleDevice);
- mFakeFlagsImpl.setFlag(Flags.FLAG_AUDIO_ROUTING_CENTRALIZATION, true);
+ mSetFlagsRule.enableFlags(Flags.FLAG_AUDIO_ROUTING_CENTRALIZATION);
recv = SynchronousResultReceiver.get();
mServiceBinder.setActiveDevice(null, null, recv);
verify(mAudioRoutingManager)
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceAndStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceAndStateMachineTest.java
index 3eaa5cf..86d5bac 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceAndStateMachineTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceAndStateMachineTest.java
@@ -220,7 +220,8 @@
mOriginalVrTimeoutMs = HeadsetService.sStartVrTimeoutMs;
HeadsetService.sStartVrTimeoutMs = START_VR_TIMEOUT_MILLIS;
mHeadsetService = new HeadsetService(mTargetContext);
- mHeadsetService.doStart();
+ mHeadsetService.start();
+ mHeadsetService.setAvailable(true);
mIsHeadsetServiceStarted = true;
Assert.assertNotNull(mHeadsetService);
verify(mObjectsFactory).makeSystemInterface(mHeadsetService);
@@ -247,7 +248,7 @@
if (mIsHeadsetServiceStarted) {
mTargetContext.unregisterReceiver(mHeadsetIntentReceiver);
- mHeadsetService.doStop();
+ mHeadsetService.stop();
mHeadsetService = HeadsetService.getHeadsetService();
Assert.assertNull(mHeadsetService);
// Clear classes that is spied on and has static life time
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceTest.java
index fd4d22f..2aa1e1f 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceTest.java
@@ -19,7 +19,6 @@
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyInt;
-import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
@@ -159,7 +158,8 @@
doReturn(mNativeInterface).when(mObjectsFactory).getNativeInterface();
HeadsetNativeInterface.setInstance(mNativeInterface);
mHeadsetService = new HeadsetService(mTargetContext);
- mHeadsetService.doStart();
+ mHeadsetService.start();
+ mHeadsetService.setAvailable(true);
verify(mObjectsFactory).makeSystemInterface(mHeadsetService);
verify(mObjectsFactory).getNativeInterface();
mHeadsetService.setForceScoAudio(true);
@@ -167,7 +167,7 @@
@After
public void tearDown() throws Exception {
- mHeadsetService.doStop();
+ mHeadsetService.stop();
HeadsetNativeInterface.setInstance(null);
mHeadsetService = HeadsetService.getHeadsetService();
Assert.assertNull(mHeadsetService);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStateMachineTest.java
index 9dbd289..a8acf74 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStateMachineTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStateMachineTest.java
@@ -39,7 +39,7 @@
import android.os.HandlerThread;
import android.os.SystemProperties;
import android.os.UserHandle;
-import android.platform.test.annotations.RequiresFlagsEnabled;
+import android.platform.test.flag.junit.SetFlagsRule;
import android.provider.CallLog;
import android.provider.CallLog.Calls;
import android.telephony.PhoneNumberUtils;
@@ -65,6 +65,7 @@
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
+import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
@@ -85,6 +86,9 @@
private static final int ASYNC_CALL_TIMEOUT_MILLIS = 250;
private static final String TEST_PHONE_NUMBER = "1234567890";
private static final int MAX_RETRY_DISCONNECT_AUDIO = 3;
+
+ @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
+
private Context mTargetContext;
private BluetoothAdapter mAdapter;
private HandlerThread mHandlerThread;
@@ -1017,8 +1021,8 @@
/** A test to verify that we correctly send CIND response when a call is in progress */
@Test
- @RequiresFlagsEnabled(Flags.FLAG_PRETEND_NETWORK_SERVICE)
public void testCindEventWhenCallIsInProgress() {
+ mSetFlagsRule.enableFlags(Flags.FLAG_PRETEND_NETWORK_SERVICE);
when(mPhoneState.getCindService())
.thenReturn(HeadsetHalConstants.NETWORK_STATE_NOT_AVAILABLE);
when(mHeadsetService.isVirtualCallStarted()).thenReturn(false);
@@ -1657,8 +1661,8 @@
/** Test setting audio parameters according to received SWB event. SWB AptX is enabled. */
@Test
- @RequiresFlagsEnabled(Flags.FLAG_HFP_CODEC_APTX_VOICE)
public void testSetAudioParameters_SwbAptxEnabled() {
+ mSetFlagsRule.enableFlags(Flags.FLAG_HFP_CODEC_APTX_VOICE);
assumeTrue(SystemProperties.getBoolean("bluetooth.hfp.codec_aptx_voice.enabled", false));
setUpConnectedState();
mHeadsetStateMachine.sendMessage(
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceTest.java
index 92923b6..a6288f6 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceTest.java
@@ -20,7 +20,6 @@
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyInt;
-import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.never;
@@ -176,11 +175,11 @@
doReturn(packageManager).when(context).getPackageManager();
HeadsetClientService service = new HeadsetClientService(context);
- service.doStart();
+ service.start();
verify(context).startService(any(Intent.class));
- service.doStop();
+ service.stop();
}
@Test
@@ -192,17 +191,18 @@
doReturn(packageManager).when(context).getPackageManager();
HeadsetClientService service = new HeadsetClientService(context);
- service.doStart();
+ service.start();
verify(context, never()).startService(any(Intent.class));
- service.doStop();
+ service.stop();
}
private void startService() throws Exception {
// At this point the service should have started so check NOT null
mService = new HeadsetClientService(mTargetContext);
- mService.doStart();
+ mService.start();
+ mService.setAvailable(true);
// Try getting the Bluetooth adapter
mAdapter = BluetoothAdapter.getDefaultAdapter();
Assert.assertNotNull(mAdapter);
@@ -211,7 +211,7 @@
private void stopServiceIfStarted() throws Exception {
if (mIsHeadsetClientServiceStarted) {
- mService.doStop();
+ mService.stop();
mService = HeadsetClientService.getHeadsetClientService();
Assert.assertNull(mService);
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hid/HidDeviceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hid/HidDeviceTest.java
index fe59fd6..db4a62e 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hid/HidDeviceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hid/HidDeviceTest.java
@@ -111,7 +111,8 @@
mTestDevice = mAdapter.getRemoteDevice("10:11:12:13:14:15");
mHidDeviceService = new HidDeviceService(mTargetContext);
- mHidDeviceService.doStart();
+ mHidDeviceService.start();
+ mHidDeviceService.setAvailable(true);
// Force unregister app first
mHidDeviceService.unregisterApp();
@@ -137,7 +138,7 @@
@After
public void tearDown() throws Exception {
- mHidDeviceService.doStop();
+ mHidDeviceService.stop();
mHidDeviceService = HidDeviceService.getHidDeviceService();
Assert.assertNull(mHidDeviceService);
mTargetContext.unregisterReceiver(mConnectionStateChangedReceiver);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceBinderTest.java
index f90f867..8bedfb3 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceBinderTest.java
@@ -17,17 +17,16 @@
package com.android.bluetooth.hid;
import static org.mockito.Mockito.verify;
-
+import android.platform.test.flag.junit.SetFlagsRule;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
-
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
-
+import com.android.bluetooth.flags.Flags;
import com.android.bluetooth.x.com.android.modules.utils.SynchronousResultReceiver;
-
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
@@ -36,7 +35,7 @@
@SmallTest
@RunWith(AndroidJUnit4.class)
public class HidHostServiceBinderTest {
-
+ @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
private static final String REMOTE_DEVICE_ADDRESS = "00:00:00:00:00:00";
@Mock
@@ -107,6 +106,24 @@
}
@Test
+ public void setPreferredTransport_callsServiceMethod() {
+ mSetFlagsRule.enableFlags(Flags.FLAG_ALLOW_SWITCHING_HID_AND_HOGP);
+ int preferredTransport = BluetoothDevice.TRANSPORT_AUTO;
+ mBinder.setPreferredTransport(
+ mRemoteDevice, preferredTransport, null, SynchronousResultReceiver.get());
+
+ verify(mService).setPreferredTransport(mRemoteDevice, preferredTransport);
+ }
+
+ @Test
+ public void getPreferredTransport_callsServiceMethod() {
+ mSetFlagsRule.enableFlags(Flags.FLAG_ALLOW_SWITCHING_HID_AND_HOGP);
+ mBinder.getPreferredTransport(mRemoteDevice, null, SynchronousResultReceiver.get());
+
+ verify(mService).getPreferredTransport(mRemoteDevice);
+ }
+
+ @Test
public void getProtocolMode_callsServiceMethod() {
mBinder.getProtocolMode(mRemoteDevice, null,
SynchronousResultReceiver.get());
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceTest.java
index d92f70d..41652ab 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceTest.java
@@ -58,7 +58,8 @@
when(mAdapterService.getDatabase()).thenReturn(mDatabaseManager);
HidHostNativeInterface.setInstance(mNativeInterface);
mService = new HidHostService(mTargetContext);
- mService.doStart();
+ mService.start();
+ mService.setAvailable(true);
// Try getting the Bluetooth adapter
mAdapter = BluetoothAdapter.getDefaultAdapter();
Assert.assertNotNull(mAdapter);
@@ -69,7 +70,8 @@
@After
public void tearDown() throws Exception {
- mService.doStop();
+ mService.stop();
+ mService.cleanup();
HidHostNativeInterface.setInstance(null);
mService = HidHostService.getHidHostService();
Assert.assertNull(mService);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBinderTest.java
index 660d1c5..4c6d909 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBinderTest.java
@@ -90,7 +90,7 @@
InstrumentationRegistry.getTargetContext(),
mNativeInterface,
mFakeFlagsImpl));
- mLeAudioService.doStart();
+ mLeAudioService.start();
mAdapter = BluetoothAdapter.getDefaultAdapter();
mBinder = new LeAudioService.BluetoothLeAudioBinder(mLeAudioService);
mLeAudioService.mLeAudioCallbacks = mLeAudioCallbacks;
@@ -100,7 +100,7 @@
@After
public void cleanUp() {
mBinder.cleanup();
- mLeAudioService.doStop();
+ mLeAudioService.stop();
TestUtils.clearAdapterService(mAdapterService);
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcastServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcastServiceTest.java
index 3568a93..33894b8 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcastServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcastServiceTest.java
@@ -226,11 +226,12 @@
private void startService() throws TimeoutException {
mService = new LeAudioService(mTargetContext);
- mService.doStart();
+ mService.start();
+ mService.setAvailable(true);
}
private void stopService() throws TimeoutException {
- mService.doStop();
+ mService.stop();
mService = LeAudioService.getLeAudioService();
Assert.assertNull(mService);
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioServiceTest.java
index 70bd423..46c35d3 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
@@ -109,6 +109,7 @@
private LinkedBlockingQueue<Intent> mGroupIntentQueue = new LinkedBlockingQueue<>();
private int testGroupId = 1;
private boolean onGroupStatusCallbackCalled = false;
+ private boolean onGroupStreamStatusCallbackCalled = false;
private boolean onGroupCodecConfChangedCallbackCalled = false;
private BluetoothLeAudioCodecStatus testCodecStatus = null;
private FakeFeatureFlagsImpl mFakeFlagsImpl;
@@ -275,13 +276,14 @@
// LeAudioService#init and expect it to be run after start
// has finished.
// To ensure that we run start on the main looper as well.
- FutureTask task = new FutureTask(mService::doStart, null);
+ mService.setAvailable(true);
+ FutureTask task = new FutureTask(mService::start, null);
new Handler(Looper.getMainLooper()).post(task);
task.get();
}
private void stopService() throws TimeoutException {
- mService.doStop();
+ mService.stop();
mService = LeAudioService.getLeAudioService();
assertThat(mService).isNull();
}
@@ -838,7 +840,7 @@
.when(mAdapterService)
.getBondState(any(BluetoothDevice.class));
mService.bondStateChanged(mLeftDevice, BluetoothDevice.BOND_NONE);
- assertThat(mService.getDevices().contains(mLeftDevice)).isTrue();
+
verifyConnectionStateIntent(
TIMEOUT_MS,
mLeftDevice,
@@ -850,6 +852,8 @@
reset(mTbsService);
reset(mMcpService);
+ assertThat(mService.getDevices().contains(mLeftDevice)).isFalse();
+
// Unbond received in CONNECTION_STATE_CONNECTED
// Create device descriptor with connect request. To connect service,
// device needs to be bonded
@@ -919,8 +923,8 @@
assertThat(mService.getConnectionState(mLeftDevice))
.isEqualTo(BluetoothProfile.STATE_CONNECTED);
- assertThat(mService.getDevices().contains(mLeftDevice)).isTrue();
injectAndVerifyDeviceDisconnected(mLeftDevice);
+ assertThat(mService.getDevices().contains(mLeftDevice)).isTrue();
verify(mTbsService, times(0)).removeDeviceAuthorizationInfo(mLeftDevice);
verify(mMcpService, times(0)).removeDeviceAuthorizationInfo(mLeftDevice);
@@ -929,9 +933,6 @@
reset(mMcpService);
// Device unbond
- doReturn(BluetoothDevice.BOND_NONE)
- .when(mAdapterService)
- .getBondState(any(BluetoothDevice.class));
mService.bondStateChanged(mLeftDevice, BluetoothDevice.BOND_NONE);
verify(mTbsService, times(1)).removeDeviceAuthorizationInfo(mLeftDevice);
@@ -1615,6 +1616,14 @@
mService.messageFromNative(groupStatusChangedEvent);
}
+ private void injectGroupStreamStatusChange(int groupId, int groupStreamStatus) {
+ int eventType = LeAudioStackEvent.EVENT_TYPE_GROUP_STREAM_STATUS_CHANGED;
+ LeAudioStackEvent groupStreamStatusChangedEvent = new LeAudioStackEvent(eventType);
+ groupStreamStatusChangedEvent.valueInt1 = groupId;
+ groupStreamStatusChangedEvent.valueInt2 = groupStreamStatus;
+ mService.messageFromNative(groupStreamStatusChangedEvent);
+ }
+
private void injectAudioConfChanged(int groupId, Integer availableContexts, int direction) {
int snkAudioLocation = 3;
int srcAudioLocation = 4;
@@ -1761,20 +1770,26 @@
onGroupStatusCallbackCalled = false;
IBluetoothLeAudioCallback leAudioCallbacks =
- new IBluetoothLeAudioCallback.Stub() {
- @Override
- public void onCodecConfigChanged(int gid, BluetoothLeAudioCodecStatus status) {}
- @Override
- public void onGroupStatusChanged(int gid, int gStatus) {
- onGroupStatusCallbackCalled = true;
- assertThat(gid == groupId).isTrue();
- assertThat(gStatus == groupStatus).isTrue();
- }
- @Override
- public void onGroupNodeAdded(BluetoothDevice device, int gid) {}
- @Override
- public void onGroupNodeRemoved(BluetoothDevice device, int gid) {}
- };
+ new IBluetoothLeAudioCallback.Stub() {
+ @Override
+ public void onCodecConfigChanged(int gid, BluetoothLeAudioCodecStatus status) {}
+
+ @Override
+ public void onGroupStatusChanged(int gid, int gStatus) {
+ onGroupStatusCallbackCalled = true;
+ assertThat(gid == groupId).isTrue();
+ assertThat(gStatus == groupStatus).isTrue();
+ }
+
+ @Override
+ public void onGroupNodeAdded(BluetoothDevice device, int gid) {}
+
+ @Override
+ public void onGroupNodeRemoved(BluetoothDevice device, int gid) {}
+
+ @Override
+ public void onGroupStreamStatusChanged(int groupId, int groupStreamStatus) {}
+ };
mService.mLeAudioCallbacks.register(leAudioCallbacks);
@@ -1802,6 +1817,60 @@
sendEventAndVerifyIntentForGroupStatusChanged(testGroupId, LeAudioStackEvent.GROUP_STATUS_INACTIVE);
}
+ private void sendEventAndVerifyGroupStreamStatusChanged(int groupId, int groupStreamStatus) {
+
+ onGroupStreamStatusCallbackCalled = 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 gid, int gStreamStatus) {
+ onGroupStreamStatusCallbackCalled = true;
+ assertThat(gid == groupId).isTrue();
+ assertThat(gStreamStatus == groupStreamStatus).isTrue();
+ }
+ };
+
+ mService.mLeAudioCallbacks.register(leAudioCallbacks);
+
+ injectGroupStreamStatusChange(groupId, groupStreamStatus);
+
+ TestUtils.waitForLooperToFinishScheduledTask(mService.getMainLooper());
+ assertThat(onGroupStreamStatusCallbackCalled).isTrue();
+
+ onGroupStreamStatusCallbackCalled = false;
+ mService.mLeAudioCallbacks.unregister(leAudioCallbacks);
+ }
+
+ /** Test native interface group stream status message handling */
+ @Test
+ public void testMessageFromNativeGroupStreamStatusChanged() {
+ doReturn(true).when(mNativeInterface).connectLeAudio(any(BluetoothDevice.class));
+ connectTestDevice(mSingleDevice, testGroupId);
+
+ injectAudioConfChanged(
+ testGroupId,
+ BluetoothLeAudio.CONTEXT_TYPE_MEDIA | BluetoothLeAudio.CONTEXT_TYPE_CONVERSATIONAL,
+ 3);
+
+ sendEventAndVerifyGroupStreamStatusChanged(
+ testGroupId, LeAudioStackEvent.GROUP_STREAM_STATUS_IDLE);
+ sendEventAndVerifyGroupStreamStatusChanged(
+ testGroupId, LeAudioStackEvent.GROUP_STREAM_STATUS_STREAMING);
+ }
+
private void injectLocalCodecConfigCapaChanged(List<BluetoothLeAudioCodecConfig> inputCodecCapa,
List<BluetoothLeAudioCodecConfig> outputCodecCapa) {
int eventType = LeAudioStackEvent.EVENT_TYPE_AUDIO_LOCAL_CODEC_CONFIG_CAPA_CHANGED;
@@ -1859,19 +1928,25 @@
OUTPUT_SELECTABLE_CONFIG);
IBluetoothLeAudioCallback leAudioCallbacks =
- new IBluetoothLeAudioCallback.Stub() {
- @Override
- public void onCodecConfigChanged(int gid, BluetoothLeAudioCodecStatus status) {
- onGroupCodecConfChangedCallbackCalled = true;
- assertThat(status.equals(testCodecStatus)).isTrue();
- }
- @Override
- public void onGroupStatusChanged(int gid, int gStatus) {}
- @Override
- public void onGroupNodeAdded(BluetoothDevice device, int gid) {}
- @Override
- public void onGroupNodeRemoved(BluetoothDevice device, int gid) {}
- };
+ new IBluetoothLeAudioCallback.Stub() {
+ @Override
+ public void onCodecConfigChanged(int gid, BluetoothLeAudioCodecStatus status) {
+ onGroupCodecConfChangedCallbackCalled = true;
+ assertThat(status.equals(testCodecStatus)).isTrue();
+ }
+
+ @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) {}
+ };
mService.mLeAudioCallbacks.register(leAudioCallbacks);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioStateMachineTest.java
index baee9ab..73365d6 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioStateMachineTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioStateMachineTest.java
@@ -77,6 +77,7 @@
mAdapter = BluetoothAdapter.getDefaultAdapter();
mFakeFlagsImpl = new FakeFeatureFlagsImpl();
mFakeFlagsImpl.setFlag(Flags.FLAG_AUDIO_ROUTING_CENTRALIZATION, false);
+ mFakeFlagsImpl.setFlag(Flags.FLAG_LEAUDIO_BROADCAST_AUDIO_HANDOVER_POLICIES, false);
// Get a device for testing
mTestDevice = mAdapter.getRemoteDevice("00:01:02:03:04:05");
diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java
index 8c021b9..f95b08b 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java
@@ -53,6 +53,7 @@
import android.os.Handler;
import android.os.Message;
import android.os.test.TestLooper;
+import android.platform.test.flag.junit.SetFlagsRule;
import android.provider.Settings;
import android.test.mock.MockContentProvider;
import android.test.mock.MockContentResolver;
@@ -68,12 +69,10 @@
import com.android.bluetooth.btservice.AdapterService;
import com.android.bluetooth.btservice.BluetoothAdapterProxy;
import com.android.bluetooth.btservice.MetricsLogger;
-import com.android.bluetooth.flags.FakeFeatureFlagsImpl;
import com.android.bluetooth.flags.Flags;
import com.android.bluetooth.gatt.GattNativeInterface;
import com.android.bluetooth.gatt.GattObjectsFactory;
import com.android.bluetooth.gatt.GattService;
-import com.android.bluetooth.le_scan.ScanClient;
import com.android.internal.app.IBatteryStats;
import org.junit.After;
@@ -101,7 +100,7 @@
@RunWith(AndroidJUnit4.class)
public class ScanManagerTest {
private static final String TAG = ScanManagerTest.class.getSimpleName();
- private static final int DELAY_ASYNC_MS = 40;
+ private static final int DELAY_ASYNC_MS = 50;
private static final int DELAY_DEFAULT_SCAN_TIMEOUT_MS = 1500000;
private static final int DELAY_SCAN_TIMEOUT_MS = 100;
private static final int DEFAULT_SCAN_REPORT_DELAY_MS = 100;
@@ -122,8 +121,9 @@
final BatteryStatsManager mBatteryStatsManager =
new BatteryStatsManager(mock(IBatteryStats.class));
- private FakeFeatureFlagsImpl mFakeFlagsImpl;
@Rule public final ServiceTestRule mServiceRule = new ServiceTestRule();
+ @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
+
@Mock private AdapterService mAdapterService;
@Mock private GattService mMockGattService;
@Mock private BluetoothAdapterProxy mBluetoothAdapterProxy;
@@ -190,8 +190,6 @@
doReturn(mTargetContext.getUser()).when(mMockGattService).getUser();
doReturn(mTargetContext.getPackageName()).when(mMockGattService).getPackageName();
- mFakeFlagsImpl = new FakeFeatureFlagsImpl();
- mFakeFlagsImpl.setFlag(Flags.FLAG_SCAN_TIMEOUT_RESET, true);
mTestLooper = new TestLooper();
mTestLooper.startAutoDispatch();
mScanManager =
@@ -199,8 +197,7 @@
mMockGattService,
mAdapterService,
mBluetoothAdapterProxy,
- mTestLooper.getLooper(),
- mFakeFlagsImpl);
+ mTestLooper.getLooper());
mHandler = mScanManager.getClientHandler();
assertThat(mHandler).isNotNull();
@@ -648,6 +645,8 @@
@Test
public void testScanTimeoutResetForNewScan() {
+ mSetFlagsRule.enableFlags(Flags.FLAG_SCAN_TIMEOUT_RESET);
+
mTestLooper.stopAutoDispatchAndIgnoreExceptions();
// Set filtered scan flag
final boolean isFiltered = false;
@@ -1365,8 +1364,8 @@
mScanDurationCaptor.capture());
long capturedDuration = mScanDurationCaptor.getValue();
Log.d(TAG, "capturedDuration: " + String.valueOf(capturedDuration));
- assertThat(weightedScanDuration <= capturedDuration
- && capturedDuration <= weightedScanDuration + DELAY_ASYNC_MS).isTrue();
+ assertThat(capturedDuration).isAtLeast(weightedScanDuration);
+ assertThat(capturedDuration).isAtMost(weightedScanDuration + DELAY_ASYNC_MS);
Mockito.clearInvocations(mMetricsLogger);
}
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapMasInstanceTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapMasInstanceTest.java
index 621c991..34105af 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapMasInstanceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapMasInstanceTest.java
@@ -61,14 +61,6 @@
}
@Test
- public void constructor_withNoParameters() {
- BluetoothMapMasInstance instance = new BluetoothMapMasInstance();
-
- assertThat(instance.mTag).isEqualTo(
- "BluetoothMapMasInstance" + (BluetoothMapMasInstance.sInstanceCounter - 1));
- }
-
- @Test
public void toString_returnsInfo() {
BluetoothMapMasInstance instance = new BluetoothMapMasInstance(mMapService, mContext,
mAccountItem, TEST_MAS_ID, TEST_ENABLE_SMS_MMS);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceTest.java
index 8aa4c0c..5989177 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceTest.java
@@ -23,7 +23,6 @@
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyInt;
-import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.spy;
@@ -74,7 +73,8 @@
TestUtils.setAdapterService(mAdapterService);
doReturn(mDatabaseManager).when(mAdapterService).getDatabase();
mService = new BluetoothMapService(targetContext);
- mService.doStart();
+ mService.start();
+ mService.setAvailable(true);
// Try getting the Bluetooth adapter
mAdapter = BluetoothAdapter.getDefaultAdapter();
assertThat(mAdapter).isNotNull();
@@ -83,7 +83,7 @@
@After
public void tearDown() throws Exception {
- mService.doStop();
+ mService.stop();
mService = BluetoothMapService.getBluetoothMapService();
assertThat(mService).isNull();
TestUtils.clearAdapterService(mAdapterService);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapSettingsTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapSettingsTest.java
index ccb8341..f57f1bd 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapSettingsTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapSettingsTest.java
@@ -25,14 +25,21 @@
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
+import static com.google.common.truth.Truth.assertThat;
+
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import androidx.test.core.app.ActivityScenario;
+import androidx.test.filters.FlakyTest;
import androidx.test.filters.LargeTest;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
+import androidx.test.uiautomator.By;
+import androidx.test.uiautomator.UiDevice;
+import androidx.test.uiautomator.UiObject2;
+import androidx.test.uiautomator.Until;
import com.android.bluetooth.R;
import com.android.bluetooth.TestUtils;
@@ -64,15 +71,23 @@
public void tearDown() throws Exception {
TestUtils.tearDownUiTest();
if (mActivityScenario != null) {
- // Workaround for b/159805732. Without this, test hangs for 45 seconds.
- Thread.sleep(1_000);
mActivityScenario.close();
}
enableActivity(false);
}
@Test
+ @FlakyTest
public void initialize() throws Exception {
+ UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
+
+ long timeoutMs = 5_000;
+ String activityLabel = mTargetContext.getString(R.string.bluetooth_map_settings_title);
+ UiObject2 object = device.wait(Until.findObject(By.text(activityLabel)), timeoutMs);
+ assertThat(object).isNotNull();
+
+ object.click();
+
onView(withId(R.id.bluetooth_map_settings_list_view)).check(matches(isDisplayed()));
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceTest.java
index 1fe5d60..0622a7e 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceTest.java
@@ -74,7 +74,8 @@
MnsService mnsServer = null;
mService = new MapClientService(targetContext, mTestLooper.getLooper(), mnsServer);
- mService.doStart();
+ mService.start();
+ mService.setAvailable(true);
// Try getting the Bluetooth adapter
mAdapter = BluetoothAdapter.getDefaultAdapter();
@@ -84,7 +85,8 @@
@After
public void tearDown() throws Exception {
- mService.doStop();
+ mService.stop();
+ mService.cleanup();
mService = MapClientService.getMapClientService();
assertThat(mService).isNull();
TestUtils.clearAdapterService(mAdapterService);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientStateMachineTest.java
index 6305c79..baadbd7 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientStateMachineTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientStateMachineTest.java
@@ -22,21 +22,27 @@
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
+import android.app.Activity;
import android.app.BroadcastOptions;
+import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothMapClient;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.SdpMasRecord;
+import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
+import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
+import android.platform.test.flag.junit.SetFlagsRule;
import android.provider.Telephony.Sms;
+import android.telephony.SmsManager;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.test.mock.MockContentProvider;
@@ -51,6 +57,7 @@
import com.android.bluetooth.TestUtils;
import com.android.bluetooth.btservice.AdapterService;
import com.android.bluetooth.btservice.storage.DatabaseManager;
+import com.android.bluetooth.flags.Flags;
import com.android.obex.HeaderSet;
import com.android.vcard.VCardConstants;
import com.android.vcard.VCardEntry;
@@ -74,17 +81,24 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
@MediumTest
@RunWith(AndroidJUnit4.class)
public class MapClientStateMachineTest {
private static final String TAG = "MapStateMachineTest";
+
+ @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
+
private static final String FOLDER_SENT = "sent";
private static final int ASYNC_CALL_TIMEOUT_MILLIS = 100;
private static final int DISCONNECT_TIMEOUT = 3000;
+ private static final long PENDING_INTENT_TIMEOUT_MS = 3_000;
+
private Bmessage mTestIncomingSmsBmessage;
private Bmessage mTestIncomingMmsBmessage;
private String mTestMessageSmsHandle = "0001";
@@ -95,6 +109,12 @@
private static final boolean MESSAGE_SEEN = true;
private static final boolean MESSAGE_NOT_SEEN = false;
+ private static final String TEST_MESSAGE_HANDLE = "0123456789000032";
+ private static final String TEST_MESSAGE = "Hello World!";
+ private static final String SENT_PATH = "telecom/msg/sent";
+ private static final Uri[] TEST_CONTACTS_ONE_PHONENUM = new Uri[] {Uri.parse("tel://5551234")};
+ private static final String TEST_DATETIME = "19991231T235959";
+
private VCardEntry mOriginator;
@Rule
@@ -143,6 +163,42 @@
MapClientStateMachineTest::getFolderNameFromRequestGetMessagesListing,
"has folder name of");
+ private static final String ACTION_MESSAGE_SENT =
+ "com.android.bluetooth.mapclient.MapClientStateMachineTest.action.MESSAGE_SENT";
+ private static final String ACTION_MESSAGE_DELIVERED =
+ "com.android.bluetooth.mapclient.MapClientStateMachineTest.action.MESSAGE_DELIVERED";
+
+ private SentDeliveryReceiver mSentDeliveryReceiver;
+
+ private static class SentDeliveryReceiver extends BroadcastReceiver {
+ private CountDownLatch mActionReceivedLatch;
+
+ SentDeliveryReceiver() {
+ mActionReceivedLatch = new CountDownLatch(1);
+ }
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ Log.i(TAG, "onReceive: Action=" + intent.getAction());
+ if (ACTION_MESSAGE_SENT.equals(intent.getAction())
+ || ACTION_MESSAGE_DELIVERED.equals(intent.getAction())) {
+ mActionReceivedLatch.countDown();
+ } else {
+ Log.i(TAG, "unhandled action.");
+ }
+ }
+
+ public boolean isActionReceived(long timeout) {
+ boolean result = false;
+ try {
+ result = mActionReceivedLatch.await(timeout, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException e) {
+ Log.e(TAG, "Latch await", e);
+ }
+ return result;
+ }
+ }
+
@Before
public void setUp() throws Exception {
mTargetContext = InstrumentationRegistry.getTargetContext();
@@ -195,6 +251,13 @@
mMockTelephonyManager);
when(mMockTelephonyManager.isSmsCapable()).thenReturn(false);
+ // Set up receiver for 'Sent' and 'Delivered' PendingIntents
+ IntentFilter filter = new IntentFilter();
+ filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
+ filter.addAction(ACTION_MESSAGE_DELIVERED);
+ filter.addAction(ACTION_MESSAGE_SENT);
+ mSentDeliveryReceiver = new SentDeliveryReceiver();
+ mTargetContext.registerReceiver(mSentDeliveryReceiver, filter, Context.RECEIVER_EXPORTED);
}
@After
@@ -206,6 +269,7 @@
if (mIsAdapterServiceSet) {
TestUtils.clearAdapterService(mAdapterService);
}
+ mTargetContext.unregisterReceiver(mSentDeliveryReceiver);
}
/**
@@ -944,6 +1008,194 @@
assertThat(mMceStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTING);
}
+ /**
+ * Preconditions:
+ * - In {@code STATE_CONNECTED}.
+ *
+ * Actions:
+ * - {@link #sendMapMessage} with 'Sent' {@link PendingIntents}.
+ * - {@link #receiveEvent} of type {@link SENDING_SUCCESS}.
+ *
+ * Outcome:
+ * - SENT_STATUS Intent was broadcast with 'Success' result code.
+ */
+ @Test
+ public void testSendMapMessageSentPendingIntent_notifyStatusSuccess() {
+ mSetFlagsRule.enableFlags(Flags.FLAG_HANDLE_DELIVERY_SENDING_FAILURE_EVENTS);
+ testSendMapMessagePendingIntents_base(
+ ACTION_MESSAGE_SENT, EventReport.Type.SENDING_SUCCESS);
+
+ assertThat(mSentDeliveryReceiver.isActionReceived(PENDING_INTENT_TIMEOUT_MS)).isTrue();
+ assertThat(mSentDeliveryReceiver.getResultCode()).isEqualTo(Activity.RESULT_OK);
+ }
+
+ /**
+ * Preconditions:
+ * - In {@code STATE_CONNECTED}.
+ *
+ * Actions:
+ * - {@link #sendMapMessage} with 'Delivery' {@link PendingIntents}.
+ * - {@link #receiveEvent} of type {@link DELIVERY_SUCCESS}.
+ *
+ * Outcome:
+ * - DELIVERY_STATUS Intent was broadcast with 'Success' result code.
+ */
+ @Test
+ public void testSendMapMessageDeliveryPendingIntent_notifyStatusSuccess() {
+ mSetFlagsRule.enableFlags(Flags.FLAG_HANDLE_DELIVERY_SENDING_FAILURE_EVENTS);
+ testSendMapMessagePendingIntents_base(
+ ACTION_MESSAGE_DELIVERED, EventReport.Type.DELIVERY_SUCCESS);
+
+ assertThat(mSentDeliveryReceiver.isActionReceived(PENDING_INTENT_TIMEOUT_MS)).isTrue();
+ assertThat(mSentDeliveryReceiver.getResultCode()).isEqualTo(Activity.RESULT_OK);
+ }
+
+ /**
+ * Preconditions:
+ * - In {@code STATE_CONNECTED}.
+ *
+ * Actions:
+ * - {@link #sendMapMessage} with 'null' {@link PendingIntents}.
+ * - {@link #receiveEvent} of type {@link SENDING_SUCCESS}.
+ * - {@link #receiveEvent} of type {@link DELIVERY_SUCCESS}.
+ *
+ * Outcome:
+ * - No Intent was broadcast.
+ */
+ @Test
+ public void testSendMapMessageNullPendingIntent_noNotifyStatus() {
+ mSetFlagsRule.enableFlags(Flags.FLAG_HANDLE_DELIVERY_SENDING_FAILURE_EVENTS);
+ testSendMapMessagePendingIntents_base(null, EventReport.Type.SENDING_SUCCESS);
+
+ assertThat(mSentDeliveryReceiver.isActionReceived(PENDING_INTENT_TIMEOUT_MS)).isFalse();
+ }
+
+ /**
+ * Preconditions:
+ * - In {@code STATE_CONNECTED}.
+ *
+ * Actions:
+ * - {@link #sendMapMessage} with 'Sent' {@link PendingIntents}.
+ * - {@link #receiveEvent} of type {@link SENDING_FAILURE}.
+ *
+ * Outcome:
+ * - SENT_STATUS Intent was broadcast with 'Failure' result code.
+ */
+ @Test
+ public void testSendMapMessageSentPendingIntent_notifyStatusFailure() {
+ mSetFlagsRule.enableFlags(Flags.FLAG_HANDLE_DELIVERY_SENDING_FAILURE_EVENTS);
+ testSendMapMessagePendingIntents_base(
+ ACTION_MESSAGE_SENT, EventReport.Type.SENDING_FAILURE);
+
+ assertThat(mSentDeliveryReceiver.isActionReceived(PENDING_INTENT_TIMEOUT_MS)).isTrue();
+ assertThat(mSentDeliveryReceiver.getResultCode())
+ .isEqualTo(SmsManager.RESULT_ERROR_GENERIC_FAILURE);
+ }
+
+ /**
+ * Preconditions:
+ * - In {@code STATE_CONNECTED}.
+ *
+ * Actions:
+ * - {@link #sendMapMessage} with 'Delivery' {@link PendingIntents}.
+ * - {@link #receiveEvent} of type {@link DELIVERY_FAILURE}.
+ *
+ * Outcome:
+ * - DELIVERY_STATUS Intent was broadcast with 'Failure' result code.
+ */
+ @Test
+ public void testSendMapMessageDeliveryPendingIntent_notifyStatusFailure() {
+ mSetFlagsRule.enableFlags(Flags.FLAG_HANDLE_DELIVERY_SENDING_FAILURE_EVENTS);
+ testSendMapMessagePendingIntents_base(
+ ACTION_MESSAGE_DELIVERED, EventReport.Type.DELIVERY_FAILURE);
+
+ assertThat(mSentDeliveryReceiver.isActionReceived(PENDING_INTENT_TIMEOUT_MS)).isTrue();
+ assertThat(mSentDeliveryReceiver.getResultCode())
+ .isEqualTo(SmsManager.RESULT_ERROR_GENERIC_FAILURE);
+ }
+
+ /**
+ * @param action corresponding to the {@link PendingIntent} you want to create/register for
+ * when pushing a MAP message, e.g., for 'Sent' or 'Delivery' status.
+ * @param type the EventReport type of the new notification, e.g., 'Sent'/'Delivery'
+ * 'Success'/'Failure'.
+ */
+ private void testSendMapMessagePendingIntents_base(String action, EventReport.Type type) {
+ transitionToConnected();
+
+ PendingIntent pendingIntentSent;
+ PendingIntent pendingIntentDelivered;
+ if (ACTION_MESSAGE_SENT.equals(action)) {
+ pendingIntentSent = createPendingIntent(action);
+ pendingIntentDelivered = null;
+ } else if (ACTION_MESSAGE_DELIVERED.equals(action)) {
+ pendingIntentSent = null;
+ pendingIntentDelivered = createPendingIntent(action);
+ } else {
+ pendingIntentSent = null;
+ pendingIntentDelivered = null;
+ }
+ sendMapMessageWithPendingIntents(
+ pendingIntentSent, pendingIntentDelivered, TEST_MESSAGE_HANDLE);
+
+ receiveSentDeliveryEvent(type, TEST_MESSAGE_HANDLE);
+ }
+
+ private void transitionToConnected() {
+ Message msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_CONNECTED);
+ mMceStateMachine.sendMessage(msg);
+ TestUtils.waitForLooperToFinishScheduledTask(mMceStateMachine.getHandler().getLooper());
+ assertThat(mMceStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_CONNECTED);
+ }
+
+ private PendingIntent createPendingIntent(String action) {
+ return PendingIntent.getBroadcast(
+ mTargetContext, 1, new Intent(action), PendingIntent.FLAG_IMMUTABLE);
+ }
+
+ private void sendMapMessageWithPendingIntents(
+ PendingIntent pendingIntentSent,
+ PendingIntent pendingIntentDelivered,
+ String messageHandle) {
+ mMceStateMachine.sendMapMessage(
+ TEST_CONTACTS_ONE_PHONENUM, TEST_MESSAGE,
+ pendingIntentSent, pendingIntentDelivered);
+ TestUtils.waitForLooperToFinishScheduledTask(mMceStateMachine.getHandler().getLooper());
+
+ // {@link sendMapMessage} leads to a new {@link RequestPushMessage}, which contains
+ // a {@link Bmessage} object that is used as a key to a map to retrieve the corresponding
+ // {@link PendingIntent} that was provided.
+ // Thus, we need to intercept this Bmessage and inject it back in for
+ // MSG_MAS_REQUEST_COMPLETED. We also need to spy/mock it in order to inject our
+ // TEST_MESSAGE_HANDLE (message handles are normally provided by the remote device).
+ // The message handle injected here needs to match the handle of the SENT/DELIVERY
+ // SUCCESS/FAILURE events.
+
+ ArgumentCaptor<RequestPushMessage> requestCaptor =
+ ArgumentCaptor.forClass(RequestPushMessage.class);
+ verify(mMockMasClient, atLeastOnce()).makeRequest(requestCaptor.capture());
+ RequestPushMessage spyRequestPushMessage = spy(requestCaptor.getValue());
+ when(spyRequestPushMessage.getMsgHandle()).thenReturn(messageHandle);
+
+ Message msgSent =
+ Message.obtain(
+ mHandler, MceStateMachine.MSG_MAS_REQUEST_COMPLETED, spyRequestPushMessage);
+
+ mMceStateMachine.sendMessage(msgSent);
+ TestUtils.waitForLooperToFinishScheduledTask(mMceStateMachine.getHandler().getLooper());
+ }
+
+ private void receiveSentDeliveryEvent(EventReport.Type type, String messageHandle) {
+ mMceStateMachine.receiveEvent(
+ createNewEventReport(
+ type.toString(),
+ TEST_DATETIME,
+ messageHandle,
+ SENT_PATH,
+ null,
+ Bmessage.Type.SMS_GSM.toString()));
+ }
+
private void setupSdpRecordReceipt() {
// Perform first part of MAP connection logic.
verify(mMockMapClientService,
diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientTest.java
index aef59c7..ab5f97b 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientTest.java
@@ -71,14 +71,16 @@
mIsMapClientServiceStarted = true;
Looper looper = null;
mService = new MapClientService(mTargetContext, looper, mMockMnsService);
- mService.doStart();
+ mService.start();
+ mService.setAvailable(true);
mAdapter = BluetoothAdapter.getDefaultAdapter();
}
@After
public void tearDown() throws Exception {
if (mIsMapClientServiceStarted) {
- mService.doStop();
+ mService.stop();
+ mService.cleanup();
mService = MapClientService.getMapClientService();
Assert.assertNull(mService);
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/mcp/McpServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/mcp/McpServiceTest.java
index 3d72e0b..5c77c88 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/mcp/McpServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/mcp/McpServiceTest.java
@@ -67,7 +67,8 @@
McpService.setMediaControlProfileForTesting(mMediaControlProfile);
mMcpService = new McpService(mTargetContext);
- mMcpService.doStart();
+ mMcpService.start();
+ mMcpService.setAvailable(true);
}
@After
@@ -76,7 +77,7 @@
return;
}
- mMcpService.doStop();
+ mMcpService.stop();
mMcpService = McpService.getMcpService();
Assert.assertNull(mMcpService);
reset(mMediaControlProfile);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlGattServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlGattServiceTest.java
index de22c6f..6f16c76 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlGattServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlGattServiceTest.java
@@ -28,7 +28,6 @@
import android.bluetooth.BluetoothLeBroadcastMetadata;
import android.content.Context;
import android.os.Looper;
-import android.platform.test.annotations.RequiresFlagsEnabled;
import androidx.test.InstrumentationRegistry;
import androidx.test.filters.MediumTest;
@@ -38,10 +37,12 @@
import com.android.bluetooth.btservice.AdapterService;
import com.android.bluetooth.flags.Flags;
import com.android.bluetooth.le_audio.LeAudioService;
+import android.platform.test.flag.junit.SetFlagsRule;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
@@ -68,6 +69,8 @@
private static final UUID UUID_CCCD = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
public static final int TEST_CCID = 1;
+ @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
+
private MediaControlGattService mMcpService;
@Mock private AdapterService mAdapterService;
@@ -942,8 +945,8 @@
}
@Test
- @RequiresFlagsEnabled(Flags.FLAG_LEAUDIO_BROADCAST_FEATURE_SUPPORT)
public void testMediaControlPointeRequest_OpcodePlayCallLeAudioServiceSetActiveDevice() {
+ mSetFlagsRule.enableFlags(Flags.FLAG_LEAUDIO_BROADCAST_FEATURE_SUPPORT);
BluetoothGattService service = initAllFeaturesGattService();
prepareConnectedDevice();
mMcpService.updateSupportedOpcodesChar(Request.SupportedOpcodes.PLAY, true);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnableActivityTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnableActivityTest.java
index 3a5de2a..7156c70 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnableActivityTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnableActivityTest.java
@@ -61,7 +61,6 @@
mIntent = new Intent();
mIntent.setClass(mTargetContext, BluetoothOppBtEnableActivity.class);
Intents.init();
- BluetoothOppTestUtils.enableOppActivities(true, mTargetContext);
TestUtils.setUpUiTest();
}
@@ -69,7 +68,6 @@
public void tearDown() throws Exception {
TestUtils.tearDownUiTest();
Intents.release();
- BluetoothOppTestUtils.enableOppActivities(false, mTargetContext);
}
@Test
diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnablingActivityTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnablingActivityTest.java
index b2f7588..c4abf9a 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnablingActivityTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnablingActivityTest.java
@@ -80,7 +80,6 @@
mIntent.setClass(mTargetContext, BluetoothOppBtEnablingActivity.class);
mRealTimeoutValue = BluetoothOppBtEnablingActivity.sBtEnablingTimeoutMs;
- BluetoothOppTestUtils.enableOppActivities(true, mTargetContext);
TestUtils.setUpUiTest();
}
@@ -89,7 +88,6 @@
TestUtils.tearDownUiTest();
BluetoothMethodProxy.setInstanceForTesting(null);
BluetoothOppBtEnablingActivity.sBtEnablingTimeoutMs = mRealTimeoutValue;
- BluetoothOppTestUtils.enableOppActivities(false, mTargetContext);
}
@Ignore("b/277594572")
diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppLauncherActivityTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppLauncherActivityTest.java
index 24267f6..58ee1b6 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppLauncherActivityTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppLauncherActivityTest.java
@@ -87,7 +87,6 @@
mIntent = new Intent();
mIntent.setClass(mTargetContext, BluetoothOppLauncherActivity.class);
- BluetoothOppTestUtils.enableOppActivities(true, mTargetContext);
TestUtils.setUpUiTest();
BluetoothOppManager.setInstance(mBluetoothOppManager);
@@ -100,7 +99,6 @@
BluetoothMethodProxy.setInstanceForTesting(null);
BluetoothOppManager.setInstance(null);
Intents.release();
- BluetoothOppTestUtils.enableOppActivities(false, mTargetContext);
}
@Test
diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiverTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiverTest.java
index c01b3ba..faadf25 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiverTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiverTest.java
@@ -42,10 +42,7 @@
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
-import android.platform.test.annotations.RequiresFlagsDisabled;
-import android.platform.test.annotations.RequiresFlagsEnabled;
-import android.platform.test.flag.junit.CheckFlagsRule;
-import android.platform.test.flag.junit.DeviceFlagsValueProvider;
+import android.platform.test.flag.junit.SetFlagsRule;
import androidx.test.core.app.ActivityScenario;
import androidx.test.espresso.intent.Intents;
@@ -73,8 +70,7 @@
@RunWith(AndroidJUnit4.class)
public class BluetoothOppReceiverTest {
- @Rule
- public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule();
+ @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
Context mContext;
@@ -94,8 +90,6 @@
mReceiver = new BluetoothOppReceiver();
Intents.init();
-
- BluetoothOppTestUtils.enableOppActivities(true, mContext);
TestUtils.setUpUiTest();
}
@@ -118,24 +112,41 @@
Intent intent = new Intent();
intent.setAction(BluetoothDevicePicker.ACTION_DEVICE_SELECTED);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
- ActivityScenario<BluetoothOppBtEnableActivity> activityScenario
- = ActivityScenario.launch(BluetoothOppBtEnableActivity.class);
- activityScenario.onActivity(activity -> {
- mReceiver.onReceive(mContext, intent);
- });
- doNothing().when(bluetoothOppManager).startTransfer(eq(device));
- verify(bluetoothOppManager).startTransfer(eq(device));
- BluetoothOppManager.setInstance(null);
+
+ try {
+ BluetoothOppTestUtils.enableActivity(
+ BluetoothOppBtEnableActivity.class, true, mContext);
+ ActivityScenario<BluetoothOppBtEnableActivity> activityScenario =
+ ActivityScenario.launch(BluetoothOppBtEnableActivity.class);
+ activityScenario.onActivity(
+ activity -> {
+ mReceiver.onReceive(mContext, intent);
+ });
+ doNothing().when(bluetoothOppManager).startTransfer(eq(device));
+ verify(bluetoothOppManager).startTransfer(eq(device));
+ BluetoothOppManager.setInstance(null);
+ } finally {
+ BluetoothOppTestUtils.enableActivity(
+ BluetoothOppBtEnableActivity.class, false, mContext);
+ }
}
@Test
- @RequiresFlagsDisabled(Flags.FLAG_OPP_START_ACTIVITY_DIRECTLY_FROM_NOTIFICATION)
public void onReceive_withActionIncomingFileConfirm_startsIncomingFileConfirmActivity() {
- Intent intent = new Intent();
- intent.setAction(Constants.ACTION_INCOMING_FILE_CONFIRM);
- intent.setData(Uri.parse("content:///not/important"));
- mReceiver.onReceive(mContext, intent);
- intended(hasComponent(BluetoothOppIncomingFileConfirmActivity.class.getName()));
+ mSetFlagsRule.disableFlags(Flags.FLAG_OPP_START_ACTIVITY_DIRECTLY_FROM_NOTIFICATION);
+ try {
+ BluetoothOppTestUtils.enableActivity(
+ BluetoothOppIncomingFileConfirmActivity.class, true, mContext);
+
+ Intent intent = new Intent();
+ intent.setAction(Constants.ACTION_INCOMING_FILE_CONFIRM);
+ intent.setData(Uri.parse("content:///not/important"));
+ mReceiver.onReceive(mContext, intent);
+ intended(hasComponent(BluetoothOppIncomingFileConfirmActivity.class.getName()));
+ } finally {
+ BluetoothOppTestUtils.enableActivity(
+ BluetoothOppIncomingFileConfirmActivity.class, false, mContext);
+ }
}
@Test
@@ -163,30 +174,46 @@
}
@Test
- @RequiresFlagsDisabled(Flags.FLAG_OPP_START_ACTIVITY_DIRECTLY_FROM_NOTIFICATION)
public void onReceive_withActionOutboundTransfer_startsTransferHistoryActivity() {
- Intent intent = new Intent();
- intent.setAction(Constants.ACTION_OPEN_OUTBOUND_TRANSFER);
- intent.setData(Uri.parse("content:///not/important"));
- intending(anyIntent()).respondWith(
- new Instrumentation.ActivityResult(Activity.RESULT_OK, new Intent()));
+ mSetFlagsRule.disableFlags(Flags.FLAG_OPP_START_ACTIVITY_DIRECTLY_FROM_NOTIFICATION);
+ try {
+ BluetoothOppTestUtils.enableActivity(BluetoothOppTransferHistory.class, true, mContext);
- mReceiver.onReceive(mContext, intent);
- intended(hasComponent(BluetoothOppTransferHistory.class.getName()));
- intended(hasExtra(Constants.EXTRA_DIRECTION, BluetoothShare.DIRECTION_OUTBOUND));
+ Intent intent = new Intent();
+ intent.setAction(Constants.ACTION_OPEN_OUTBOUND_TRANSFER);
+ intent.setData(Uri.parse("content:///not/important"));
+ intending(anyIntent())
+ .respondWith(
+ new Instrumentation.ActivityResult(Activity.RESULT_OK, new Intent()));
+
+ mReceiver.onReceive(mContext, intent);
+ intended(hasComponent(BluetoothOppTransferHistory.class.getName()));
+ intended(hasExtra(Constants.EXTRA_DIRECTION, BluetoothShare.DIRECTION_OUTBOUND));
+ } finally {
+ BluetoothOppTestUtils.enableActivity(
+ BluetoothOppTransferHistory.class, false, mContext);
+ }
}
@Test
- @RequiresFlagsDisabled(Flags.FLAG_OPP_START_ACTIVITY_DIRECTLY_FROM_NOTIFICATION)
public void onReceive_withActionInboundTransfer_startsTransferHistoryActivity() {
- Intent intent = new Intent();
- intent.setAction(Constants.ACTION_OPEN_INBOUND_TRANSFER);
- intent.setData(Uri.parse("content:///not/important"));
- intending(anyIntent()).respondWith(
- new Instrumentation.ActivityResult(Activity.RESULT_OK, new Intent()));
- mReceiver.onReceive(mContext, intent);
- intended(hasComponent(BluetoothOppTransferHistory.class.getName()));
- intended(hasExtra(Constants.EXTRA_DIRECTION, BluetoothShare.DIRECTION_INBOUND));
+ mSetFlagsRule.disableFlags(Flags.FLAG_OPP_START_ACTIVITY_DIRECTLY_FROM_NOTIFICATION);
+ try {
+ BluetoothOppTestUtils.enableActivity(BluetoothOppTransferHistory.class, true, mContext);
+
+ Intent intent = new Intent();
+ intent.setAction(Constants.ACTION_OPEN_INBOUND_TRANSFER);
+ intent.setData(Uri.parse("content:///not/important"));
+ intending(anyIntent())
+ .respondWith(
+ new Instrumentation.ActivityResult(Activity.RESULT_OK, new Intent()));
+ mReceiver.onReceive(mContext, intent);
+ intended(hasComponent(BluetoothOppTransferHistory.class.getName()));
+ intended(hasExtra(Constants.EXTRA_DIRECTION, BluetoothShare.DIRECTION_INBOUND));
+ } finally {
+ BluetoothOppTestUtils.enableActivity(
+ BluetoothOppTransferHistory.class, false, mContext);
+ }
}
@Test
@@ -216,8 +243,8 @@
}
@Test
- @RequiresFlagsDisabled(Flags.FLAG_OPP_FIX_MULTIPLE_NOTIFICATIONS_ISSUES)
public void onReceive_withActionCompleteHide_makeAllVisibilityHidden() {
+ mSetFlagsRule.disableFlags(Flags.FLAG_OPP_FIX_MULTIPLE_NOTIFICATIONS_ISSUES);
Intent intent = new Intent();
intent.setAction(Constants.ACTION_COMPLETE_HIDE);
mReceiver.onReceive(mContext, intent);
@@ -227,8 +254,8 @@
}
@Test
- @RequiresFlagsEnabled(Flags.FLAG_OPP_FIX_MULTIPLE_NOTIFICATIONS_ISSUES)
public void onReceive_withActionHideCompletedInboundTransfer_makesInboundVisibilityHidden() {
+ mSetFlagsRule.enableFlags(Flags.FLAG_OPP_FIX_MULTIPLE_NOTIFICATIONS_ISSUES);
Intent intent = new Intent();
intent.setAction(Constants.ACTION_HIDE_COMPLETED_INBOUND_TRANSFER);
mReceiver.onReceive(mContext, intent);
@@ -246,8 +273,8 @@
}
@Test
- @RequiresFlagsEnabled(Flags.FLAG_OPP_FIX_MULTIPLE_NOTIFICATIONS_ISSUES)
public void onReceive_withActionHideCompletedOutboundTransfer_makesOutboundVisibilityHidden() {
+ mSetFlagsRule.enableFlags(Flags.FLAG_OPP_FIX_MULTIPLE_NOTIFICATIONS_ISSUES);
Intent intent = new Intent();
intent.setAction(Constants.ACTION_HIDE_COMPLETED_OUTBOUND_TRANSFER);
mReceiver.onReceive(mContext, intent);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppServiceTest.java
index cead686..05b0460 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppServiceTest.java
@@ -80,7 +80,8 @@
TestUtils.setAdapterService(mAdapterService);
mIsAdapterServiceSet = true;
mService = new BluetoothOppService(targetContext);
- mService.doStart();
+ mService.start();
+ mService.setAvailable(true);
mIsBluetoothOppServiceStarted = true;
// Try getting the Bluetooth adapter
@@ -112,7 +113,7 @@
BluetoothMethodProxy.setInstanceForTesting(null);
if (mIsBluetoothOppServiceStarted) {
- mService.doStop();
+ mService.stop();
}
if (mIsAdapterServiceSet) {
TestUtils.clearAdapterService(mAdapterService);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTestUtils.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTestUtils.java
index c8174be..0c23856 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTestUtils.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTestUtils.java
@@ -31,7 +31,6 @@
import org.mockito.internal.util.MockUtil;
-import java.util.Arrays;
import java.util.List;
import java.util.Objects;
@@ -115,35 +114,25 @@
}
/**
- * Enable/Disable all activities in Opp for testing
+ * Enable/Disable an activity for testing
*
+ * @param activityClass the activity class to enable/disable
* @param enable true to enable, false to disable
* @param mTargetContext target context
*/
- public static void enableOppActivities(boolean enable, Context mTargetContext) {
- int enabledState = enable ? COMPONENT_ENABLED_STATE_ENABLED
- : COMPONENT_ENABLED_STATE_DEFAULT;
+ public static void enableActivity(Class activityClass, boolean enable, Context mTargetContext) {
+ int enabledState =
+ enable ? COMPONENT_ENABLED_STATE_ENABLED : COMPONENT_ENABLED_STATE_DEFAULT;
- mTargetContext.getPackageManager().setApplicationEnabledSetting(
- mTargetContext.getPackageName(), enabledState, DONT_KILL_APP);
+ mTargetContext
+ .getPackageManager()
+ .setApplicationEnabledSetting(
+ mTargetContext.getPackageName(), enabledState, DONT_KILL_APP);
- // All activities to be test
- Class[] activities = {
- BluetoothOppTransferActivity.class,
- BluetoothOppBtEnableActivity.class,
- BluetoothOppBtEnablingActivity.class,
- BluetoothOppBtErrorActivity.class,
- BluetoothOppIncomingFileConfirmActivity.class,
- BluetoothOppTransferHistory.class,
- BluetoothOppLauncherActivity.class,
- };
-
- Arrays.stream(activities).forEach(activityClass -> {
- ComponentName activityName = new ComponentName(mTargetContext, activityClass);
- mTargetContext.getPackageManager().setComponentEnabledSetting(
- activityName, enabledState, DONT_KILL_APP);
- });
-
+ ComponentName activityName = new ComponentName(mTargetContext, activityClass);
+ mTargetContext
+ .getPackageManager()
+ .setComponentEnabledSetting(activityName, enabledState, DONT_KILL_APP);
}
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferActivityTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferActivityTest.java
index 0a158a5..40580e6 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferActivityTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferActivityTest.java
@@ -110,7 +110,8 @@
new CursorMockData(BluetoothShare.USER_CONFIRMATION, 11,
BluetoothShare.USER_CONFIRMATION_HANDOVER_CONFIRMED)
));
- BluetoothOppTestUtils.enableOppActivities(true, mTargetContext);
+ BluetoothOppTestUtils.enableActivity(
+ BluetoothOppTransferActivity.class, true, mTargetContext);
TestUtils.setUpUiTest();
}
@@ -119,7 +120,8 @@
TestUtils.tearDownUiTest();
BluetoothMethodProxy.setInstanceForTesting(null);
- BluetoothOppTestUtils.enableOppActivities(false, mTargetContext);
+ BluetoothOppTestUtils.enableActivity(
+ BluetoothOppTransferActivity.class, false, mTargetContext);
}
@Test
diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferHistoryTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferHistoryTest.java
index 5516165..7739c31 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferHistoryTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferHistoryTest.java
@@ -126,7 +126,8 @@
BluetoothShare.USER_CONFIRMATION_HANDOVER_CONFIRMED)
));
- BluetoothOppTestUtils.enableOppActivities(true, mTargetContext);
+ BluetoothOppTestUtils.enableActivity(
+ BluetoothOppTransferHistory.class, true, mTargetContext);
TestUtils.setUpUiTest();
}
@@ -134,7 +135,8 @@
public void tearDown() throws Exception {
TestUtils.tearDownUiTest();
BluetoothMethodProxy.setInstanceForTesting(null);
- BluetoothOppTestUtils.enableOppActivities(false, mTargetContext);
+ BluetoothOppTestUtils.enableActivity(
+ BluetoothOppTransferHistory.class, false, mTargetContext);
}
@Test
diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppUtilityTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppUtilityTest.java
index 377dd3b..c3897b1 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppUtilityTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppUtilityTest.java
@@ -79,7 +79,6 @@
MockitoAnnotations.initMocks(this);
mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
BluetoothMethodProxy.setInstanceForTesting(mCallProxy);
- BluetoothOppTestUtils.enableOppActivities(true, mContext);
TestUtils.setUpUiTest();
}
@@ -87,7 +86,6 @@
public void tearDown() throws Exception {
TestUtils.tearDownUiTest();
- BluetoothOppTestUtils.enableOppActivities(false, mContext);
BluetoothMethodProxy.setInstanceForTesting(null);
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/IncomingFileConfirmActivityTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/IncomingFileConfirmActivityTest.java
index 9b74894..7787241 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/opp/IncomingFileConfirmActivityTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/opp/IncomingFileConfirmActivityTest.java
@@ -135,7 +135,8 @@
BluetoothShare.USER_CONFIRMATION_HANDOVER_CONFIRMED)
));
- BluetoothOppTestUtils.enableOppActivities(true, mTargetContext);
+ BluetoothOppTestUtils.enableActivity(
+ BluetoothOppIncomingFileConfirmActivity.class, true, mTargetContext);
TestUtils.setUpUiTest();
}
@@ -144,7 +145,8 @@
TestUtils.tearDownUiTest();
BluetoothMethodProxy.setInstanceForTesting(null);
- BluetoothOppTestUtils.enableOppActivities(false, mTargetContext);
+ BluetoothOppTestUtils.enableActivity(
+ BluetoothOppIncomingFileConfirmActivity.class, false, mTargetContext);
}
@Test
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceTest.java
index 729875a..e08f520 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceTest.java
@@ -21,7 +21,6 @@
import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
@@ -72,7 +71,8 @@
doReturn(mDatabaseManager).when(mAdapterService).getDatabase();
PanNativeInterface.setInstance(mNativeInterface);
mService = new PanService(targetContext);
- mService.doStart();
+ mService.start();
+ mService.setAvailable(true);
// Try getting the Bluetooth adapter
mAdapter = BluetoothAdapter.getDefaultAdapter();
@@ -83,7 +83,8 @@
@After
public void tearDown() throws Exception {
- mService.doStop();
+ mService.stop();
+ mService.cleanup();
PanNativeInterface.setInstance(null);
mService = PanService.getPanService();
assertThat(mService).isNull();
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceTest.java
index 48db9a7..69dac46 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceTest.java
@@ -19,7 +19,6 @@
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
@@ -82,7 +81,8 @@
mIsAdapterServiceSet = true;
doReturn(mDatabaseManager).when(mAdapterService).getDatabase();
mService = new BluetoothPbapService(targetContext);
- mService.doStart();
+ mService.start();
+ mService.setAvailable(true);
mIsBluetoothPabpServiceStarted = true;
// Try getting the Bluetooth adapter
mAdapter = BluetoothAdapter.getDefaultAdapter();
@@ -98,7 +98,7 @@
return;
}
if (mIsBluetoothPabpServiceStarted) {
- mService.doStop();
+ mService.stop();
mService = BluetoothPbapService.getBluetoothPbapService();
assertThat(mService).isNull();
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandlerTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandlerTest.java
index 832efad..50f96db 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandlerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandlerTest.java
@@ -18,7 +18,6 @@
import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
@@ -82,7 +81,7 @@
TestUtils.setAdapterService(mAdapterService);
doReturn(mDatabaseManager).when(mAdapterService).getDatabase();
mService = new PbapClientService(mTargetContext);
- mService.doStart();
+ mService.start();
mAdapter = BluetoothAdapter.getDefaultAdapter();
@@ -102,7 +101,7 @@
@After
public void tearDown() throws Exception {
- mService.doStop();
+ mService.stop();
mService = PbapClientService.getPbapClientService();
assertThat(mService).isNull();
TestUtils.clearAdapterService(mAdapterService);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientServiceTest.java
index 1fae911..06e63c9 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientServiceTest.java
@@ -19,7 +19,6 @@
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
@@ -79,7 +78,8 @@
mIsAdapterServiceSet = true;
doReturn(mDatabaseManager).when(mAdapterService).getDatabase();
mService = new PbapClientService(mTargetContext);
- mService.doStart();
+ mService.start();
+ mService.setAvailable(true);
mIsPbapClientServiceStarted = true;
// Try getting the Bluetooth adapter
mAdapter = BluetoothAdapter.getDefaultAdapter();
@@ -93,7 +93,7 @@
return;
}
if (mIsPbapClientServiceStarted) {
- mService.doStop();
+ mService.stop();
mService = PbapClientService.getPbapClientService();
Assert.assertNull(mService);
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/sap/SapServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/sap/SapServiceTest.java
index d1f641a..27cb3a9 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/sap/SapServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/sap/SapServiceTest.java
@@ -61,7 +61,8 @@
MockitoAnnotations.initMocks(this);
TestUtils.setAdapterService(mAdapterService);
mService = new SapService(mTargetContext);
- mService.doStart();
+ mService.start();
+ mService.setAvailable(true);
// Try getting the Bluetooth adapter
mAdapter = BluetoothAdapter.getDefaultAdapter();
assertThat(mAdapter).isNotNull();
@@ -70,7 +71,7 @@
@After
public void tearDown() throws Exception {
- mService.doStop();
+ mService.stop();
mService = SapService.getSapService();
assertThat(mService).isNull();
TestUtils.clearAdapterService(mAdapterService);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlServiceTest.java
index 1832cd6..79a327c 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
@@ -126,10 +126,12 @@
mFakeFlagsImpl = new FakeFeatureFlagsImpl();
mFakeFlagsImpl.setFlag(
Flags.FLAG_LEAUDIO_BROADCAST_VOLUME_CONTROL_FOR_CONNECTED_DEVICES, false);
+ mFakeFlagsImpl.setFlag(Flags.FLAG_LEAUDIO_MULTIPLE_VOCS_INSTANCES_API, false);
VolumeControlNativeInterface.setInstance(mNativeInterface);
mService = new VolumeControlService(mTargetContext, mFakeFlagsImpl);
- mService.doStart();
+ mService.start();
+ mService.setAvailable(true);
mService.mAudioManager = mAudioManager;
mService.mFactory = mServiceFactory;
@@ -168,7 +170,7 @@
return;
}
- mService.doStop();
+ mService.stop();
VolumeControlNativeInterface.setInstance(null);
mTargetContext.unregisterReceiver(mVolumeControlIntentReceiver);
mDeviceQueueMap.clear();
@@ -1011,17 +1013,28 @@
public void testServiceBinderVolumeOffsetMethods() throws Exception {
// Send a message to trigger connection completed
generateDeviceAvailableMessageFromNative(mDevice, 2);
- final SynchronousResultReceiver<Boolean> boolRecv = SynchronousResultReceiver.get();
- boolean defaultRecvValue = false;
- mServiceBinder.isVolumeOffsetAvailable(mDevice, mAttributionSource, boolRecv);
- Assert.assertTrue(boolRecv.awaitResultNoInterrupt(Duration.ofMillis(TIMEOUT_MS))
- .getValue(defaultRecvValue));
+ final SynchronousResultReceiver<Boolean> boolRecv = SynchronousResultReceiver.get();
+ boolean defaultAvailability = false;
+ mServiceBinder.isVolumeOffsetAvailable(mDevice, mAttributionSource, boolRecv);
+ Assert.assertTrue(
+ boolRecv.awaitResultNoInterrupt(Duration.ofMillis(TIMEOUT_MS))
+ .getValue(defaultAvailability));
+
+ final SynchronousResultReceiver<Integer> intRecv = SynchronousResultReceiver.get();
+ int defaultNumberOfInstances = 0;
+ mServiceBinder.getNumberOfVolumeOffsetInstances(mDevice, mAttributionSource, intRecv);
+ int numberOfInstances =
+ intRecv.awaitResultNoInterrupt(Duration.ofMillis(TIMEOUT_MS))
+ .getValue(defaultNumberOfInstances);
+ Assert.assertEquals(2, numberOfInstances);
+
+ int id = 1;
int volumeOffset = 100;
final SynchronousResultReceiver<Void> voidRecv = SynchronousResultReceiver.get();
- mServiceBinder.setVolumeOffset(mDevice, volumeOffset, mAttributionSource, voidRecv);
+ mServiceBinder.setVolumeOffset(mDevice, id, volumeOffset, mAttributionSource, voidRecv);
voidRecv.awaitResultNoInterrupt(Duration.ofMillis(TIMEOUT_MS));
- verify(mNativeInterface).setExtAudioOutVolumeOffset(mDevice, 1, volumeOffset);
+ verify(mNativeInterface).setExtAudioOutVolumeOffset(mDevice, id, volumeOffset);
}
@Test
@@ -1096,6 +1109,8 @@
@Test
public void testServiceBinderRegisterCallbackWhenDeviceAlreadyConnected() throws Exception {
+ mFakeFlagsImpl.setFlag(Flags.FLAG_LEAUDIO_MULTIPLE_VOCS_INSTANCES_API, true);
+
int groupId = 1;
int groupVolume = 56;
@@ -1111,7 +1126,7 @@
doReturn(true).when(mNativeInterface).connectVolumeControl(any(BluetoothDevice.class));
doReturn(true).when(mNativeInterface).disconnectVolumeControl(any(BluetoothDevice.class));
- generateDeviceAvailableMessageFromNative(mDevice, 1);
+ generateDeviceAvailableMessageFromNative(mDevice, 2);
generateConnectionMessageFromNative(
mDevice, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED);
Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, mService.getConnectionState(mDevice));
@@ -1130,9 +1145,21 @@
Assert.assertTrue(mService.getDevices().contains(mDeviceTwo));
verify(mNativeInterface, times(1)).setVolume(eq(mDeviceTwo), eq(groupVolume));
- // Set different offset to both devices
+ // Generate events for both devices
generateDeviceOffsetChangedMessageFromNative(mDevice, 1, 100);
- generateDeviceOffsetChangedMessageFromNative(mDeviceTwo, 1, 200);
+ generateDeviceLocationChangedMessageFromNative(mDevice, 1, 1);
+ final String testDevice1Desc1 = "testDevice1Desc1";
+ generateDeviceDescriptionChangedMessageFromNative(mDevice, 1, testDevice1Desc1);
+
+ generateDeviceOffsetChangedMessageFromNative(mDevice, 2, 200);
+ generateDeviceLocationChangedMessageFromNative(mDevice, 2, 2);
+ final String testDevice1Desc2 = "testDevice1Desc2";
+ generateDeviceDescriptionChangedMessageFromNative(mDevice, 2, testDevice1Desc2);
+
+ generateDeviceOffsetChangedMessageFromNative(mDeviceTwo, 1, 250);
+ generateDeviceLocationChangedMessageFromNative(mDeviceTwo, 1, 3);
+ final String testDevice2Desc = "testDevice2Desc";
+ generateDeviceDescriptionChangedMessageFromNative(mDeviceTwo, 1, testDevice2Desc);
// Register callback and verify it is called with known devices
IBluetoothVolumeControlCallback callback =
@@ -1146,12 +1173,30 @@
recv.awaitResultNoInterrupt(Duration.ofMillis(TIMEOUT_MS)).getValue(null);
Assert.assertEquals(size + 1, mService.mCallbacks.getRegisteredCallbackCount());
- verify(callback).onVolumeOffsetChanged(eq(mDeviceTwo), eq(200));
- verify(callback).onVolumeOffsetChanged(eq(mDevice), eq(100));
+ verify(callback).onVolumeOffsetChanged(eq(mDevice), eq(1), eq(100));
+ verify(callback).onVolumeOffsetAudioLocationChanged(eq(mDevice), eq(1), eq(1));
+ verify(callback)
+ .onVolumeOffsetAudioDescriptionChanged(eq(mDevice), eq(1), eq(testDevice1Desc1));
+
+ verify(callback).onVolumeOffsetChanged(eq(mDevice), eq(2), eq(200));
+ verify(callback).onVolumeOffsetAudioLocationChanged(eq(mDevice), eq(2), eq(2));
+ verify(callback)
+ .onVolumeOffsetAudioDescriptionChanged(eq(mDevice), eq(2), eq(testDevice1Desc2));
+
+ verify(callback).onVolumeOffsetChanged(eq(mDeviceTwo), eq(1), eq(250));
+ verify(callback).onVolumeOffsetAudioLocationChanged(eq(mDeviceTwo), eq(1), eq(3));
+ verify(callback)
+ .onVolumeOffsetAudioDescriptionChanged(eq(mDeviceTwo), eq(1), eq(testDevice2Desc));
generateDeviceOffsetChangedMessageFromNative(mDevice, 1, 50);
+ generateDeviceLocationChangedMessageFromNative(mDevice, 1, 0);
+ final String testDevice1Desc3 = "testDevice1Desc3";
+ generateDeviceDescriptionChangedMessageFromNative(mDevice, 1, testDevice1Desc3);
- verify(callback).onVolumeOffsetChanged(eq(mDevice), eq(50));
+ verify(callback).onVolumeOffsetChanged(eq(mDevice), eq(1), eq(50));
+ verify(callback).onVolumeOffsetAudioLocationChanged(eq(mDevice), eq(1), eq(0));
+ verify(callback)
+ .onVolumeOffsetAudioDescriptionChanged(eq(mDevice), eq(1), eq(testDevice1Desc3));
}
@Test
@@ -1511,6 +1556,30 @@
mService.messageFromNative(event);
}
+ private void generateDeviceLocationChangedMessageFromNative(
+ BluetoothDevice device, int extOffsetIndex, int location) {
+ // Send a message to trigger connection completed
+ VolumeControlStackEvent event =
+ new VolumeControlStackEvent(
+ VolumeControlStackEvent.EVENT_TYPE_EXT_AUDIO_OUT_LOCATION_CHANGED);
+ event.device = device;
+ event.valueInt1 = extOffsetIndex; // external output index
+ event.valueInt2 = location; // location
+ mService.messageFromNative(event);
+ }
+
+ private void generateDeviceDescriptionChangedMessageFromNative(
+ BluetoothDevice device, int extOffsetIndex, String description) {
+ // Send a message to trigger connection completed
+ VolumeControlStackEvent event =
+ new VolumeControlStackEvent(
+ VolumeControlStackEvent.EVENT_TYPE_EXT_AUDIO_OUT_DESCRIPTION_CHANGED);
+ event.device = device;
+ event.valueInt1 = extOffsetIndex; // external output index
+ event.valueString1 = description; // description
+ mService.messageFromNative(event);
+ }
+
/**
* Helper function to test okToConnect() method
*
diff --git a/android/pandora/server/configs/pts_bot_tests_config.json b/android/pandora/server/configs/pts_bot_tests_config.json
index e2545cc..4be7bff 100644
--- a/android/pandora/server/configs/pts_bot_tests_config.json
+++ b/android/pandora/server/configs/pts_bot_tests_config.json
@@ -550,6 +550,7 @@
"PBAP/PSE/GOEP/SRM/BI-03-C",
"PBAP/PSE/GOEP/SRM/BI-05-C",
"PBAP/PSE/GOEP/SRM/BV-08-C",
+ "PBAP/PSE/GOEP/SRMP/BI-02-C",
"PBAP/PSE/GOEP/SRMP/BV-02-C",
"PBAP/PSE/PBB/BI-01-C",
"PBAP/PSE/PBB/BI-07-C",
@@ -994,7 +995,6 @@
"PAN/NAP/MISC/UUID/BV-02-C",
"PAN/PANU/IP/APP/BV-04-I",
"PAN/PANU/IPv4/AUTONET/BV-01-I",
- "PBAP/PSE/GOEP/SRMP/BI-02-C",
"PBAP/PSE/SSM/BV-07-C",
"RFCOMM/DEVA-DEVB/RFC/BV-21-C",
"RFCOMM/DEVA-DEVB/RFC/BV-22-C",
@@ -2219,4 +2219,4 @@
"SUM ICS": {},
"VCP": {}
}
-}
\ No newline at end of file
+}
diff --git a/android/pandora/server/src/Pbap.kt b/android/pandora/server/src/Pbap.kt
index 7c630dc..5b7cef4 100644
--- a/android/pandora/server/src/Pbap.kt
+++ b/android/pandora/server/src/Pbap.kt
@@ -94,6 +94,7 @@
val displayName = String.format(DEFAULT_DISPLAY_NAME, contactIndex)
val phoneNumber = generatePhoneNumber(PHONE_NUM_LENGTH)
val emailID = String.format(DEFAULT_EMAIL_ID, contactIndex)
+ val note = String.format(DEFAULT_NOTE, contactIndex)
val rawContactInsertIndex = operations.size
operations.add(
@@ -129,6 +130,14 @@
.build()
)
+ operations.add(
+ ContentProviderOperation.newInsert(Data.CONTENT_URI)
+ .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
+ .withValue(Data.MIMETYPE, Note.CONTENT_ITEM_TYPE)
+ .withValue(Note.NOTE, note)
+ .build()
+ )
+
context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, operations)
}
@@ -146,5 +155,12 @@
const val DEFAULT_EMAIL_ID = "user%d@example.com"
const val CONTACT_LIST_SIZE = 125
const val PHONE_NUM_LENGTH = 10
+ const val DEFAULT_NOTE =
+ """
+ %d Lorem ipsum dolor sit amet, consectetur adipiscing elit.
+ Vivamus condimentum rhoncus est volutpat venenatis.
+ Fusce semper, sapien ut venenatis pellentesque,
+ lorem dui aliquam sapien, non pharetra diam neque id mi.
+ """
}
}
diff --git a/flags/Android.bp b/flags/Android.bp
index 84b96b3..6fe1b7c 100644
--- a/flags/Android.bp
+++ b/flags/Android.bp
@@ -6,6 +6,7 @@
aconfig_declarations {
name: "bluetooth_aconfig_flags",
package: "com.android.bluetooth.flags",
+ container: "com.android.btservices",
srcs: [
"**/*.aconfig",
],
diff --git a/flags/a2dp.aconfig b/flags/a2dp.aconfig
index 456a263..0e3db85 100644
--- a/flags/a2dp.aconfig
+++ b/flags/a2dp.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "a2dp_offload_codec_extensibility"
diff --git a/flags/asha.aconfig b/flags/asha.aconfig
index 368a237..e20012c 100644
--- a/flags/asha.aconfig
+++ b/flags/asha.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "higher_l2cap_flush_threshold"
diff --git a/flags/audio_routing.aconfig b/flags/audio_routing.aconfig
index e46c83b..f34f8a5 100644
--- a/flags/audio_routing.aconfig
+++ b/flags/audio_routing.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "audio_routing_centralization"
diff --git a/flags/bta_dm.aconfig b/flags/bta_dm.aconfig
index 38a0e4a..332fa49 100644
--- a/flags/bta_dm.aconfig
+++ b/flags/bta_dm.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "synchronous_bta_sec"
diff --git a/flags/btif_dm.aconfig b/flags/btif_dm.aconfig
index aeb88e2..0d05890 100644
--- a/flags/btif_dm.aconfig
+++ b/flags/btif_dm.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "ignore_bond_type_for_le"
diff --git a/flags/connectivity.aconfig b/flags/connectivity.aconfig
index 1d50dad..372f5db 100644
--- a/flags/connectivity.aconfig
+++ b/flags/connectivity.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "api_get_connection_state_using_identity_address"
@@ -13,3 +14,10 @@
description: "Guard the le shim connection map with a mutex"
bug: "302054609"
}
+
+flag {
+ name: "api_get_connection_state_sync_on_main"
+ namespace: "bluetooth"
+ description: "API call is unprotected from thread race conditions"
+ bug: "325333718"
+}
diff --git a/flags/content_profiles.aconfig b/flags/content_profiles.aconfig
deleted file mode 100644
index 6f37130..0000000
--- a/flags/content_profiles.aconfig
+++ /dev/null
@@ -1,8 +0,0 @@
-package: "com.android.bluetooth.flags"
-
-flag {
- name: "content_profiles_errors_metrics"
- namespace: "bluetooth"
- description: "Enable logging error metrics in content profiles"
- bug: "317002318"
-}
diff --git a/flags/discovery_service.aconfig b/flags/discovery_service.aconfig
index eaecd0f..f3ccef9 100644
--- a/flags/discovery_service.aconfig
+++ b/flags/discovery_service.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "gdx_device_discovery"
diff --git a/flags/dumpsys.aconfig b/flags/dumpsys.aconfig
index 66fb79d..ae7ff19 100644
--- a/flags/dumpsys.aconfig
+++ b/flags/dumpsys.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "dumpsys_use_passed_in_fd"
diff --git a/flags/framework.aconfig b/flags/framework.aconfig
index ab09f71..daa1119 100644
--- a/flags/framework.aconfig
+++ b/flags/framework.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "mfi_has_uuid"
diff --git a/flags/gap.aconfig b/flags/gap.aconfig
index 8ac7124..8513d59 100644
--- a/flags/gap.aconfig
+++ b/flags/gap.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "encrypted_advertising_data"
@@ -76,3 +77,17 @@
description: "Cleans up restricted handles when disconnected"
bug: "323110155"
}
+
+flag {
+ name: "brcm_better_le_scan_params"
+ namespace: "bluetooth"
+ description: "Optimize LE scan parameters for BRCM controllers"
+ bug: "324238597"
+}
+
+flag {
+ name: "le_periodic_scanning_reassembler"
+ namespace: "bluetooth"
+ description: "Enable reassembly of LE periodic advertising events"
+ bug: "324886466"
+}
diff --git a/flags/hal.aconfig b/flags/hal.aconfig
index 101650d..ebcf643 100644
--- a/flags/hal.aconfig
+++ b/flags/hal.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "audio_hal_version_class"
diff --git a/flags/hap.aconfig b/flags/hap.aconfig
index 45c8749..32da69b 100644
--- a/flags/hap.aconfig
+++ b/flags/hap.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "settings_can_control_hap_preset"
diff --git a/flags/hfp.aconfig b/flags/hfp.aconfig
index 3ff6dc7..b50bb4a 100644
--- a/flags/hfp.aconfig
+++ b/flags/hfp.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "auto_connect_on_hfp_when_no_a2dp_device"
diff --git a/flags/hid.aconfig b/flags/hid.aconfig
index ebad661..cfca613 100644
--- a/flags/hid.aconfig
+++ b/flags/hid.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "break_uhid_polling_early"
diff --git a/flags/l2cap.aconfig b/flags/l2cap.aconfig
index 7b7dd68..86b36f7 100644
--- a/flags/l2cap.aconfig
+++ b/flags/l2cap.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "l2cap_tx_complete_cb_info"
diff --git a/flags/le_advertising.aconfig b/flags/le_advertising.aconfig
index 4b12c8a..524d046 100644
--- a/flags/le_advertising.aconfig
+++ b/flags/le_advertising.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "nrpa_non_connectable_adv"
diff --git a/flags/leaudio.aconfig b/flags/leaudio.aconfig
index ccf18f6..f74c517 100644
--- a/flags/leaudio.aconfig
+++ b/flags/leaudio.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "leaudio_broadcast_monitor_source_sync_status"
@@ -127,4 +128,34 @@
namespace: "bluetooth"
description: "Support multiple audio outputs for volume offset"
bug: "323156655"
-}
\ No newline at end of file
+}
+
+flag {
+ name: "leaudio_volume_change_on_ringtone_fix"
+ namespace: "bluetooth"
+ description: "Apply the volume update to call volume during ringtone"
+ bug: "324041939"
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
+}
+
+flag {
+ name: "leaudio_active_device_manager_group_handling_fix"
+ namespace: "bluetooth"
+ description: "Make sure Active Device Manager understands LeAudio groups"
+ bug: "324364321"
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
+}
+
+flag {
+ name: "leaudio_start_stream_race_fix"
+ namespace: "bluetooth"
+ description: "Fix possible race on start stream request"
+ bug: "325181889"
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
+}
diff --git a/flags/mapclient.aconfig b/flags/mapclient.aconfig
new file mode 100644
index 0000000..33afc8f
--- /dev/null
+++ b/flags/mapclient.aconfig
@@ -0,0 +1,15 @@
+package: "com.android.bluetooth.flags"
+
+flag {
+ name: "handle_delivery_sending_failure_events"
+ namespace: "bluetooth"
+ description: "Handle DeliveryFailure and SendingFailure Event types of MAP-Event-Reports from the MNS."
+ bug: "317400386"
+}
+
+flag {
+ name: "use_entire_message_handle"
+ namespace: "bluetooth"
+ description: "Use entire message handle of messages pushed from MCE to MSE."
+ bug: "323382399"
+}
diff --git a/flags/opp.aconfig b/flags/opp.aconfig
index 8cbb212..d32b73f 100644
--- a/flags/opp.aconfig
+++ b/flags/opp.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "opp_start_activity_directly_from_notification"
diff --git a/flags/ranging.aconfig b/flags/ranging.aconfig
index 1be1b6e..811bf61 100644
--- a/flags/ranging.aconfig
+++ b/flags/ranging.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "channel_sounding"
@@ -6,3 +7,10 @@
description: "Enable Channel Sounding"
bug: "317683528"
}
+
+flag {
+ name: "channel_sounding_in_stack"
+ namespace: "bluetooth"
+ description: "Enable Channel Sounding in the Bluetooth stack"
+ bug: "324185011"
+}
\ No newline at end of file
diff --git a/flags/rfcomm.aconfig b/flags/rfcomm.aconfig
index f7e9fe9..a801f4b 100644
--- a/flags/rfcomm.aconfig
+++ b/flags/rfcomm.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "rfcomm_always_use_mitm"
diff --git a/flags/rnr.aconfig b/flags/rnr.aconfig
index d1b9143..3acc5d0 100644
--- a/flags/rnr.aconfig
+++ b/flags/rnr.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "rnr_cancel_before_event_race"
diff --git a/flags/security.aconfig b/flags/security.aconfig
index 85bedde..3addb59 100644
--- a/flags/security.aconfig
+++ b/flags/security.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "correct_bond_type_of_loaded_devices"
diff --git a/flags/sniff.aconfig b/flags/sniff.aconfig
index 14aa2b0..5b66d74 100644
--- a/flags/sniff.aconfig
+++ b/flags/sniff.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "enable_sniff_offload"
diff --git a/flags/sockets.aconfig b/flags/sockets.aconfig
index 8310fed..c6770cd 100644
--- a/flags/sockets.aconfig
+++ b/flags/sockets.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "unix_file_socket_creation_failure"
diff --git a/flags/system_service.aconfig b/flags/system_service.aconfig
index b95d44f..64bdedc 100644
--- a/flags/system_service.aconfig
+++ b/flags/system_service.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "airplane_ressources_in_app"
diff --git a/flags/vcp.aconfig b/flags/vcp.aconfig
index 2869941..bdc0047 100644
--- a/flags/vcp.aconfig
+++ b/flags/vcp.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "vcp_mute_unmute"
diff --git a/flags/vsc.aconfig b/flags/vsc.aconfig
index 7f77e57..fe31287 100644
--- a/flags/vsc.aconfig
+++ b/flags/vsc.aconfig
@@ -1,4 +1,5 @@
package: "com.android.bluetooth.flags"
+container: "com.android.btservices"
flag {
name: "report_vsc_data_from_the_gd_controller"
diff --git a/framework/OWNERS b/framework/OWNERS
index 301f9e8..fdf7a66 100644
--- a/framework/OWNERS
+++ b/framework/OWNERS
@@ -1,4 +1,4 @@
-eruffieux@google.com
+hallstrom@google.com
sattiraju@google.com
siyuanh@google.com
wescande@google.com
diff --git a/framework/api/current.txt b/framework/api/current.txt
index 43cf91b..4b56783 100644
--- a/framework/api/current.txt
+++ b/framework/api/current.txt
@@ -977,12 +977,19 @@
field public static final int FRAME_DURATION_10000 = 2; // 0x2
field public static final int FRAME_DURATION_7500 = 1; // 0x1
field public static final int FRAME_DURATION_NONE = 0; // 0x0
+ field @FlaggedApi("com.android.bluetooth.flags.leaudio_add_sampling_frequencies") public static final int SAMPLE_RATE_11025 = 2; // 0x2
field public static final int SAMPLE_RATE_16000 = 4; // 0x4
+ field @FlaggedApi("com.android.bluetooth.flags.leaudio_add_sampling_frequencies") public static final int SAMPLE_RATE_176400 = 1024; // 0x400
+ field @FlaggedApi("com.android.bluetooth.flags.leaudio_add_sampling_frequencies") public static final int SAMPLE_RATE_192000 = 2048; // 0x800
+ field @FlaggedApi("com.android.bluetooth.flags.leaudio_add_sampling_frequencies") public static final int SAMPLE_RATE_22050 = 8; // 0x8
field public static final int SAMPLE_RATE_24000 = 16; // 0x10
field public static final int SAMPLE_RATE_32000 = 32; // 0x20
+ field @FlaggedApi("com.android.bluetooth.flags.leaudio_add_sampling_frequencies") public static final int SAMPLE_RATE_384000 = 4096; // 0x1000
field public static final int SAMPLE_RATE_44100 = 64; // 0x40
field public static final int SAMPLE_RATE_48000 = 128; // 0x80
field public static final int SAMPLE_RATE_8000 = 1; // 0x1
+ field @FlaggedApi("com.android.bluetooth.flags.leaudio_add_sampling_frequencies") public static final int SAMPLE_RATE_88200 = 256; // 0x100
+ field @FlaggedApi("com.android.bluetooth.flags.leaudio_add_sampling_frequencies") public static final int SAMPLE_RATE_96000 = 512; // 0x200
field public static final int SAMPLE_RATE_NONE = 0; // 0x0
field public static final int SOURCE_CODEC_TYPE_INVALID = 1000000; // 0xf4240
field public static final int SOURCE_CODEC_TYPE_LC3 = 0; // 0x0
diff --git a/framework/api/system-current.txt b/framework/api/system-current.txt
index 02126d3..04a1691 100644
--- a/framework/api/system-current.txt
+++ b/framework/api/system-current.txt
@@ -75,6 +75,8 @@
method @NonNull @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public android.os.Bundle getPreferredAudioProfiles(@NonNull android.bluetooth.BluetoothDevice);
method @NonNull @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public java.util.List<java.lang.Integer> getSupportedProfiles();
method @NonNull @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public java.util.List<android.os.ParcelUuid> getUuidsList();
+ method @FlaggedApi("com.android.bluetooth.flags.auto_on_feature") @RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED) public boolean isAutoOnEnabled();
+ method @FlaggedApi("com.android.bluetooth.flags.auto_on_feature") @RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED) public boolean isAutoOnSupported();
method public boolean isBleScanAlwaysAvailable();
method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int isDistanceMeasurementSupported();
method public boolean isLeEnabled();
@@ -88,6 +90,7 @@
method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public void requestControllerActivityEnergyInfo(@NonNull java.util.concurrent.Executor, @NonNull android.bluetooth.BluetoothAdapter.OnBluetoothActivityEnergyInfoCallback);
method @NonNull @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public android.bluetooth.BluetoothSocket retrieveConnectedRfcommSocket(@NonNull java.util.UUID);
method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED, android.Manifest.permission.MODIFY_PHONE_STATE}) public boolean setActiveDevice(@NonNull android.bluetooth.BluetoothDevice, int);
+ method @FlaggedApi("com.android.bluetooth.flags.auto_on_feature") @RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED) public void setAutoOnEnabled(boolean);
method @RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED) public int setBluetoothHciSnoopLoggingMode(int);
method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_SCAN, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int setDiscoverableTimeout(@NonNull java.time.Duration);
method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int setPreferredAudioProfiles(@NonNull android.bluetooth.BluetoothDevice, @NonNull android.os.Bundle);
@@ -442,7 +445,9 @@
method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int getConnectionPolicy(@NonNull android.bluetooth.BluetoothDevice);
method @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public int getConnectionState(@NonNull android.bluetooth.BluetoothDevice);
method @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public java.util.List<android.bluetooth.BluetoothDevice> getDevicesMatchingConnectionStates(int[]);
+ method @FlaggedApi("com.android.bluetooth.flags.allow_switching_hid_and_hogp") @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int getPreferredTransport(@NonNull android.bluetooth.BluetoothDevice);
method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public boolean setConnectionPolicy(@NonNull android.bluetooth.BluetoothDevice, int);
+ method @FlaggedApi("com.android.bluetooth.flags.allow_switching_hid_and_hogp") @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public boolean setPreferredTransport(@NonNull android.bluetooth.BluetoothDevice, int);
field @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public static final String ACTION_CONNECTION_STATE_CHANGED = "android.bluetooth.input.profile.action.CONNECTION_STATE_CHANGED";
}
@@ -1102,18 +1107,23 @@
method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int getConnectionPolicy(@NonNull android.bluetooth.BluetoothDevice);
method @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public int getConnectionState(android.bluetooth.BluetoothDevice);
method @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public java.util.List<android.bluetooth.BluetoothDevice> getDevicesMatchingConnectionStates(int[]);
+ method @FlaggedApi("com.android.bluetooth.flags.leaudio_multiple_vocs_instances_api") @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public int getNumberOfVolumeOffsetInstances(@NonNull android.bluetooth.BluetoothDevice);
method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public boolean isVolumeOffsetAvailable(@NonNull android.bluetooth.BluetoothDevice);
method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public void registerCallback(@NonNull java.util.concurrent.Executor, @NonNull android.bluetooth.BluetoothVolumeControl.Callback);
method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public boolean setConnectionPolicy(@NonNull android.bluetooth.BluetoothDevice, int);
method @FlaggedApi("com.android.bluetooth.flags.leaudio_broadcast_volume_control_for_connected_devices") @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public void setDeviceVolume(@NonNull android.bluetooth.BluetoothDevice, @IntRange(from=0, to=255) int, boolean);
- method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public void setVolumeOffset(@NonNull android.bluetooth.BluetoothDevice, @IntRange(from=0xffffff01, to=255) int);
+ method @Deprecated @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public void setVolumeOffset(@NonNull android.bluetooth.BluetoothDevice, @IntRange(from=0xffffff01, to=255) int);
+ method @FlaggedApi("com.android.bluetooth.flags.leaudio_multiple_vocs_instances_api") @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public void setVolumeOffset(@NonNull android.bluetooth.BluetoothDevice, @IntRange(from=1, to=255) int, @IntRange(from=0xffffff01, to=255) int);
method @RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT, android.Manifest.permission.BLUETOOTH_PRIVILEGED}) public void unregisterCallback(@NonNull android.bluetooth.BluetoothVolumeControl.Callback);
field @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public static final String ACTION_CONNECTION_STATE_CHANGED = "android.bluetooth.volume-control.profile.action.CONNECTION_STATE_CHANGED";
}
public static interface BluetoothVolumeControl.Callback {
method @FlaggedApi("com.android.bluetooth.flags.leaudio_broadcast_volume_control_for_connected_devices") public default void onDeviceVolumeChanged(@NonNull android.bluetooth.BluetoothDevice, @IntRange(from=0, to=255) int);
- method public void onVolumeOffsetChanged(@NonNull android.bluetooth.BluetoothDevice, @IntRange(from=0xffffff01, to=255) int);
+ method @FlaggedApi("com.android.bluetooth.flags.leaudio_multiple_vocs_instances_api") public default void onVolumeOffsetAudioDescriptionChanged(@NonNull android.bluetooth.BluetoothDevice, @IntRange(from=1, to=255) int, @NonNull String);
+ method @FlaggedApi("com.android.bluetooth.flags.leaudio_multiple_vocs_instances_api") public default void onVolumeOffsetAudioLocationChanged(@NonNull android.bluetooth.BluetoothDevice, @IntRange(from=1, to=255) int, @IntRange(from=0xffffff01, to=255) int);
+ method @Deprecated public void onVolumeOffsetChanged(@NonNull android.bluetooth.BluetoothDevice, @IntRange(from=0xffffff01, to=255) int);
+ method @FlaggedApi("com.android.bluetooth.flags.leaudio_multiple_vocs_instances_api") public default void onVolumeOffsetChanged(@NonNull android.bluetooth.BluetoothDevice, @IntRange(from=1, to=255) int, @IntRange(from=0xffffff01, to=255) int);
}
public final class BufferConstraint implements android.os.Parcelable {
diff --git a/framework/java/android/bluetooth/BluetoothAdapter.java b/framework/java/android/bluetooth/BluetoothAdapter.java
index f4eaf21..e0cdc2c 100644
--- a/framework/java/android/bluetooth/BluetoothAdapter.java
+++ b/framework/java/android/bluetooth/BluetoothAdapter.java
@@ -22,6 +22,7 @@
import static java.util.Objects.requireNonNull;
import android.annotation.CallbackExecutor;
+import android.annotation.FlaggedApi;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -69,6 +70,7 @@
import android.util.Log;
import android.util.Pair;
+import com.android.bluetooth.flags.Flags;
import com.android.internal.annotations.GuardedBy;
import com.android.modules.expresslog.Counter;
import com.android.modules.utils.SynchronousResultReceiver;
@@ -5796,6 +5798,60 @@
return BT_SNOOP_LOG_MODE_DISABLED;
}
+ /**
+ * Returns true if the auto on feature is supported on the device
+ *
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_AUTO_ON_FEATURE)
+ @RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED)
+ public boolean isAutoOnSupported() {
+ try {
+ return mManagerService.isAutoOnSupported();
+ } catch (RemoteException e) {
+ e.rethrowFromSystemServer();
+ }
+ return false;
+ }
+
+ /**
+ * Get the value of the automatic restart of the Bluetooth stack for the current user
+ *
+ * @return true if the auto on feature is enabled for the current user
+ * @throws IllegalStateException if feature is not supported
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_AUTO_ON_FEATURE)
+ @RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED)
+ public boolean isAutoOnEnabled() {
+ try {
+ return mManagerService.isAutoOnEnabled();
+ } catch (RemoteException e) {
+ e.rethrowFromSystemServer();
+ }
+ return false;
+ }
+
+ /**
+ * Set the value of the automatic restart of the Bluetooth stack for the current user
+ *
+ * @param status true if the feature is enabled
+ * @throws IllegalStateException if feature is not supported
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_AUTO_ON_FEATURE)
+ @RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED)
+ public void setAutoOnEnabled(boolean status) {
+ try {
+ mManagerService.setAutoOnEnabled(status);
+ } catch (RemoteException e) {
+ e.rethrowFromSystemServer();
+ }
+ }
+
/** @hide */
@Retention(RetentionPolicy.SOURCE)
@IntDef(
diff --git a/framework/java/android/bluetooth/BluetoothGatt.java b/framework/java/android/bluetooth/BluetoothGatt.java
index 0c0a333..76d1cf4 100644
--- a/framework/java/android/bluetooth/BluetoothGatt.java
+++ b/framework/java/android/bluetooth/BluetoothGatt.java
@@ -46,6 +46,7 @@
import java.util.UUID;
import java.util.concurrent.TimeoutException;
+
/**
* Public API for the Bluetooth GATT Profile.
*
@@ -1686,6 +1687,13 @@
}
throw e.rethrowAsRuntimeException();
}
+ if (Flags.gattFixDeviceBusy()) {
+ if (requestStatus != BluetoothStatusCodes.SUCCESS) {
+ synchronized (mDeviceBusyLock) {
+ mDeviceBusy = false;
+ }
+ }
+ }
return requestStatus;
}
@@ -1837,6 +1845,11 @@
}
throw e.rethrowAsRuntimeException();
}
+ if (Flags.gattFixDeviceBusy()) {
+ synchronized (mDeviceBusyLock) {
+ mDeviceBusy = false;
+ }
+ }
return BluetoothStatusCodes.ERROR_UNKNOWN;
}
diff --git a/framework/java/android/bluetooth/BluetoothHidHost.java b/framework/java/android/bluetooth/BluetoothHidHost.java
index 4c55ad1..69bdf21 100644
--- a/framework/java/android/bluetooth/BluetoothHidHost.java
+++ b/framework/java/android/bluetooth/BluetoothHidHost.java
@@ -19,12 +19,14 @@
import static android.bluetooth.BluetoothUtils.getSyncTimeout;
import android.Manifest;
+import android.annotation.FlaggedApi;
import android.annotation.NonNull;
import android.annotation.RequiresPermission;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.annotation.SuppressLint;
import android.annotation.SystemApi;
+import android.bluetooth.BluetoothDevice.Transport;
import android.bluetooth.annotations.RequiresBluetoothConnectPermission;
import android.bluetooth.annotations.RequiresLegacyBluetoothAdminPermission;
import android.bluetooth.annotations.RequiresLegacyBluetoothPermission;
@@ -34,10 +36,12 @@
import android.os.RemoteException;
import android.util.Log;
+import com.android.bluetooth.flags.Flags;
import com.android.modules.utils.SynchronousResultReceiver;
import java.util.ArrayList;
import java.util.List;
+import java.util.Objects;
import java.util.concurrent.TimeoutException;
/**
@@ -64,12 +68,16 @@
* <ul>
* <li>{@link #EXTRA_STATE} - The current state of the profile.
* <li>{@link #EXTRA_PREVIOUS_STATE}- The previous state of the profile.
+ * <li>{@link BluetoothDevice#EXTRA_TRANSPORT} - Transport of the connection.
* <li>{@link BluetoothDevice#EXTRA_DEVICE} - The remote device.
* </ul>
*
* <p>{@link #EXTRA_STATE} or {@link #EXTRA_PREVIOUS_STATE} can be any of {@link
* #STATE_DISCONNECTED}, {@link #STATE_CONNECTING}, {@link #STATE_CONNECTED}, {@link
* #STATE_DISCONNECTING}.
+ *
+ * <p>{@link BluetoothDevice#EXTRA_TRANSPORT} can be any of {@link
+ * BluetoothDevice#TRANSPORT_BREDR}, {@link BluetoothDevice#TRANSPORT_LE}.
*/
@SuppressLint("ActionValue")
@RequiresLegacyBluetoothPermission
@@ -465,6 +473,60 @@
}
/**
+ * Set preferred transport for the device
+ *
+ * <p>The device should already be paired, services must have been discovered. This API is
+ * effective only if both the HID and HOGP are supported on the remote device.
+ *
+ * @param device paired bluetooth device
+ * @param transport the preferred transport to set for this device
+ * @return true if preferred transport is set, false on error
+ * @throws IllegalArgumentException if the {@code device} invalid.
+ * @hide
+ */
+ @FlaggedApi(Flags.FLAG_ALLOW_SWITCHING_HID_AND_HOGP)
+ @SystemApi
+ @RequiresBluetoothConnectPermission
+ @RequiresPermission(
+ allOf = {
+ android.Manifest.permission.BLUETOOTH_CONNECT,
+ android.Manifest.permission.BLUETOOTH_PRIVILEGED,
+ })
+ public boolean setPreferredTransport(
+ @NonNull BluetoothDevice device, @Transport int transport) {
+ if (DBG) log("setPreferredTransport(" + device + ", " + transport + ")");
+
+ Objects.requireNonNull(device, "device must not be null");
+
+ if (transport != BluetoothDevice.TRANSPORT_AUTO
+ && transport != BluetoothDevice.TRANSPORT_BREDR
+ && transport != BluetoothDevice.TRANSPORT_LE) {
+ throw new IllegalArgumentException("Invalid transport value");
+ }
+
+ final IBluetoothHidHost service = getService();
+ final boolean defaultValue = false;
+
+ if (service == null) {
+ Log.w(TAG, "Proxy not attached to service");
+ if (DBG) log(Log.getStackTraceString(new Throwable()));
+ } else if (!isEnabled()) {
+ Log.w(TAG, "Not ready");
+ } else if (!isValidDevice(device)) {
+ throw new IllegalArgumentException("Invalid device");
+ } else {
+ try {
+ final SynchronousResultReceiver<Boolean> recv = SynchronousResultReceiver.get();
+ service.setPreferredTransport(device, transport, mAttributionSource, recv);
+ return recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(defaultValue);
+ } catch (RemoteException | TimeoutException e) {
+ Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
+ }
+ }
+ return defaultValue;
+ }
+
+ /**
* Get the priority of the profile.
*
* <p>The priority can be any of: {@link #PRIORITY_OFF}, {@link #PRIORITY_ON}, {@link
@@ -524,6 +586,48 @@
return defaultValue;
}
+ /**
+ * Get the preferred transport for the device.
+ *
+ * @param device Bluetooth device
+ * @return preferred transport for the device
+ * @throws IllegalArgumentException if the {@code device} invalid.
+ * @hide
+ */
+ @FlaggedApi(Flags.FLAG_ALLOW_SWITCHING_HID_AND_HOGP)
+ @SystemApi
+ @RequiresBluetoothConnectPermission
+ @RequiresPermission(
+ allOf = {
+ android.Manifest.permission.BLUETOOTH_CONNECT,
+ android.Manifest.permission.BLUETOOTH_PRIVILEGED,
+ })
+ public @Transport int getPreferredTransport(@NonNull BluetoothDevice device) {
+ if (VDBG) log("getPreferredTransport(" + device + ")");
+
+ Objects.requireNonNull(device, "device must not be null");
+
+ final IBluetoothHidHost service = getService();
+ final int defaultValue = BluetoothDevice.TRANSPORT_AUTO;
+ if (service == null) {
+ Log.w(TAG, "Proxy not attached to service");
+ if (DBG) log(Log.getStackTraceString(new Throwable()));
+ } else if (!isEnabled()) {
+ Log.w(TAG, "Not ready");
+ } else if (!isValidDevice(device)) {
+ throw new IllegalArgumentException("Invalid device");
+ } else {
+ try {
+ final SynchronousResultReceiver<Integer> recv = SynchronousResultReceiver.get();
+ service.getPreferredTransport(device, mAttributionSource, recv);
+ return recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(defaultValue);
+ } catch (RemoteException | TimeoutException e) {
+ Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
+ }
+ }
+ return defaultValue;
+ }
+
private boolean isEnabled() {
return mAdapter.getState() == BluetoothAdapter.STATE_ON;
}
diff --git a/framework/java/android/bluetooth/BluetoothLeAudio.java b/framework/java/android/bluetooth/BluetoothLeAudio.java
index 1bbc084..ae0883b 100644
--- a/framework/java/android/bluetooth/BluetoothLeAudio.java
+++ b/framework/java/android/bluetooth/BluetoothLeAudio.java
@@ -201,6 +201,21 @@
executor.execute(() -> callback.onGroupStatusChanged(groupId, groupStatus));
}
}
+
+ @Override
+ public void onGroupStreamStatusChanged(int groupId, int groupStreamStatus) {
+ if (Flags.leaudioCallbackOnGroupStreamStatus()) {
+ for (Map.Entry<BluetoothLeAudio.Callback, Executor> callbackExecutorEntry :
+ mCallbackExecutorMap.entrySet()) {
+ BluetoothLeAudio.Callback callback = callbackExecutorEntry.getKey();
+ Executor executor = callbackExecutorEntry.getValue();
+ executor.execute(
+ () ->
+ callback.onGroupStreamStatusChanged(
+ groupId, groupStreamStatus));
+ }
+ }
+ }
};
/**
diff --git a/framework/java/android/bluetooth/BluetoothLeAudioCodecConfig.java b/framework/java/android/bluetooth/BluetoothLeAudioCodecConfig.java
index acf95c7..4c820b6 100644
--- a/framework/java/android/bluetooth/BluetoothLeAudioCodecConfig.java
+++ b/framework/java/android/bluetooth/BluetoothLeAudioCodecConfig.java
@@ -16,12 +16,15 @@
package android.bluetooth;
+import android.annotation.FlaggedApi;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.os.Parcel;
import android.os.Parcelable;
+import com.android.bluetooth.flags.Flags;
+
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Objects;
@@ -73,11 +76,18 @@
value = {
SAMPLE_RATE_NONE,
SAMPLE_RATE_8000,
+ SAMPLE_RATE_11025,
SAMPLE_RATE_16000,
+ SAMPLE_RATE_22050,
SAMPLE_RATE_24000,
SAMPLE_RATE_32000,
SAMPLE_RATE_44100,
- SAMPLE_RATE_48000
+ SAMPLE_RATE_48000,
+ SAMPLE_RATE_88200,
+ SAMPLE_RATE_96000,
+ SAMPLE_RATE_176400,
+ SAMPLE_RATE_192000,
+ SAMPLE_RATE_384000
})
@Retention(RetentionPolicy.SOURCE)
public @interface SampleRate {}
@@ -85,16 +95,24 @@
/**
* Codec sample rate 0 Hz. Default value used for codec sample rate. Values are the bit mask as
* defined in the Bluetooth Assigned Numbers, Generic Audio, Supported_Sampling_Frequencies
- * table Note: We use only part of it.
+ * table.
*/
public static final int SAMPLE_RATE_NONE = 0;
/** Codec sample rate 8000 Hz. */
public static final int SAMPLE_RATE_8000 = 0x01 << 0;
+ /** Codec sample rate 11025 Hz. */
+ @FlaggedApi(Flags.FLAG_LEAUDIO_ADD_SAMPLING_FREQUENCIES)
+ public static final int SAMPLE_RATE_11025 = 0x01 << 1;
+
/** Codec sample rate 16000 Hz. */
public static final int SAMPLE_RATE_16000 = 0x01 << 2;
+ /** Codec sample rate 22050 Hz. */
+ @FlaggedApi(Flags.FLAG_LEAUDIO_ADD_SAMPLING_FREQUENCIES)
+ public static final int SAMPLE_RATE_22050 = 0x01 << 3;
+
/** Codec sample rate 24000 Hz. */
public static final int SAMPLE_RATE_24000 = 0x01 << 4;
@@ -107,6 +125,26 @@
/** Codec sample rate 48000 Hz. */
public static final int SAMPLE_RATE_48000 = 0x01 << 7;
+ /** Codec sample rate 88200 Hz. */
+ @FlaggedApi(Flags.FLAG_LEAUDIO_ADD_SAMPLING_FREQUENCIES)
+ public static final int SAMPLE_RATE_88200 = 0x01 << 8;
+
+ /** Codec sample rate 96000 Hz. */
+ @FlaggedApi(Flags.FLAG_LEAUDIO_ADD_SAMPLING_FREQUENCIES)
+ public static final int SAMPLE_RATE_96000 = 0x01 << 9;
+
+ /** Codec sample rate 176400 Hz. */
+ @FlaggedApi(Flags.FLAG_LEAUDIO_ADD_SAMPLING_FREQUENCIES)
+ public static final int SAMPLE_RATE_176400 = 0x01 << 10;
+
+ /** Codec sample rate 192000 Hz. */
+ @FlaggedApi(Flags.FLAG_LEAUDIO_ADD_SAMPLING_FREQUENCIES)
+ public static final int SAMPLE_RATE_192000 = 0x01 << 11;
+
+ /** Codec sample rate 384000 Hz. */
+ @FlaggedApi(Flags.FLAG_LEAUDIO_ADD_SAMPLING_FREQUENCIES)
+ public static final int SAMPLE_RATE_384000 = 0x01 << 12;
+
/** @hide */
@IntDef(
flag = true,
diff --git a/framework/java/android/bluetooth/BluetoothLeAudioCodecConfigMetadata.java b/framework/java/android/bluetooth/BluetoothLeAudioCodecConfigMetadata.java
index 0cff465..680c15d 100644
--- a/framework/java/android/bluetooth/BluetoothLeAudioCodecConfigMetadata.java
+++ b/framework/java/android/bluetooth/BluetoothLeAudioCodecConfigMetadata.java
@@ -29,13 +29,18 @@
import static android.bluetooth.BluetoothLeAudioCodecConfig.SAMPLE_RATE_NONE;
import static android.bluetooth.BluetoothLeAudioCodecConfig.SampleRate;
+import android.annotation.FlaggedApi;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
+import android.bluetooth.BluetoothLeAudioCodecConfig.FrameDuration;
+import android.bluetooth.BluetoothLeAudioCodecConfig.SampleRate;
import android.bluetooth.BluetoothUtils.TypeValueEntry;
import android.os.Parcel;
import android.os.Parcelable;
+import com.android.bluetooth.flags.Flags;
+
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
@@ -70,6 +75,13 @@
private static final int CONFIG_SAMPLING_FREQUENCY_32000 = 0x06;
private static final int CONFIG_SAMPLING_FREQUENCY_44100 = 0x07;
private static final int CONFIG_SAMPLING_FREQUENCY_48000 = 0x08;
+ private static final int CONFIG_SAMPLING_FREQUENCY_11025 = 0x09;
+ private static final int CONFIG_SAMPLING_FREQUENCY_22050 = 0x0a;
+ private static final int CONFIG_SAMPLING_FREQUENCY_88200 = 0x0b;
+ private static final int CONFIG_SAMPLING_FREQUENCY_96000 = 0x0c;
+ private static final int CONFIG_SAMPLING_FREQUENCY_176400 = 0x0d;
+ private static final int CONFIG_SAMPLING_FREQUENCY_192000 = 0x0e;
+ private static final int CONFIG_SAMPLING_FREQUENCY_384000 = 0x0f;
/** Audio codec config frame duration from metadata. */
private static final int CONFIG_FRAME_DURATION_UNKNOWN = -1;
@@ -375,7 +387,20 @@
&& sampleRate != SAMPLE_RATE_32000
&& sampleRate != SAMPLE_RATE_44100
&& sampleRate != SAMPLE_RATE_48000) {
- throw new IllegalArgumentException("Invalid sample rate " + sampleRate);
+
+ if (Flags.leaudioAddSamplingFrequencies()) {
+ if (sampleRate != BluetoothLeAudioCodecConfig.SAMPLE_RATE_11025
+ && sampleRate != BluetoothLeAudioCodecConfig.SAMPLE_RATE_22050
+ && sampleRate != BluetoothLeAudioCodecConfig.SAMPLE_RATE_88200
+ && sampleRate != BluetoothLeAudioCodecConfig.SAMPLE_RATE_96000
+ && sampleRate != BluetoothLeAudioCodecConfig.SAMPLE_RATE_176400
+ && sampleRate != BluetoothLeAudioCodecConfig.SAMPLE_RATE_192000
+ && sampleRate != BluetoothLeAudioCodecConfig.SAMPLE_RATE_384000) {
+ throw new IllegalArgumentException("Invalid sample rate " + sampleRate);
+ }
+ } else {
+ throw new IllegalArgumentException("Invalid sample rate " + sampleRate);
+ }
}
mSampleRate = sampleRate;
return this;
@@ -504,6 +529,24 @@
case CONFIG_SAMPLING_FREQUENCY_48000:
return SAMPLE_RATE_48000;
default:
+ if (Flags.leaudioAddSamplingFrequencies()) {
+ switch (samplingFrequencyValue) {
+ case CONFIG_SAMPLING_FREQUENCY_11025:
+ return BluetoothLeAudioCodecConfig.SAMPLE_RATE_11025;
+ case CONFIG_SAMPLING_FREQUENCY_22050:
+ return BluetoothLeAudioCodecConfig.SAMPLE_RATE_22050;
+ case CONFIG_SAMPLING_FREQUENCY_88200:
+ return BluetoothLeAudioCodecConfig.SAMPLE_RATE_88200;
+ case CONFIG_SAMPLING_FREQUENCY_96000:
+ return BluetoothLeAudioCodecConfig.SAMPLE_RATE_96000;
+ case CONFIG_SAMPLING_FREQUENCY_176400:
+ return BluetoothLeAudioCodecConfig.SAMPLE_RATE_176400;
+ case CONFIG_SAMPLING_FREQUENCY_192000:
+ return BluetoothLeAudioCodecConfig.SAMPLE_RATE_192000;
+ case CONFIG_SAMPLING_FREQUENCY_384000:
+ return BluetoothLeAudioCodecConfig.SAMPLE_RATE_384000;
+ }
+ }
return SAMPLE_RATE_NONE;
}
}
@@ -523,6 +566,24 @@
case SAMPLE_RATE_48000:
return CONFIG_SAMPLING_FREQUENCY_48000;
default:
+ if (Flags.leaudioAddSamplingFrequencies()) {
+ switch (sampleRateBitSet) {
+ case BluetoothLeAudioCodecConfig.SAMPLE_RATE_11025:
+ return CONFIG_SAMPLING_FREQUENCY_11025;
+ case BluetoothLeAudioCodecConfig.SAMPLE_RATE_22050:
+ return CONFIG_SAMPLING_FREQUENCY_22050;
+ case BluetoothLeAudioCodecConfig.SAMPLE_RATE_88200:
+ return CONFIG_SAMPLING_FREQUENCY_88200;
+ case BluetoothLeAudioCodecConfig.SAMPLE_RATE_96000:
+ return CONFIG_SAMPLING_FREQUENCY_96000;
+ case BluetoothLeAudioCodecConfig.SAMPLE_RATE_176400:
+ return CONFIG_SAMPLING_FREQUENCY_176400;
+ case BluetoothLeAudioCodecConfig.SAMPLE_RATE_192000:
+ return CONFIG_SAMPLING_FREQUENCY_192000;
+ case BluetoothLeAudioCodecConfig.SAMPLE_RATE_384000:
+ return CONFIG_SAMPLING_FREQUENCY_384000;
+ }
+ }
return CONFIG_SAMPLING_FREQUENCY_UNKNOWN;
}
}
diff --git a/framework/java/android/bluetooth/BluetoothVolumeControl.java b/framework/java/android/bluetooth/BluetoothVolumeControl.java
index 29ae950..cffce77 100644
--- a/framework/java/android/bluetooth/BluetoothVolumeControl.java
+++ b/framework/java/android/bluetooth/BluetoothVolumeControl.java
@@ -85,13 +85,65 @@
*
* @param device remote device whose volume offset changed
* @param volumeOffset latest volume offset for this device
+ * @deprecated Use new callback which give information about a VOCS instance ID
* @hide
*/
+ @Deprecated
@SystemApi
void onVolumeOffsetChanged(
@NonNull BluetoothDevice device, @IntRange(from = -255, to = 255) int volumeOffset);
/**
+ * Callback invoked when callback is registered and when volume offset changes on the remote
+ * device. Change can be triggered autonomously by the remote device or after volume offset
+ * change on the user request done by calling {@link #setVolumeOffset(device, instanceId,
+ * volumeOffset)}
+ *
+ * @param device remote device whose volume offset changed
+ * @param instanceId identifier of VOCS instance on the remote device
+ * @param volumeOffset latest volume offset for this VOCS instance
+ * @hide
+ */
+ @FlaggedApi(Flags.FLAG_LEAUDIO_MULTIPLE_VOCS_INSTANCES_API)
+ @SystemApi
+ default void onVolumeOffsetChanged(
+ @NonNull BluetoothDevice device,
+ @IntRange(from = 1, to = 255) int instanceId,
+ @IntRange(from = -255, to = 255) int volumeOffset) {}
+
+ /**
+ * Callback invoked when callback is registered and when audio location changes on the
+ * remote device. Change can be triggered autonomously by the remote device.
+ *
+ * @param device remote device whose audio location changed
+ * @param instanceId identifier of VOCS instance on the remote device
+ * @param audioLocation latest audio location for this VOCS instance
+ * @hide
+ */
+ @FlaggedApi(Flags.FLAG_LEAUDIO_MULTIPLE_VOCS_INSTANCES_API)
+ @SystemApi
+ default void onVolumeOffsetAudioLocationChanged(
+ @NonNull BluetoothDevice device,
+ @IntRange(from = 1, to = 255) int instanceId,
+ @IntRange(from = -255, to = 255) int audioLocation) {}
+
+ /**
+ * Callback invoked when callback is registered and when audio description changes on the
+ * remote device. Change can be triggered autonomously by the remote device.
+ *
+ * @param device remote device whose audio description changed
+ * @param instanceId identifier of VOCS instance on the remote device
+ * @param audioDescription latest audio description for this VOCS instance
+ * @hide
+ */
+ @FlaggedApi(Flags.FLAG_LEAUDIO_MULTIPLE_VOCS_INSTANCES_API)
+ @SystemApi
+ default void onVolumeOffsetAudioDescriptionChanged(
+ @NonNull BluetoothDevice device,
+ @IntRange(from = 1, to = 255) int instanceId,
+ @NonNull String audioDescription) {}
+
+ /**
* Callback for le audio connected device volume level change
*
* <p>The valid volume range is [0, 255], as defined in 2.3.1.1 Volume_Setting field of
@@ -112,14 +164,64 @@
new IBluetoothVolumeControlCallback.Stub() {
@Override
public void onVolumeOffsetChanged(
- @NonNull BluetoothDevice device, int volumeOffset) {
+ @NonNull BluetoothDevice device, int instanceId, int volumeOffset) {
Attributable.setAttributionSource(device, mAttributionSource);
for (Map.Entry<BluetoothVolumeControl.Callback, Executor>
callbackExecutorEntry : mCallbackExecutorMap.entrySet()) {
BluetoothVolumeControl.Callback callback = callbackExecutorEntry.getKey();
Executor executor = callbackExecutorEntry.getValue();
- executor.execute(
- () -> callback.onVolumeOffsetChanged(device, volumeOffset));
+
+ // The old API operates on the first instance only
+ if (instanceId == 1) {
+ try {
+ executor.execute(
+ () -> callback.onVolumeOffsetChanged(device, volumeOffset));
+ } finally {
+ // As this deprecated callback, might not be defined; continue
+ }
+ }
+ if (Flags.leaudioMultipleVocsInstancesApi()) {
+ executor.execute(
+ () ->
+ callback.onVolumeOffsetChanged(
+ device, instanceId, volumeOffset));
+ }
+ }
+ }
+
+ @Override
+ public void onVolumeOffsetAudioLocationChanged(
+ @NonNull BluetoothDevice device, int instanceId, int audioLocation) {
+ if (Flags.leaudioMultipleVocsInstancesApi()) {
+ Attributable.setAttributionSource(device, mAttributionSource);
+ for (Map.Entry<BluetoothVolumeControl.Callback, Executor>
+ callbackExecutorEntry : mCallbackExecutorMap.entrySet()) {
+ BluetoothVolumeControl.Callback callback =
+ callbackExecutorEntry.getKey();
+ Executor executor = callbackExecutorEntry.getValue();
+ executor.execute(
+ () ->
+ callback.onVolumeOffsetAudioLocationChanged(
+ device, instanceId, audioLocation));
+ }
+ }
+ }
+
+ @Override
+ public void onVolumeOffsetAudioDescriptionChanged(
+ @NonNull BluetoothDevice device, int instanceId, String audioDescription) {
+ if (Flags.leaudioMultipleVocsInstancesApi()) {
+ Attributable.setAttributionSource(device, mAttributionSource);
+ for (Map.Entry<BluetoothVolumeControl.Callback, Executor>
+ callbackExecutorEntry : mCallbackExecutorMap.entrySet()) {
+ BluetoothVolumeControl.Callback callback =
+ callbackExecutorEntry.getKey();
+ Executor executor = callbackExecutorEntry.getValue();
+ executor.execute(
+ () ->
+ callback.onVolumeOffsetAudioDescriptionChanged(
+ device, instanceId, audioDescription));
+ }
}
}
@@ -374,52 +476,96 @@
throw new IllegalArgumentException("This callback has already been registered");
}
+ final IBluetoothVolumeControl service = getService();
+ if (service == null) {
+ return;
+ }
try {
- final IBluetoothVolumeControl service = getService();
- if (service != null) {
- final SynchronousResultReceiver<Integer> recv = SynchronousResultReceiver.get();
+ final SynchronousResultReceiver<Integer> recv = SynchronousResultReceiver.get();
- /* If the callback map is empty, we register the service-to-app callback.
- * Otherwise, callback is registered in mCallbackExecutorMap and we just notify
- * user over callback with current values.
- */
- boolean isRegisterCallbackRequired = mCallbackExecutorMap.isEmpty();
- mCallbackExecutorMap.put(callback, executor);
+ /* If the callback map is empty, we register the service-to-app callback.
+ * Otherwise, callback is registered in mCallbackExecutorMap and we just notify
+ * user over callback with current values.
+ */
+ boolean isRegisterCallbackRequired = mCallbackExecutorMap.isEmpty();
+ mCallbackExecutorMap.put(callback, executor);
- if (isRegisterCallbackRequired) {
- service.registerCallback(mCallback, mAttributionSource, recv);
- } else {
- service.notifyNewRegisteredCallback(
- new IBluetoothVolumeControlCallback.Stub() {
- @Override
- public void onVolumeOffsetChanged(
- BluetoothDevice device, int volumeOffset)
- throws RemoteException {
- Attributable.setAttributionSource(
- device, mAttributionSource);
+ if (isRegisterCallbackRequired) {
+ service.registerCallback(mCallback, mAttributionSource, recv);
+ } else {
+ service.notifyNewRegisteredCallback(
+ new IBluetoothVolumeControlCallback.Stub() {
+ @Override
+ public void onVolumeOffsetChanged(
+ BluetoothDevice device, int instanceId, int volumeOffset)
+ throws RemoteException {
+ Attributable.setAttributionSource(device, mAttributionSource);
+
+ // The old API operates on the first instance only
+ if (instanceId == 1) {
+ try {
+ executor.execute(
+ () ->
+ callback.onVolumeOffsetChanged(
+ device, volumeOffset));
+ } finally {
+ // As this deprecated callback, might not be
+ // defined; continue
+ }
+ }
+ if (Flags.leaudioMultipleVocsInstancesApi()) {
executor.execute(
() ->
callback.onVolumeOffsetChanged(
- device, volumeOffset));
+ device, instanceId, volumeOffset));
}
+ }
- @Override
- public void onDeviceVolumeChanged(
- BluetoothDevice device, int volume)
- throws RemoteException {
+ @Override
+ public void onVolumeOffsetAudioLocationChanged(
+ BluetoothDevice device, int instanceId, int location)
+ throws RemoteException {
+ if (Flags.leaudioMultipleVocsInstancesApi()) {
Attributable.setAttributionSource(
device, mAttributionSource);
executor.execute(
() ->
- callback.onDeviceVolumeChanged(
- device, volume));
+ callback.onVolumeOffsetAudioLocationChanged(
+ device, instanceId, location));
}
- },
- mAttributionSource,
- recv);
- }
- recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(null);
+ }
+
+ @Override
+ public void onVolumeOffsetAudioDescriptionChanged(
+ BluetoothDevice device,
+ int instanceId,
+ String audioDescription)
+ throws RemoteException {
+ if (Flags.leaudioMultipleVocsInstancesApi()) {
+ Attributable.setAttributionSource(
+ device, mAttributionSource);
+ executor.execute(
+ () ->
+ callback
+ .onVolumeOffsetAudioDescriptionChanged(
+ device,
+ instanceId,
+ audioDescription));
+ }
+ }
+
+ @Override
+ public void onDeviceVolumeChanged(
+ BluetoothDevice device, int volume) throws RemoteException {
+ Attributable.setAttributionSource(device, mAttributionSource);
+ executor.execute(
+ () -> callback.onDeviceVolumeChanged(device, volume));
+ }
+ },
+ mAttributionSource,
+ recv);
}
+ recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(null);
} catch (RemoteException e) {
mCallbackExecutorMap.remove(callback);
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
@@ -481,8 +627,11 @@
*
* @param device {@link BluetoothDevice} representing the remote device
* @param volumeOffset volume offset to be set on the remote device
+ * @deprecated Use new method which allows for choosing a VOCS instance. This method will always
+ * use the first instance.
* @hide
*/
+ @Deprecated
@SystemApi
@RequiresBluetoothConnectPermission
@RequiresPermission(
@@ -492,7 +641,67 @@
})
public void setVolumeOffset(
@NonNull BluetoothDevice device, @IntRange(from = -255, to = 255) int volumeOffset) {
- if (DBG) log("setVolumeOffset(" + device + " volumeOffset: " + volumeOffset + ")");
+ final int defaultInstanceId = 1;
+ setVolumeOffsetInternal(device, defaultInstanceId, volumeOffset);
+ }
+
+ /**
+ * Tells the remote device to set a volume offset to the absolute volume. One device might have
+ * multiple VOCS instances. This instances could be i.e. different speakers or sound types as
+ * media/voice/notification.
+ *
+ * @param device {@link BluetoothDevice} representing the remote device
+ * @param instanceId identifier of VOCS instance on the remote device. Identifiers are numerated
+ * from 1. Number of them was notified by callbacks and it can be read using {@link
+ * #getNumberOfVolumeOffsetInstances(BluetoothDevice)}. Providing non existing instance ID
+ * will be ignored
+ * @param volumeOffset volume offset to be set on VOCS instance
+ * @hide
+ */
+ @FlaggedApi(Flags.FLAG_LEAUDIO_MULTIPLE_VOCS_INSTANCES_API)
+ @SystemApi
+ @RequiresBluetoothConnectPermission
+ @RequiresPermission(
+ allOf = {
+ android.Manifest.permission.BLUETOOTH_CONNECT,
+ android.Manifest.permission.BLUETOOTH_PRIVILEGED,
+ })
+ public void setVolumeOffset(
+ @NonNull BluetoothDevice device,
+ @IntRange(from = 1, to = 255) int instanceId,
+ @IntRange(from = -255, to = 255) int volumeOffset) {
+ setVolumeOffsetInternal(device, instanceId, volumeOffset);
+ }
+
+ /**
+ * INTERNAL HELPER METHOD, DO NOT MAKE PUBLIC
+ *
+ * <p>Tells the remote device to set a volume offset to the absolute volume. One device might
+ * have multiple VOCS instances. This instances could be i.e. different speakers or sound types
+ * as media/voice/notification.
+ *
+ * @param device {@link BluetoothDevice} representing the remote device
+ * @param instanceId identifier of VOCS instance on the remote device. Identifiers are numerated
+ * from 1. Number of them was notified by callbacks and it can be read using {@link
+ * #getNumberOfVolumeOffsetInstances(BluetoothDevice)}. Providing non existing instance ID
+ * will be ignored
+ * @param volumeOffset volume offset to be set on VOCS instance
+ * @hide
+ */
+ private void setVolumeOffsetInternal(
+ @NonNull BluetoothDevice device,
+ @IntRange(from = 1, to = 255) int instanceId,
+ @IntRange(from = -255, to = 255) int volumeOffset) {
+ if (DBG) {
+ log(
+ "setVolumeOffset("
+ + device
+ + "/"
+ + instanceId
+ + " volumeOffset: "
+ + volumeOffset
+ + ")");
+ }
final IBluetoothVolumeControl service = getService();
if (service == null) {
Log.w(TAG, "Proxy not attached to service");
@@ -500,7 +709,7 @@
} else if (isEnabled()) {
try {
final SynchronousResultReceiver recv = SynchronousResultReceiver.get();
- service.setVolumeOffset(device, volumeOffset, mAttributionSource, recv);
+ service.setVolumeOffset(device, instanceId, volumeOffset, mAttributionSource, recv);
recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(null);
} catch (RemoteException | TimeoutException e) {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
@@ -539,9 +748,49 @@
final boolean defaultValue = false;
try {
- final SynchronousResultReceiver recv = SynchronousResultReceiver.get();
+ final SynchronousResultReceiver<Boolean> recv = SynchronousResultReceiver.get();
service.isVolumeOffsetAvailable(device, mAttributionSource, recv);
- recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(defaultValue);
+ return recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(defaultValue);
+ } catch (RemoteException | TimeoutException e) {
+ Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
+ }
+
+ return defaultValue;
+ }
+
+ /**
+ * Provides information about the number of volume offset instances
+ *
+ * @param device {@link BluetoothDevice} representing the remote device
+ * @return number of VOCS instances. When Bluetooth is off, the return value is 0.
+ * @hide
+ */
+ @FlaggedApi(Flags.FLAG_LEAUDIO_MULTIPLE_VOCS_INSTANCES_API)
+ @SystemApi
+ @RequiresBluetoothConnectPermission
+ @RequiresPermission(
+ allOf = {
+ android.Manifest.permission.BLUETOOTH_CONNECT,
+ android.Manifest.permission.BLUETOOTH_PRIVILEGED,
+ })
+ public int getNumberOfVolumeOffsetInstances(@NonNull BluetoothDevice device) {
+ if (DBG) log("getNumberOfVolumeOffsetInstances(" + device + ")");
+ final IBluetoothVolumeControl service = getService();
+ final int defaultValue = 0;
+
+ if (service == null) {
+ Log.w(TAG, "Proxy not attached to service");
+ if (DBG) log(Log.getStackTraceString(new Throwable()));
+ return defaultValue;
+ }
+
+ if (!isEnabled()) {
+ return defaultValue;
+ }
+ try {
+ final SynchronousResultReceiver<Integer> recv = SynchronousResultReceiver.get();
+ service.getNumberOfVolumeOffsetInstances(device, mAttributionSource, recv);
+ return recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(defaultValue);
} catch (RemoteException | TimeoutException e) {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
diff --git a/framework/tests/bumble/src/android/bluetooth/GattClientTest.java b/framework/tests/bumble/src/android/bluetooth/GattClientTest.java
index ef5b6c1..e7a056d 100644
--- a/framework/tests/bumble/src/android/bluetooth/GattClientTest.java
+++ b/framework/tests/bumble/src/android/bluetooth/GattClientTest.java
@@ -25,6 +25,7 @@
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockingDetails;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
@@ -40,6 +41,7 @@
import com.android.bluetooth.flags.Flags;
import com.android.compatibility.common.util.AdoptShellPermissionsRule;
+import org.junit.Assume;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Rule;
@@ -67,6 +69,10 @@
private static final UUID GAP_UUID = UUID.fromString("00001800-0000-1000-8000-00805f9b34fb");
+ private static final UUID WRITABLE_SERVICE_UUID =
+ UUID.fromString("00000000-0000-0000-0000-00000000000");
+ private static final UUID WRITABLE_CHARACTERISTIC_UUID =
+ UUID.fromString("00010001-0000-0000-0000-000000000000");
@ClassRule public static final AdoptShellPermissionsRule PERM = new AdoptShellPermissionsRule();
@Rule public final PandoraDevice mBumble = new PandoraDevice();
@@ -87,28 +93,25 @@
mAdapter.getRemoteLeDevice(
Utils.BUMBLE_RANDOM_ADDRESS, BluetoothDevice.ADDRESS_TYPE_RANDOM);
- for (int i = 0; i < 10; i++) {
- BluetoothGattCallback gattCallback = mock(BluetoothGattCallback.class);
- BluetoothGatt gatt = device.connectGatt(mContext, false, gattCallback);
- gatt.close();
+ BluetoothGattCallback gattCallback = mock(BluetoothGattCallback.class);
+ BluetoothGatt gatt = device.connectGatt(mContext, false, gattCallback);
+ gatt.close();
- // Save the number of call in the callback to be checked later
- Collection<Invocation> invocations = mockingDetails(gattCallback).getInvocations();
- int numberOfCalls = invocations.size();
+ // Save the number of call in the callback to be checked later
+ Collection<Invocation> invocations = mockingDetails(gattCallback).getInvocations();
+ int numberOfCalls = invocations.size();
- BluetoothGattCallback gattCallback2 = mock(BluetoothGattCallback.class);
- BluetoothGatt gatt2 = device.connectGatt(mContext, false, gattCallback2);
- verify(gattCallback2, timeout(1000))
- .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_CONNECTED));
- gatt2.close();
+ BluetoothGattCallback gattCallback2 = mock(BluetoothGattCallback.class);
+ BluetoothGatt gatt2 = device.connectGatt(mContext, false, gattCallback2);
+ verify(gattCallback2, timeout(1000))
+ .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_CONNECTED));
+ disconnectAndWaitDisconnection(gatt2, gattCallback2);
- // After reconnecting with the second set of callback, check that nothing happened on
- // the first set of callback
- Collection<Invocation> invocationsAfterSomeTimes =
- mockingDetails(gattCallback).getInvocations();
- int numberOfCallsAfterSomeTimes = invocationsAfterSomeTimes.size();
- assertThat(numberOfCallsAfterSomeTimes).isEqualTo(numberOfCalls);
- }
+ // After reconnecting, verify the first callback was not invoked.
+ Collection<Invocation> invocationsAfterSomeTimes =
+ mockingDetails(gattCallback).getInvocations();
+ int numberOfCallsAfterSomeTimes = invocationsAfterSomeTimes.size();
+ assertThat(numberOfCallsAfterSomeTimes).isEqualTo(numberOfCalls);
}
@Test
@@ -202,20 +205,9 @@
verify(gattCallback, timeout(10000))
.onServicesDiscovered(any(), eq(BluetoothGatt.GATT_SUCCESS));
- BluetoothGattCharacteristic characteristic = null;
-
- outer:
- for (BluetoothGattService candidateService : gatt.getServices()) {
- for (BluetoothGattCharacteristic candidateCharacteristic :
- candidateService.getCharacteristics()) {
- if ((candidateCharacteristic.getProperties()
- & BluetoothGattCharacteristic.PROPERTY_WRITE)
- != 0) {
- characteristic = candidateCharacteristic;
- break outer;
- }
- }
- }
+ BluetoothGattCharacteristic characteristic =
+ gatt.getService(WRITABLE_SERVICE_UUID)
+ .getCharacteristic(WRITABLE_CHARACTERISTIC_UUID);
byte[] newValue = new byte[] {13};
@@ -249,21 +241,82 @@
eq(BluetoothProfile.STATE_DISCONNECTED));
}
+ @RequiresFlagsEnabled(Flags.FLAG_GATT_FIX_DEVICE_BUSY)
+ @Test
+ public void consecutiveWriteCharacteristicFails_thenSuccess() throws Exception {
+ Assume.assumeTrue(Flags.gattFixDeviceBusy());
+
+ registerWritableGattService();
+
+ BluetoothGattCallback gattCallback = mock(BluetoothGattCallback.class);
+ BluetoothGattCallback gattCallback2 = mock(BluetoothGattCallback.class);
+
+ BluetoothGatt gatt = connectGattAndWaitConnection(gattCallback);
+ BluetoothGatt gatt2 = connectGattAndWaitConnection(gattCallback2);
+
+ try {
+ gatt.discoverServices();
+ gatt2.discoverServices();
+ verify(gattCallback, timeout(10000))
+ .onServicesDiscovered(any(), eq(BluetoothGatt.GATT_SUCCESS));
+ verify(gattCallback2, timeout(10000))
+ .onServicesDiscovered(any(), eq(BluetoothGatt.GATT_SUCCESS));
+
+ BluetoothGattCharacteristic characteristic =
+ gatt.getService(WRITABLE_SERVICE_UUID)
+ .getCharacteristic(WRITABLE_CHARACTERISTIC_UUID);
+
+ BluetoothGattCharacteristic characteristic2 =
+ gatt2.getService(WRITABLE_SERVICE_UUID)
+ .getCharacteristic(WRITABLE_CHARACTERISTIC_UUID);
+
+ byte[] newValue = new byte[] {13};
+
+ gatt.writeCharacteristic(
+ characteristic, newValue, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
+
+ // TODO: b/324355496 - Make the test consistent when Bumble supports holding a response.
+ // Skip the test if the second write succeeded.
+ Assume.assumeFalse(
+ gatt2.writeCharacteristic(
+ characteristic2,
+ newValue,
+ BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT)
+ == BluetoothStatusCodes.SUCCESS);
+
+ verify(gattCallback, timeout(5000))
+ .onCharacteristicWrite(
+ any(), eq(characteristic), eq(BluetoothGatt.GATT_SUCCESS));
+ verify(gattCallback2, never())
+ .onCharacteristicWrite(
+ any(), eq(characteristic), eq(BluetoothGatt.GATT_SUCCESS));
+
+ assertThat(
+ gatt2.writeCharacteristic(
+ characteristic2,
+ newValue,
+ BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT))
+ .isEqualTo(BluetoothStatusCodes.SUCCESS);
+ verify(gattCallback2, timeout(5000))
+ .onCharacteristicWrite(
+ any(), eq(characteristic2), eq(BluetoothGatt.GATT_SUCCESS));
+ } finally {
+ disconnectAndWaitDisconnection(gatt, gattCallback);
+ disconnectAndWaitDisconnection(gatt2, gattCallback2);
+ }
+ }
+
private void registerWritableGattService() {
-
- String characteristicUuidString = "11111111-1111-1111-1111-111111111111";
- String serviceUuidString = "00000000-0000-0000-0000-000000000000";
-
GattCharacteristicParams characteristicParams =
GattCharacteristicParams.newBuilder()
.setProperties(BluetoothGattCharacteristic.PROPERTY_WRITE)
- .setUuid(characteristicUuidString)
+ .setUuid(WRITABLE_CHARACTERISTIC_UUID.toString())
.build();
GattServiceParams serviceParams =
GattServiceParams.newBuilder()
.addCharacteristics(characteristicParams)
- .setUuid(serviceUuidString)
+ .setUuid(WRITABLE_SERVICE_UUID.toString())
.build();
RegisterServiceRequest request =
diff --git a/framework/tests/bumble/src/android/bluetooth/SdpClientTest.java b/framework/tests/bumble/src/android/bluetooth/SdpClientTest.java
index c4238ce..60b1b38 100644
--- a/framework/tests/bumble/src/android/bluetooth/SdpClientTest.java
+++ b/framework/tests/bumble/src/android/bluetooth/SdpClientTest.java
@@ -23,7 +23,6 @@
import android.content.Intent;
import android.content.IntentFilter;
import android.os.ParcelUuid;
-import android.os.Parcelable;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
@@ -40,9 +39,6 @@
import pandora.HostProto.ConnectRequest;
import pandora.HostProto.WaitConnectionRequest;
-import java.util.ArrayList;
-import java.util.UUID;
-
/** Test cases for {@link ServiceDiscoveryManager}. */
@RunWith(AndroidJUnit4.class)
public class SdpClientTest {
@@ -52,7 +48,7 @@
private final BluetoothManager mManager = mContext.getSystemService(BluetoothManager.class);
private final BluetoothAdapter mAdapter = mManager.getAdapter();
- private SettableFuture<ArrayList<UUID>> mFutureIntent;
+ private SettableFuture<ParcelUuid[]> mFutureIntent;
@Rule public final AdoptShellPermissionsRule mPermissionRule = new AdoptShellPermissionsRule();
@@ -63,16 +59,10 @@
@Override
public void onReceive(Context context, Intent intent) {
if (BluetoothDevice.ACTION_UUID.equals(intent.getAction())) {
- Parcelable[] parcelable =
- (Parcelable[]) intent.getExtra(BluetoothDevice.EXTRA_UUID);
- if (parcelable != null) {
- ArrayList<UUID> list = new ArrayList<UUID>();
- for (Parcelable p : parcelable) {
- ParcelUuid uuid = (ParcelUuid) p;
- list.add(uuid.getUuid());
- }
- mFutureIntent.set(list);
- }
+ ParcelUuid[] parcelUuids =
+ intent.getParcelableArrayExtra(
+ BluetoothDevice.EXTRA_UUID, ParcelUuid.class);
+ mFutureIntent.set(parcelUuids);
}
}
};
@@ -107,8 +97,8 @@
// Execute service discovery procedure
assertThat(device.fetchUuidsWithSdp()).isTrue();
- ArrayList<UUID> list = mFutureIntent.get();
- assertThat(list.isEmpty()).isFalse();
+ ParcelUuid[] arr = mFutureIntent.get();
+ assertThat(arr).asList().contains(BluetoothUuid.HFP);
mContext.unregisterReceiver(mConnectionStateReceiver);
}
diff --git a/service/Android.bp b/service/Android.bp
index 2dc9217..b2c2a06 100644
--- a/service/Android.bp
+++ b/service/Android.bp
@@ -22,6 +22,7 @@
":statslog-bluetooth-java-gen",
"src/**/*.java",
"src/AdapterState.kt",
+ "src/AutoOnFeature.kt",
"src/Log.kt",
"src/RadioModeListener.kt",
"src/airplane/ModeListener.kt",
@@ -80,6 +81,7 @@
"bluetooth-nano-protos",
"bluetooth-proto-enums-java-gen",
"bluetooth_flags_java_lib",
+ "modules-utils-build_system",
"modules-utils-shell-command-handler",
],
@@ -160,6 +162,8 @@
":statslog-bluetooth-java-gen",
"src/AdapterState.kt",
"src/AdapterStateTest.kt",
+ "src/AutoOnFeature.kt",
+ "src/AutoOnFeatureTest.kt",
"src/Log.kt",
"src/LogTest.kt",
"src/RadioModeListener.kt",
@@ -172,6 +176,7 @@
static_libs: [
"androidx.test.core",
+ "kotlin-test",
"kotlinx_coroutines",
"kotlinx_coroutines_test",
"mockito-robolectric-prebuilt",
diff --git a/service/aidl/android/bluetooth/IBluetoothManager.aidl b/service/aidl/android/bluetooth/IBluetoothManager.aidl
index 844342d..338a9ca 100644
--- a/service/aidl/android/bluetooth/IBluetoothManager.aidl
+++ b/service/aidl/android/bluetooth/IBluetoothManager.aidl
@@ -63,4 +63,12 @@
int setBtHciSnoopLogMode(int mode);
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED)")
int getBtHciSnoopLogMode();
+
+ // AutoOnFeature
+ @JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED)")
+ boolean isAutoOnSupported();
+ @JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED)")
+ boolean isAutoOnEnabled();
+ @JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED)")
+ void setAutoOnEnabled(boolean status);
}
diff --git a/service/build.gradle.kts b/service/build.gradle.kts
index c67e740..5cae44f 100644
--- a/service/build.gradle.kts
+++ b/service/build.gradle.kts
@@ -21,6 +21,7 @@
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.2")
implementation(files("../../../../external/kotlinc/lib/kotlin-stdlib.jar"))
+ implementation(files("../../../../out/soong/.intermediates/frameworks/libs/modules-utils/java/com/android/modules/utils/build/modules-utils-build_system/android_common_apex33/turbine-combined/modules-utils-build_system.jar"))
implementation(files("../../../../out/soong/.intermediates/frameworks/libs/modules-utils/java/com/android/modules/utils/modules-utils-shell-command-handler/android_common_apex33/turbine-combined/modules-utils-shell-command-handler.jar"))
implementation(files("../../../../out/soong/.intermediates/frameworks/libs/modules-utils/java/framework-annotations-lib/android_common/turbine-combined/framework-annotations-lib.jar"))
implementation(files("../../../../out/soong/.intermediates/packages/modules/Bluetooth/framework/framework-bluetooth-pre-jarjar/android_common/turbine-combined/framework-bluetooth-pre-jarjar.jar"))
diff --git a/service/kls-classpath b/service/kls-classpath
index b8d701e..94c7487 100755
--- a/service/kls-classpath
+++ b/service/kls-classpath
@@ -21,5 +21,12 @@
CLASSPATH+=":$ROOT/out/soong/.intermediates/packages/modules/Bluetooth/android/app/bluetooth-proto-enums-java-gen/android_common_apex33/turbine-combined/bluetooth-proto-enums-java-gen.jar"
CLASSPATH+=":$ROOT/out/soong/.intermediates/packages/modules/Bluetooth/flags/bluetooth_flags_java_lib/android_common_apex33/turbine-combined/bluetooth_flags_java_lib.jar"
CLASSPATH+=":$ROOT/out/soong/.intermediates/frameworks/libs/modules-utils/java/com/android/modules/utils/modules-utils-shell-command-handler/android_common_apex33/turbine-combined/modules-utils-shell-command-handler.jar"
+CLASSPATH+=":$ROOT/out/soong/.intermediates/frameworks/libs/modules-utils/java/com/android/modules/utils/build/modules-utils-build_system/android_common_apex33/turbine-combined/modules-utils-build_system.jar"
+
+CLASSPATH+=":$ROOT/out/soong/.intermediates/prebuilts/misc/common/androidx-test/androidx.test.core/android_common/combined/androidx.test.core.jar"
+CLASSPATH+=":$ROOT/out/soong/.intermediates/external/truth/truth/android_common/turbine-combined/truth.jar"
+CLASSPATH+=":$ROOT/out/soong/.intermediates/external/junit/junit/android_common/turbine-combined/junit.jar"
+CLASSPATH+=":$ROOT/out/soong/.intermediates/prebuilts/tools/common/m2/mockito-robolectric-prebuilt/android_common/turbine-combined/mockito-robolectric-prebuilt.jar"
+CLASSPATH+=":$ROOT/out/soong/.intermediates/external/robolectric/Robolectric_all_upstream/linux_glibc_common/6da2cb1db6f5106f6cbbfb5faa1ac779/javac-header/Robolectric_all_upstream.jar"
echo "$CLASSPATH"
diff --git a/service/src/AutoOnFeature.kt b/service/src/AutoOnFeature.kt
new file mode 100644
index 0000000..efc2759
--- /dev/null
+++ b/service/src/AutoOnFeature.kt
@@ -0,0 +1,348 @@
+/*
+ * 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.
+ */
+
+@file:JvmName("AutoOnFeature")
+
+package com.android.server.bluetooth
+
+import android.bluetooth.BluetoothAdapter.STATE_ON
+import android.content.BroadcastReceiver
+import android.content.ContentResolver
+import android.content.Context
+import android.content.Intent
+import android.content.IntentFilter
+import android.database.ContentObserver
+import android.os.Handler
+import android.os.Looper
+import android.provider.Settings
+import androidx.annotation.VisibleForTesting
+import com.android.modules.expresslog.Counter
+import com.android.server.bluetooth.airplane.hasUserToggledApm as hasUserToggledApm
+import com.android.server.bluetooth.airplane.isOn as isAirplaneModeOn
+import com.android.server.bluetooth.satellite.isOn as isSatelliteModeOn
+import java.time.LocalDateTime
+import java.time.LocalTime
+import java.time.temporal.ChronoUnit
+import kotlin.time.Duration
+import kotlin.time.DurationUnit
+import kotlin.time.toDuration
+
+private const val TAG = "AutoOnFeature"
+
+public fun resetAutoOnTimerForUser(
+ looper: Looper,
+ context: Context,
+ state: BluetoothAdapterState,
+ callback_on: () -> Unit
+) {
+ // Remove any previous timer
+ timer?.cancel()
+ timer = null
+
+ if (!isFeatureEnabledForUser(context.contentResolver)) {
+ Log.d(TAG, "Not Enabled for current user: ${context.getUser()}")
+ return
+ }
+ if (state.oneOf(STATE_ON)) {
+ Log.d(TAG, "Bluetooth already in ${state}, no need for timer")
+ return
+ }
+ if (isSatelliteModeOn) {
+ Log.d(TAG, "Satellite prevent feature activation")
+ return
+ }
+ if (isAirplaneModeOn) {
+ if (!hasUserToggledApm(context)) {
+ Log.d(TAG, "Airplane prevent feature activation")
+ return
+ }
+ Log.d(TAG, "Airplane bypassed as airplane enhanced mode has been activated previously")
+ }
+
+ val receiver =
+ object : BroadcastReceiver() {
+ override fun onReceive(ctx: Context, intent: Intent) {
+ Log.i(TAG, "Received ${intent.action} that trigger a new alarm scheduling")
+ pause()
+ resetAutoOnTimerForUser(looper, context, state, callback_on)
+ }
+ }
+
+ timer = Timer.start(looper, context, receiver, callback_on)
+}
+
+public fun pause() {
+ timer?.pause()
+ timer = null
+}
+
+public fun notifyBluetoothOn(resolver: ContentResolver) {
+ timer?.cancel()
+ timer = null
+
+ if (!isFeatureSupportedForUser(resolver)) {
+ val defaultFeatureValue = true
+ Log.i(TAG, "Feature was set to its default value ${defaultFeatureValue}")
+ setFeatureEnabledForUserUnchecked(resolver, defaultFeatureValue)
+ }
+}
+
+public fun isUserSupported(resolver: ContentResolver) = isFeatureSupportedForUser(resolver)
+
+public fun isUserEnabled(context: Context): Boolean {
+ if (!isUserSupported(context.contentResolver)) {
+ throw IllegalStateException("AutoOnFeature not supported for user: ${context.getUser()}")
+ }
+ return isFeatureEnabledForUser(context.contentResolver)
+}
+
+public fun setUserEnabled(
+ looper: Looper,
+ context: Context,
+ state: BluetoothAdapterState,
+ status: Boolean,
+ callback_on: () -> Unit,
+) {
+ if (!isUserSupported(context.contentResolver)) {
+ throw IllegalStateException("AutoOnFeature not supported for user: ${context.getUser()}")
+ }
+ setFeatureEnabledForUserUnchecked(context.contentResolver, status)
+ Counter.logIncrement(
+ if (status) "bluetooth.value_auto_on_enabled" else "bluetooth.value_auto_on_disabled"
+ )
+ resetAutoOnTimerForUser(looper, context, state, callback_on)
+}
+
+// Listener is needed because code should be actionable prior to V API release
+public fun registerHiddenApiListener(
+ looper: Looper,
+ context: Context,
+ state: BluetoothAdapterState,
+ callback_on: () -> Unit
+) {
+ HiddenApiListener.registerUser(looper, context, state, callback_on)
+}
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////// PRIVATE METHODS /////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+@VisibleForTesting internal var timer: Timer? = null
+
+@VisibleForTesting
+internal class Timer
+private constructor(
+ looper: Looper,
+ private val context: Context,
+ private val receiver: BroadcastReceiver,
+ callback_on: () -> Unit,
+ private val now: LocalDateTime,
+ private val target: LocalDateTime,
+ private val timeToSleep: Duration
+) {
+ private val handler = Handler(looper)
+
+ init {
+ writeDateToStorage(target, context.contentResolver)
+ handler.postDelayed(
+ {
+ Log.i(TAG, "[${this}]: Bluetooth restarting now")
+ callback_on()
+ cancel()
+ // Set global instance to null to prevent further action. Job is done here
+ timer = null
+ },
+ timeToSleep.inWholeMilliseconds
+ )
+ Log.i(TAG, "[${this}]: Scheduling next Bluetooth restart")
+
+ context.registerReceiver(
+ receiver,
+ IntentFilter().apply {
+ addAction(Intent.ACTION_DATE_CHANGED)
+ addAction(Intent.ACTION_TIMEZONE_CHANGED)
+ addAction(Intent.ACTION_TIME_CHANGED)
+ },
+ null,
+ handler
+ )
+ }
+
+ companion object {
+ @VisibleForTesting internal val STORAGE_KEY = "bluetooth_internal_automatic_turn_on_timer"
+
+ private fun writeDateToStorage(date: LocalDateTime, resolver: ContentResolver): Boolean {
+ return Settings.Secure.putString(resolver, STORAGE_KEY, date.toString())
+ }
+
+ private fun getDateFromStorage(resolver: ContentResolver): LocalDateTime? {
+ val date = Settings.Secure.getString(resolver, STORAGE_KEY)
+ return date?.let { LocalDateTime.parse(it) }
+ }
+
+ private fun resetStorage(resolver: ContentResolver) {
+ Settings.Secure.putString(resolver, STORAGE_KEY, null)
+ }
+
+ fun start(
+ looper: Looper,
+ context: Context,
+ receiver: BroadcastReceiver,
+ callback_on: () -> Unit
+ ): Timer? {
+ val now = LocalDateTime.now()
+ val target = getDateFromStorage(context.contentResolver) ?: nextTimeout(now)
+ val timeToSleep =
+ now.until(target, ChronoUnit.NANOS).toDuration(DurationUnit.NANOSECONDS)
+
+ if (timeToSleep.isNegative()) {
+ Log.i(TAG, "Starting now (${now}) as it was scheduled for ${target}")
+ callback_on()
+ resetStorage(context.contentResolver)
+ return null
+ }
+
+ return Timer(looper, context, receiver, callback_on, now, target, timeToSleep)
+ }
+
+ /** Return a LocalDateTime for tomorrow 5 am */
+ private fun nextTimeout(now: LocalDateTime) =
+ LocalDateTime.of(now.toLocalDate(), LocalTime.of(5, 0)).plusDays(1)
+ }
+
+ /** Save timer to storage and stop it */
+ internal fun pause() {
+ Log.i(TAG, "[${this}]: Pausing timer")
+ context.unregisterReceiver(receiver)
+ handler.removeCallbacksAndMessages(null)
+ }
+
+ /** Stop timer and reset storage */
+ @VisibleForTesting
+ internal fun cancel() {
+ Log.i(TAG, "[${this}]: Cancelling timer")
+ context.unregisterReceiver(receiver)
+ handler.removeCallbacksAndMessages(null)
+ resetStorage(context.contentResolver)
+ }
+
+ override fun toString() = "Timer scheduled ${now} for target=${target} (=${timeToSleep} delay)."
+}
+
+@VisibleForTesting internal val USER_SETTINGS_KEY = "bluetooth_automatic_turn_on"
+
+/**
+ * *Do not use outside of this file to avoid async issues*
+ *
+ * @return whether the auto on feature is enabled for this user
+ */
+private fun isFeatureEnabledForUser(resolver: ContentResolver): Boolean {
+ return Settings.Secure.getInt(resolver, USER_SETTINGS_KEY, 0) == 1
+}
+
+/**
+ * *Do not use outside of this file to avoid async issues*
+ *
+ * @return whether the auto on feature is supported for the user
+ */
+private fun isFeatureSupportedForUser(resolver: ContentResolver): Boolean {
+ return Settings.Secure.getInt(resolver, USER_SETTINGS_KEY, -1) != -1
+}
+
+/**
+ * *Do not use outside of this file to avoid async issues*
+ *
+ * @return whether the auto on feature is enabled for this user
+ */
+private fun setFeatureEnabledForUserUnchecked(resolver: ContentResolver, status: Boolean) {
+ Settings.Secure.putInt(resolver, USER_SETTINGS_KEY, if (status) 1 else 0)
+}
+
+// Listener is needed because code should be actionable prior to V API release
+@VisibleForTesting
+internal class HiddenApiListener
+private constructor(
+ looper: Looper,
+ private val context: Context,
+ state: BluetoothAdapterState,
+ callback_on: () -> Unit
+) {
+ companion object {
+ @VisibleForTesting internal var listener: HiddenApiListener? = null
+
+ fun registerUser(
+ looper: Looper,
+ context: Context,
+ state: BluetoothAdapterState,
+ callback_on: () -> Unit
+ ) {
+ // Remove observer on previous user
+ listener?.remove()
+ listener = HiddenApiListener(looper, context, state, callback_on)
+ }
+ }
+
+ private val handler = Handler(looper)
+
+ private val observer =
+ object : ContentObserver(handler) {
+ override fun onChange(selfChange: Boolean) {
+ var previousState = featureState
+ var newState =
+ Settings.Secure.getInt(context.contentResolver, USER_SETTINGS_KEY, -1)
+ featureState = newState
+
+ if (previousState == newState) {
+ Log.d(TAG, "HiddenApi: State is unchanged: ${newState}")
+ return
+ }
+
+ if (previousState == -1) {
+ Log.d(TAG, "HiddenApi: Feature default state got setup to ${newState}")
+ return
+ }
+
+ Log.d(TAG, "HiddenApi: Feature state change from ${previousState} to ${newState}")
+
+ Counter.logIncrement("bluetooth.value_auto_on_hidden_usage")
+ Counter.logIncrement(
+ if (newState == 1) "bluetooth.value_auto_on_enabled"
+ else "bluetooth.value_auto_on_disabled"
+ )
+
+ resetAutoOnTimerForUser(looper, context, state, callback_on)
+ }
+ }
+
+ private var featureState =
+ Settings.Secure.getInt(context.contentResolver, USER_SETTINGS_KEY, -1)
+
+ init {
+ val notifyForDescendants = false
+
+ context.contentResolver.registerContentObserver(
+ Settings.Secure.getUriFor(USER_SETTINGS_KEY),
+ notifyForDescendants,
+ observer
+ )
+ }
+
+ @VisibleForTesting
+ internal fun remove() {
+ context.contentResolver.unregisterContentObserver(observer)
+ handler.removeCallbacksAndMessages(null)
+ }
+}
diff --git a/service/src/AutoOnFeatureTest.kt b/service/src/AutoOnFeatureTest.kt
new file mode 100644
index 0000000..b18314e
--- /dev/null
+++ b/service/src/AutoOnFeatureTest.kt
@@ -0,0 +1,511 @@
+/*
+ * 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 com.android.server.bluetooth.test
+
+import android.bluetooth.BluetoothAdapter
+import android.content.Context
+import android.content.Intent
+import android.os.Looper
+import android.provider.Settings
+import androidx.test.core.app.ApplicationProvider
+import com.android.server.bluetooth.BluetoothAdapterState
+import com.android.server.bluetooth.HiddenApiListener
+import com.android.server.bluetooth.Log
+import com.android.server.bluetooth.Timer
+import com.android.server.bluetooth.USER_SETTINGS_KEY
+import com.android.server.bluetooth.airplane.isOn as isAirplaneModeOn
+import com.android.server.bluetooth.airplane.test.ModeListenerTest as AirplaneListener
+import com.android.server.bluetooth.isUserEnabled
+import com.android.server.bluetooth.isUserSupported
+import com.android.server.bluetooth.notifyBluetoothOn
+import com.android.server.bluetooth.pause
+import com.android.server.bluetooth.registerHiddenApiListener
+import com.android.server.bluetooth.resetAutoOnTimerForUser
+import com.android.server.bluetooth.satellite.isOn as isSatelliteModeOn
+import com.android.server.bluetooth.satellite.test.ModeListenerTest as SatelliteListener
+import com.android.server.bluetooth.setUserEnabled
+import com.android.server.bluetooth.timer
+import com.google.common.truth.Expect
+import com.google.common.truth.Truth.assertThat
+import java.time.LocalDateTime
+import java.time.LocalTime
+import kotlin.test.assertFailsWith
+import org.junit.After
+import org.junit.Before
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TestName
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.Shadows.shadowOf
+
+@RunWith(RobolectricTestRunner::class)
+@kotlinx.coroutines.ExperimentalCoroutinesApi
+class AutoOnFeatureTest {
+ private val SETTING_URI = Settings.Secure.getUriFor(USER_SETTINGS_KEY)
+
+ private val looper = Looper.getMainLooper()
+ private val state = BluetoothAdapterState()
+ private val context = ApplicationProvider.getApplicationContext<Context>()
+ private val resolver = context.contentResolver
+ private val now = LocalDateTime.now()
+ private val timerTarget = LocalDateTime.of(now.toLocalDate(), LocalTime.of(5, 0)).plusDays(1)
+
+ private var callback_count = 0
+
+ @JvmField @Rule val testName = TestName()
+ @JvmField @Rule val expect = Expect.create()
+
+ @Before
+ fun setUp() {
+ Log.i("AutoOnFeatureTest", "\t--> setUp(${testName.getMethodName()})")
+
+ enableUserSettings()
+ }
+
+ @After
+ fun tearDown() {
+ HiddenApiListener.listener?.let { it.remove() }
+ HiddenApiListener.listener = null
+
+ callback_count = 0
+ timer?.cancel()
+ timer = null
+ restoreSavedTimer()
+ }
+
+ private fun setupTimer() {
+ resetAutoOnTimerForUser(looper, context, state, this::callback_on)
+ }
+
+ private fun setUserEnabled(status: Boolean) {
+ setUserEnabled(looper, context, state, status, this::callback_on)
+ }
+
+ private fun enableUserSettings() {
+ Settings.Secure.putInt(resolver, USER_SETTINGS_KEY, 1)
+ shadowOf(looper).idle()
+ }
+
+ private fun disableUserSettings() {
+ Settings.Secure.putInt(resolver, USER_SETTINGS_KEY, 0)
+ shadowOf(looper).idle()
+ }
+
+ private fun restoreSettings() {
+ Settings.Secure.putString(resolver, USER_SETTINGS_KEY, null)
+ shadowOf(looper).idle()
+ }
+
+ private fun restoreSavedTimer() {
+ Settings.Secure.putString(resolver, Timer.STORAGE_KEY, null)
+ shadowOf(looper).idle()
+ }
+
+ private fun expectStorageTime() {
+ shadowOf(looper).idle()
+ expect
+ .that(Settings.Secure.getString(resolver, Timer.STORAGE_KEY))
+ .isEqualTo(timerTarget.toString())
+ }
+
+ private fun expectNoStorageTime() {
+ shadowOf(looper).idle()
+ expect.that(Settings.Secure.getString(resolver, Timer.STORAGE_KEY)).isNull()
+ }
+
+ private fun callback_on() {
+ callback_count++
+ }
+
+ @Test
+ fun setupTimer_whenItWasNeverUsed_isNotScheduled() {
+ restoreSettings()
+
+ setupTimer()
+
+ expect.that(timer).isNull()
+ expect.that(callback_count).isEqualTo(0)
+ }
+
+ @Test
+ fun setupTimer_whenBtOn_isNotScheduled() {
+ state.set(BluetoothAdapter.STATE_ON)
+
+ setupTimer()
+
+ state.set(BluetoothAdapter.STATE_OFF)
+ expect.that(timer).isNull()
+ expect.that(callback_count).isEqualTo(0)
+ }
+
+ @Test
+ fun setupTimer_whenBtOffAndUserEnabled_isScheduled() {
+ setupTimer()
+
+ expect.that(timer).isNotNull()
+ }
+
+ @Test
+ fun setupTimer_whenBtOffAndUserEnabled_triggerCallback() {
+ setupTimer()
+
+ shadowOf(looper).runToEndOfTasks()
+ expect.that(callback_count).isEqualTo(1)
+ expect.that(timer).isNull()
+ }
+
+ @Test
+ fun setupTimer_whenAlreadySetup_triggerCallbackOnce() {
+ setupTimer()
+ setupTimer()
+ setupTimer()
+
+ shadowOf(looper).runToEndOfTasks()
+ expect.that(callback_count).isEqualTo(1)
+ expect.that(timer).isNull()
+ }
+
+ @Test
+ fun notifyBluetoothOn_whenNoTimer_noCrash() {
+ notifyBluetoothOn(resolver)
+
+ assertThat(timer).isNull()
+ }
+
+ @Test
+ fun notifyBluetoothOn_whenTimer_isNotScheduled() {
+ setupTimer()
+ notifyBluetoothOn(resolver)
+
+ shadowOf(looper).runToEndOfTasks()
+ expect.that(callback_count).isEqualTo(0)
+ expect.that(timer).isNull()
+ }
+
+ @Test
+ fun notifyBluetoothOn_whenItWasNeverUsed_enableSettings() {
+ restoreSettings()
+
+ notifyBluetoothOn(resolver)
+
+ assertThat(isUserSupported(resolver)).isTrue()
+ }
+
+ @Test
+ fun apiIsUserEnable_whenItWasNeverUsed_throwException() {
+ restoreSettings()
+
+ assertFailsWith<IllegalStateException> { isUserEnabled(context) }
+ }
+
+ @Test
+ fun apiSetUserEnabled_whenItWasNeverUsed_throwException() {
+ restoreSettings()
+
+ assertFailsWith<IllegalStateException> { setUserEnabled(true) }
+ }
+
+ @Test
+ fun apiIsUserEnable_whenEnabled_isTrue() {
+ assertThat(isUserEnabled(context)).isTrue()
+ }
+
+ @Test
+ fun apiIsUserEnable_whenDisabled_isFalse() {
+ disableUserSettings()
+ assertThat(isUserEnabled(context)).isFalse()
+ }
+
+ @Test
+ fun apiSetUserEnableToFalse_whenScheduled_isNotScheduled() {
+ setupTimer()
+
+ setUserEnabled(false)
+
+ assertThat(isUserEnabled(context)).isFalse()
+ assertThat(callback_count).isEqualTo(0)
+ assertThat(timer).isNull()
+ }
+
+ @Test
+ fun apiSetUserEnableToFalse_whenIdle_isNotScheduled() {
+ setUserEnabled(false)
+
+ assertThat(isUserEnabled(context)).isFalse()
+ assertThat(callback_count).isEqualTo(0)
+ assertThat(timer).isNull()
+ }
+
+ @Test
+ fun apiSetUserEnableToTrue_whenIdle_canSchedule() {
+ disableUserSettings()
+
+ setUserEnabled(true)
+ setupTimer()
+
+ assertThat(timer).isNotNull()
+ }
+
+ @Test
+ fun pause_whenIdle_noTimeSave() {
+ pause()
+
+ expect.that(timer).isNull()
+ expect.that(callback_count).isEqualTo(0)
+ expectNoStorageTime()
+ }
+
+ @Test
+ fun pause_whenTimer_timeIsSaved() {
+ setupTimer()
+
+ pause()
+
+ expect.that(timer).isNull()
+ expect.that(callback_count).isEqualTo(0)
+ expectStorageTime()
+ }
+
+ @Test
+ fun setupTimer_whenIdle_timeIsSave() {
+ setupTimer()
+
+ expect.that(timer).isNotNull()
+ expect.that(callback_count).isEqualTo(0)
+ expectStorageTime()
+ }
+
+ @Test
+ fun setupTimer_whenPaused_isResumed() {
+ val now = LocalDateTime.now()
+ val alarmTime = LocalDateTime.of(now.toLocalDate(), LocalTime.of(5, 0)).plusDays(1)
+ Settings.Secure.putString(resolver, Timer.STORAGE_KEY, alarmTime.toString())
+ shadowOf(looper).idle()
+
+ setupTimer()
+
+ expect.that(timer).isNotNull()
+ expect.that(callback_count).isEqualTo(0)
+ expectStorageTime()
+ }
+
+ @Test
+ fun setupTimer_whenSaveTimerIsExpired_triggerCallback() {
+ val pastTime = timerTarget.minusDays(3)
+ Settings.Secure.putString(resolver, Timer.STORAGE_KEY, pastTime.toString())
+ shadowOf(looper).idle()
+
+ setupTimer()
+
+ expect.that(timer).isNull()
+ expect.that(callback_count).isEqualTo(1)
+ expectNoStorageTime()
+ }
+
+ @Test
+ fun setupTimer_whenSatelliteIsOn_isNotScheduled() {
+ val satelliteCallback: (m: Boolean) -> Unit = { _: Boolean -> }
+
+ SatelliteListener.setupSatelliteModeToOn(resolver, looper, satelliteCallback)
+ assertThat(isSatelliteModeOn).isTrue()
+
+ setupTimer()
+
+ SatelliteListener.setupSatelliteModeToOff(resolver, looper)
+ expect.that(timer).isNull()
+ expect.that(callback_count).isEqualTo(0)
+ expectNoStorageTime()
+ }
+
+ @Test
+ fun updateTimezone_whenTimerSchedule_isReScheduled() {
+ setupTimer()
+
+ // Fake storaged time so when receiving the intent, the test think we jump in the futur
+ val pastTime = timerTarget.minusDays(3)
+ Settings.Secure.putString(resolver, Timer.STORAGE_KEY, pastTime.toString())
+
+ context.sendBroadcast(Intent(Intent.ACTION_TIMEZONE_CHANGED))
+ shadowOf(looper).idle()
+
+ expect.that(timer).isNull()
+ expect.that(callback_count).isEqualTo(1)
+ expectNoStorageTime()
+ }
+
+ @Test
+ fun updateTime_whenTimerSchedule_isReScheduled() {
+ setupTimer()
+
+ // Fake stored time so when receiving the intent, the test think we jumped in the future
+ val pastTime = timerTarget.minusDays(3)
+ Settings.Secure.putString(resolver, Timer.STORAGE_KEY, pastTime.toString())
+
+ context.sendBroadcast(Intent(Intent.ACTION_TIME_CHANGED))
+ shadowOf(looper).idle()
+
+ expect.that(timer).isNull()
+ expect.that(callback_count).isEqualTo(1)
+ expectNoStorageTime()
+ }
+
+ @Test
+ fun updateDate_whenTimerSchedule_isReScheduled() {
+ setupTimer()
+
+ // Fake stored time so when receiving the intent, the test think we jumped in the future
+ val pastTime = timerTarget.minusDays(3)
+ Settings.Secure.putString(resolver, Timer.STORAGE_KEY, pastTime.toString())
+
+ context.sendBroadcast(Intent(Intent.ACTION_DATE_CHANGED))
+ shadowOf(looper).idle()
+
+ expect.that(timer).isNull()
+ expect.that(callback_count).isEqualTo(1)
+ expectNoStorageTime()
+ }
+
+ @Test
+ @kotlin.time.ExperimentalTime
+ fun setupTimer_whenLegacyAirplaneIsOn_isNotSchedule() {
+ val userCallback: () -> Context = { -> context }
+ AirplaneListener.setupAirplaneModeToOn(resolver, looper, userCallback, false)
+ assertThat(isAirplaneModeOn).isTrue()
+
+ setupTimer()
+
+ AirplaneListener.setupAirplaneModeToOff(resolver, looper)
+ expect.that(timer).isNull()
+ expect.that(callback_count).isEqualTo(0)
+ expectNoStorageTime()
+ }
+
+ @Test
+ @kotlin.time.ExperimentalTime
+ fun setupTimer_whenApmAirplaneIsOn_isSchedule() {
+ val userCallback: () -> Context = { -> context }
+ AirplaneListener.setupAirplaneModeToOn(resolver, looper, userCallback, true)
+ assertThat(isAirplaneModeOn).isTrue()
+
+ setupTimer()
+
+ AirplaneListener.setupAirplaneModeToOff(resolver, looper)
+ expect.that(timer).isNotNull()
+ expect.that(callback_count).isEqualTo(0)
+ expectStorageTime()
+ }
+
+ @Test
+ fun registerHiddenListener_whenNothing_isRegistered() {
+ registerHiddenApiListener(looper, context, state, this::callback_on)
+
+ assertThat(HiddenApiListener.listener).isNotNull()
+ }
+
+ @Test
+ fun unregisterHiddenListener_whenRegistered_isNotRegistered() {
+ registerHiddenApiListener(looper, context, state, this::callback_on)
+
+ HiddenApiListener.listener?.let { it.remove() }
+
+ assertThat(shadowOf(resolver).getContentObservers(SETTING_URI).size).isEqualTo(0)
+ }
+
+ @Test
+ fun registerHiddenListener_whenAlreadyRegistered_isRegisteredOnce() {
+ registerHiddenApiListener(looper, context, state, this::callback_on)
+
+ registerHiddenApiListener(looper, context, state, this::callback_on)
+
+ expect.that(shadowOf(resolver).getContentObservers(SETTING_URI).size).isEqualTo(1)
+ expect.that(HiddenApiListener.listener).isNotNull()
+ }
+
+ @Test
+ fun changeSettingsToDisabled_whenHiddenApiIsRegisteredandNotScheduled_isNotSchedule() {
+ registerHiddenApiListener(looper, context, state, this::callback_on)
+
+ disableUserSettings()
+
+ expect.that(timer).isNull()
+ expect.that(callback_count).isEqualTo(0)
+ expectNoStorageTime()
+ }
+
+ @Test
+ fun changeSettingsToDisabled_whenHiddenApiIsRegisteredandScheduled_isNotSchedule() {
+ setupTimer()
+ registerHiddenApiListener(looper, context, state, this::callback_on)
+
+ disableUserSettings()
+
+ expect.that(timer).isNull()
+ expect.that(callback_count).isEqualTo(0)
+ expectNoStorageTime()
+ }
+
+ @Test
+ fun changeSettingsToEnabled_whenHiddenApiIsRegisteredandNotScheduled_isSchedule() {
+ disableUserSettings()
+ registerHiddenApiListener(looper, context, state, this::callback_on)
+
+ enableUserSettings()
+
+ expect.that(timer).isNotNull()
+ expect.that(callback_count).isEqualTo(0)
+ expectStorageTime()
+ }
+
+ @Test
+ fun setSettingsToSameValue_whenHiddenApiIsRegisteredandNotScheduled_isNotSchedule() {
+ restoreSettings()
+ registerHiddenApiListener(looper, context, state, this::callback_on)
+
+ Settings.Secure.putInt(resolver, USER_SETTINGS_KEY, -1)
+ shadowOf(looper).idle()
+
+ expect.that(timer).isNull()
+ expect.that(callback_count).isEqualTo(0)
+ expectNoStorageTime()
+ }
+
+ @Test
+ fun setSettingsToEnabled_whenHiddenApiIsRegisteredandNotSupported_isNotSchedule() {
+ restoreSettings()
+ registerHiddenApiListener(looper, context, state, this::callback_on)
+
+ enableUserSettings()
+
+ expect.that(timer).isNull()
+ expect.that(callback_count).isEqualTo(0)
+ expectNoStorageTime()
+ }
+
+ @Test
+ fun setSettingsToDisable_whenHiddenApiIsRegisteredandNotSupported_isNotSchedule() {
+ // Current design will set the feature to enabled, but there is no reason to not support
+ // having a default value to disabled
+ restoreSettings()
+ registerHiddenApiListener(looper, context, state, this::callback_on)
+
+ disableUserSettings()
+
+ expect.that(timer).isNull()
+ expect.that(callback_count).isEqualTo(0)
+ expectNoStorageTime()
+ }
+}
diff --git a/service/src/airplane/ModeListener.kt b/service/src/airplane/ModeListener.kt
index 70b3fd1..2d92e6c 100644
--- a/service/src/airplane/ModeListener.kt
+++ b/service/src/airplane/ModeListener.kt
@@ -161,7 +161,7 @@
return currentAirplaneMode
}
// If "Airplane Enhancement Mode" is on and the user already used the feature …
- if (isApmEnhancementEnabled(resolver) && hasUserToggledApm(getUser)) {
+ if (isApmEnhancementEnabled(resolver) && hasUserToggledApm(getUser())) {
// … Staying on only depend on its last action in airplane mode
if (isBluetoothOnAPM(getUser)) {
Log.i(TAG, "Bluetooth stay on during airplane mode because of last user action")
@@ -299,7 +299,7 @@
isBluetoothOnBeforeApmToggle,
isBluetoothOnAfterApmToggle,
isBluetoothOn,
- hasUserToggledApm(getUser),
+ hasUserToggledApm(getUser()),
userToggledBluetoothDuringApm,
userToggledBluetoothDuringApmWithinMinute,
isMediaProfileConnectedBeforeApmToggle,
@@ -344,8 +344,8 @@
Settings.Secure.getInt(getUser().contentResolver, WIFI_APM_STATE, 0) == 1
/** Airplane Enhancement Mode: Return true if this user already toggled (aka used) the feature */
-private fun hasUserToggledApm(getUser: () -> Context) =
- Settings.Secure.getInt(getUser().contentResolver, APM_USER_TOGGLED_BLUETOOTH, 0) == 1
+fun hasUserToggledApm(userContext: Context) =
+ Settings.Secure.getInt(userContext.contentResolver, APM_USER_TOGGLED_BLUETOOTH, 0) == 1
/** Airplane Enhancement Mode: Return true if the bluetooth should stays on during airplane mode */
private fun isBluetoothOnAPM(getUser: () -> Context) =
diff --git a/service/src/airplane/ModeListenerTest.kt b/service/src/airplane/ModeListenerTest.kt
index 2180cc4..aeb1cb6 100644
--- a/service/src/airplane/ModeListenerTest.kt
+++ b/service/src/airplane/ModeListenerTest.kt
@@ -56,6 +56,40 @@
@RunWith(RobolectricTestRunner::class)
@kotlin.time.ExperimentalTime
class ModeListenerTest {
+ companion object {
+ internal fun setupAirplaneModeToOn(
+ resolver: ContentResolver,
+ looper: Looper,
+ user: () -> Context,
+ enableEnhancedMode: Boolean
+ ) {
+ enableSensitive(resolver, looper, Settings.Global.AIRPLANE_MODE_RADIOS)
+ enableMode(resolver, looper, Settings.Global.AIRPLANE_MODE_ON)
+ val mode: (m: Boolean) -> Unit = { _: Boolean -> }
+ val notif: (m: String) -> Unit = { _: String -> }
+ val media: () -> Boolean = { -> false }
+ if (enableEnhancedMode) {
+ Settings.Secure.putInt(resolver, APM_USER_TOGGLED_BLUETOOTH, 1)
+ }
+
+ initialize(
+ looper,
+ resolver,
+ BluetoothAdapterState(),
+ mode,
+ notif,
+ media,
+ user,
+ TimeSource.Monotonic,
+ )
+ }
+
+ internal fun setupAirplaneModeToOff(resolver: ContentResolver, looper: Looper) {
+ disableSensitive(resolver, looper, Settings.Global.AIRPLANE_MODE_RADIOS)
+ disableMode(resolver, looper, Settings.Global.AIRPLANE_MODE_ON)
+ }
+ }
+
private val looper: Looper = Looper.getMainLooper()
private val state = BluetoothAdapterState()
private val mContext = ApplicationProvider.getApplicationContext<Context>()
diff --git a/service/src/com/android/server/bluetooth/BluetoothManagerService.java b/service/src/com/android/server/bluetooth/BluetoothManagerService.java
index 32497dd..13172e8 100644
--- a/service/src/com/android/server/bluetooth/BluetoothManagerService.java
+++ b/service/src/com/android/server/bluetooth/BluetoothManagerService.java
@@ -25,6 +25,7 @@
import static android.bluetooth.BluetoothAdapter.STATE_TURNING_ON;
import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED;
+import static com.android.modules.utils.build.SdkLevel.isAtLeastV;
import static com.android.server.bluetooth.BluetoothAirplaneModeListener.APM_ENHANCEMENT;
import static java.util.Objects.requireNonNull;
@@ -77,6 +78,7 @@
import com.android.bluetooth.flags.Flags;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.modules.expresslog.Counter;
import com.android.server.BluetoothManagerServiceDumpProto;
import com.android.server.bluetooth.airplane.AirplaneModeListener;
import com.android.server.bluetooth.satellite.SatelliteModeListener;
@@ -435,7 +437,7 @@
intent.setComponent(resolveSystemService(intent));
intent.putExtra(
"android.bluetooth.notification.extra.NOTIFICATION_REASON", notificationReason);
- mContext.startService(intent);
+ mCurrentUserContext.startService(intent);
return Unit.INSTANCE;
}
@@ -506,6 +508,10 @@
// Clear registered LE apps to force shut-off
clearBleApps();
+ if (!AirplaneModeListener.hasUserToggledApm(mCurrentUserContext)) {
+ AutoOnFeature.pause();
+ }
+
// If state is BLE_ON make sure we trigger stopBle
if (st == STATE_BLE_ON) {
mAdapterLock.readLock().lock();
@@ -534,6 +540,8 @@
mQuietEnableExternal,
BluetoothProtoEnums.ENABLE_DISABLE_REASON_AIRPLANE_MODE,
mContext.getPackageName());
+ } else if (st != STATE_ON) {
+ autoOnSetupTimer();
}
}
}
@@ -545,9 +553,14 @@
BluetoothProtoEnums.ENABLE_DISABLE_REASON_SATELLITE_MODE,
mContext.getPackageName());
} else if (!shouldBluetoothBeOn(isSatelliteModeOn) && getState() != STATE_OFF) {
+ AutoOnFeature.pause();
sendDisableMsg(
BluetoothProtoEnums.ENABLE_DISABLE_REASON_SATELLITE_MODE,
mContext.getPackageName());
+ } else if (!isSatelliteModeOn
+ && !shouldBluetoothBeOn(isSatelliteModeOn)
+ && getState() != STATE_ON) {
+ autoOnSetupTimer();
}
}
@@ -737,6 +750,18 @@
mBluetoothSatelliteModeListener =
new BluetoothSatelliteModeListener(this, mLooper, mContext);
}
+
+ { // AutoOn feature initialization of flag guarding
+ final boolean autoOnFlag = Flags.autoOnFeature();
+ final boolean autoOnProperty =
+ SystemProperties.getBoolean("bluetooth.server.automatic_turn_on", false);
+ Log.d(TAG, "AutoOnFeature status: flag=" + autoOnFlag + ", property=" + autoOnProperty);
+
+ mDeviceConfigAllowAutoOn = autoOnFlag && autoOnProperty;
+ if (mDeviceConfigAllowAutoOn) {
+ Counter.logIncrement("bluetooth.value_auto_on_supported");
+ }
+ }
}
IBluetoothManager.Stub getBinder() {
@@ -1176,6 +1201,17 @@
}
}
+ private Unit enableFromAutoOn() {
+ if (isBluetoothDisallowed()) {
+ Log.d(TAG, "Bluetooth is not allowed, preventing AutoOn");
+ return Unit.INSTANCE;
+ }
+ Counter.logIncrement("bluetooth.value_auto_on_triggered");
+ sendToggleNotification("auto_on_bt_enabled_notification");
+ enable("BluetoothSystemServer/AutoOn");
+ return Unit.INSTANCE;
+ }
+
boolean enableNoAutoConnect(String packageName) {
if (isSatelliteModeOn()) {
Log.d(TAG, "enableNoAutoConnect(" + packageName + "): Blocked by satellite mode");
@@ -1336,8 +1372,12 @@
} else if (!isNameAndAddressSet()) {
Log.i(TAG, "internalHandleOnBootPhase: Getting adapter name and address");
mHandler.sendEmptyMessage(MESSAGE_GET_NAME_AND_ADDRESS);
+ } else {
+ autoOnSetupTimer();
}
+ autoOnHiddenListener();
+
if (!mUseNewAirplaneMode) {
mBluetoothAirplaneModeListener.start(new BluetoothModeChangeHelper(mContext));
setApmEnhancementState();
@@ -1936,6 +1976,8 @@
mBluetoothNotificationManager.createNotificationChannels();
}
+ AutoOnFeature.pause();
+
mCurrentUserContext = mContext.createContextAsUser(userTo, 0);
/* disable and enable BT when detect a user switch */
@@ -1953,7 +1995,12 @@
+ (" number of retry attempt=" + userMsg.arg1)
+ (" isBinding=" + isBinding())
+ (" mAdapter=" + mAdapter));
+ } else {
+ autoOnSetupTimer();
}
+
+ autoOnHiddenListener();
+
break;
case MESSAGE_USER_UNLOCKED:
@@ -2129,8 +2176,15 @@
return;
}
+ if (prevState == STATE_ON) {
+ autoOnSetupTimer();
+ }
+
// Notify all proxy objects first of adapter state change
if (newState == STATE_ON) {
+ if (mDeviceConfigAllowAutoOn) {
+ AutoOnFeature.notifyBluetoothOn(mCurrentUserContext.getContentResolver());
+ }
sendBluetoothOnCallback();
} else if (newState == STATE_OFF) {
// If Bluetooth is off, send service down event to proxy objects, and unbind
@@ -2640,6 +2694,57 @@
return BluetoothAdapter.BT_SNOOP_LOG_MODE_DISABLED;
}
+ private final boolean mDeviceConfigAllowAutoOn;
+
+ private void autoOnSetupTimer() {
+ if (!mDeviceConfigAllowAutoOn) {
+ Log.d(TAG, "No support for AutoOn feature: Not creating a timer");
+ return;
+ }
+ AutoOnFeature.resetAutoOnTimerForUser(
+ mLooper, mCurrentUserContext, mState, this::enableFromAutoOn);
+ }
+
+ private void autoOnHiddenListener() {
+ if (!mDeviceConfigAllowAutoOn) {
+ Log.d(TAG, "No support for AutoOn feature: Not listening on hidden api");
+ return;
+ }
+ if (isAtLeastV()) {
+ Log.d(TAG, "AutoOn feature: prevent listening on hidden api. Use proper API in V+");
+ return;
+ }
+ AutoOnFeature.registerHiddenApiListener(
+ mLooper, mCurrentUserContext, mState, this::enableFromAutoOn);
+ }
+
+ boolean isAutoOnSupported() {
+ return mDeviceConfigAllowAutoOn
+ && AutoOnFeature.isUserSupported(mCurrentUserContext.getContentResolver());
+ }
+
+ boolean isAutoOnEnabled() {
+ if (!mDeviceConfigAllowAutoOn) {
+ throw new IllegalStateException("AutoOnFeature is not supported in current config");
+ }
+ return AutoOnFeature.isUserEnabled(mCurrentUserContext);
+ }
+
+ void setAutoOnEnabled(boolean status) {
+ if (!mDeviceConfigAllowAutoOn) {
+ throw new IllegalStateException("AutoOnFeature is not supported in current config");
+ }
+ // Call coming from binder thread need to be posted before exec
+ mHandler.post(
+ () ->
+ AutoOnFeature.setUserEnabled(
+ mLooper,
+ mCurrentUserContext,
+ mState,
+ status,
+ this::enableFromAutoOn));
+ }
+
/**
* Check if BLE is supported by this platform
*
diff --git a/service/src/com/android/server/bluetooth/BluetoothServiceBinder.java b/service/src/com/android/server/bluetooth/BluetoothServiceBinder.java
index 3ba66d0..99d94e7 100644
--- a/service/src/com/android/server/bluetooth/BluetoothServiceBinder.java
+++ b/service/src/com/android/server/bluetooth/BluetoothServiceBinder.java
@@ -322,6 +322,27 @@
}
@Override
+ @RequiresPermission(BLUETOOTH_PRIVILEGED)
+ public boolean isAutoOnSupported() {
+ BtPermissionUtils.enforcePrivileged(mContext);
+ return mBluetoothManagerService.isAutoOnSupported();
+ }
+
+ @Override
+ @RequiresPermission(BLUETOOTH_PRIVILEGED)
+ public boolean isAutoOnEnabled() {
+ BtPermissionUtils.enforcePrivileged(mContext);
+ return mBluetoothManagerService.isAutoOnEnabled();
+ }
+
+ @Override
+ @RequiresPermission(BLUETOOTH_PRIVILEGED)
+ public void setAutoOnEnabled(boolean status) {
+ BtPermissionUtils.enforcePrivileged(mContext);
+ mBluetoothManagerService.setAutoOnEnabled(status);
+ }
+
+ @Override
@RequiresPermission(DUMP)
public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
if (mContext.checkCallingOrSelfPermission(DUMP) != PERMISSION_GRANTED) {
diff --git a/service/src/satellite/ModeListenerTest.kt b/service/src/satellite/ModeListenerTest.kt
index f3adeeaf..f3d858d 100644
--- a/service/src/satellite/ModeListenerTest.kt
+++ b/service/src/satellite/ModeListenerTest.kt
@@ -40,6 +40,24 @@
@RunWith(RobolectricTestRunner::class)
class ModeListenerTest {
+ companion object {
+ internal fun setupSatelliteModeToOn(
+ resolver: ContentResolver,
+ looper: Looper,
+ callback: (m: Boolean) -> Unit
+ ) {
+ enableSensitive(resolver, looper, SETTINGS_SATELLITE_MODE_RADIOS)
+ enableMode(resolver, looper, SETTINGS_SATELLITE_MODE_ENABLED)
+
+ initialize(looper, resolver, callback)
+ }
+
+ internal fun setupSatelliteModeToOff(resolver: ContentResolver, looper: Looper) {
+ disableSensitive(resolver, looper, SETTINGS_SATELLITE_MODE_RADIOS)
+ disableMode(resolver, looper, SETTINGS_SATELLITE_MODE_ENABLED)
+ }
+ }
+
private val resolver: ContentResolver =
ApplicationProvider.getApplicationContext<Context>().getContentResolver()
@JvmField @Rule val testName = TestName()
diff --git a/sysprop/ble.sysprop b/sysprop/ble.sysprop
index 50723897..ad2208f 100644
--- a/sysprop/ble.sysprop
+++ b/sysprop/ble.sysprop
@@ -8,3 +8,19 @@
access: Readonly
prop_name: "bluetooth.ble.vnd.included"
}
+
+prop {
+ api_name: "random_address_rotation_interval_min"
+ type: Integer
+ scope: Internal
+ access: Readonly
+ prop_name: "bluetooth.ble.random_address_rotation_interval_min"
+}
+
+prop {
+ api_name: "random_address_rotation_interval_max"
+ type: Integer
+ scope: Internal
+ access: Readonly
+ prop_name: "bluetooth.ble.random_address_rotation_interval_max"
+}
diff --git a/system/audio_hal_interface/Android.bp b/system/audio_hal_interface/Android.bp
index 96d05bf..ffa646d 100644
--- a/system/audio_hal_interface/Android.bp
+++ b/system/audio_hal_interface/Android.bp
@@ -101,6 +101,7 @@
shared_libs: [
"android.hardware.bluetooth.audio@2.0",
"android.hardware.bluetooth.audio@2.1",
+ "libbase",
"libbinder_ndk",
"libcutils",
"libfmq",
@@ -174,6 +175,7 @@
],
shared_libs: [
"libbase",
+ "libbase",
"libcutils",
"libfmq",
"liblog",
@@ -182,6 +184,7 @@
],
static_libs: [
"bluetooth_flags_c_lib",
+ "libbluetooth_log",
"libbt-common",
"libbt_shim_bridge",
"libchrome",
diff --git a/system/audio_hal_interface/BUILD.gn b/system/audio_hal_interface/BUILD.gn
index 93f3de5..2d56ef3 100644
--- a/system/audio_hal_interface/BUILD.gn
+++ b/system/audio_hal_interface/BUILD.gn
@@ -28,7 +28,10 @@
"//bt/system/gd/rust/shim",
]
- configs += [ "//bt/system:target_defaults" ]
+ configs += [
+ "//bt/system:target_defaults",
+ "//bt/system/log:log_defaults",
+ ]
deps = [
"//bt/system/common",
diff --git a/system/audio_hal_interface/aidl/a2dp_encoding_aidl.cc b/system/audio_hal_interface/aidl/a2dp_encoding_aidl.cc
index 8ea0c32..a929d80 100644
--- a/system/audio_hal_interface/aidl/a2dp_encoding_aidl.cc
+++ b/system/audio_hal_interface/aidl/a2dp_encoding_aidl.cc
@@ -762,7 +762,7 @@
case ChannelMode::MONO:
return BTAV_A2DP_CODEC_CHANNEL_MODE_MONO;
case ChannelMode::STEREO:
- return BTAV_A2DP_CODEC_CHANNEL_MODE_MONO;
+ return BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO;
default:
LOG(ERROR) << "unknown channel mode";
break;
diff --git a/system/audio_hal_interface/aidl/a2dp_encoding_aidl.h b/system/audio_hal_interface/aidl/a2dp_encoding_aidl.h
index e94cecf..bc61579 100644
--- a/system/audio_hal_interface/aidl/a2dp_encoding_aidl.h
+++ b/system/audio_hal_interface/aidl/a2dp_encoding_aidl.h
@@ -26,7 +26,7 @@
#include "btif/include/btif_av_co.h"
#include "btif/include/btif_hf.h"
#include "common/message_loop_thread.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#include "osi/include/properties.h"
#include "types/raw_address.h"
diff --git a/system/audio_hal_interface/aidl/a2dp_provider_info.cc b/system/audio_hal_interface/aidl/a2dp_provider_info.cc
index 4440085..f7ecca8 100644
--- a/system/audio_hal_interface/aidl/a2dp_provider_info.cc
+++ b/system/audio_hal_interface/aidl/a2dp_provider_info.cc
@@ -32,7 +32,7 @@
#include "a2dp_vendor_ldac_constants.h"
#include "a2dp_vendor_opus_constants.h"
#include "client_interface_aidl.h"
-#include "osi/include/log.h"
+#include "os/log.h"
namespace bluetooth::audio::aidl::a2dp {
diff --git a/system/audio_hal_interface/aidl/hearing_aid_software_encoding_aidl.cc b/system/audio_hal_interface/aidl/hearing_aid_software_encoding_aidl.cc
index e804270..e6fbd16 100644
--- a/system/audio_hal_interface/aidl/hearing_aid_software_encoding_aidl.cc
+++ b/system/audio_hal_interface/aidl/hearing_aid_software_encoding_aidl.cc
@@ -20,7 +20,7 @@
#include "audio_hearing_aid_hw/include/audio_hearing_aid_hw.h"
#include "client_interface_aidl.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#include "osi/include/properties.h"
namespace {
diff --git a/system/audio_hal_interface/aidl/le_audio_software_aidl.cc b/system/audio_hal_interface/aidl/le_audio_software_aidl.cc
index 08033e9..87cf547 100644
--- a/system/audio_hal_interface/aidl/le_audio_software_aidl.cc
+++ b/system/audio_hal_interface/aidl/le_audio_software_aidl.cc
@@ -25,7 +25,7 @@
#include "codec_status_aidl.h"
#include "hal_version_manager.h"
-#include "osi/include/log.h"
+#include "os/log.h"
namespace bluetooth {
namespace audio {
diff --git a/system/audio_hal_interface/fuzzer/Android.bp b/system/audio_hal_interface/fuzzer/Android.bp
index fa21731..2c4e144 100644
--- a/system/audio_hal_interface/fuzzer/Android.bp
+++ b/system/audio_hal_interface/fuzzer/Android.bp
@@ -82,6 +82,7 @@
"libcgrouprc",
"libcgrouprc_format",
"libchrome",
+ "libcom.android.sysprop.bluetooth.wrapped",
"libcutils",
"libevent",
"libg722codec",
diff --git a/system/audio_hal_interface/hfp_client_interface.cc b/system/audio_hal_interface/hfp_client_interface.cc
index bd34d36..5a42fa2 100644
--- a/system/audio_hal_interface/hfp_client_interface.cc
+++ b/system/audio_hal_interface/hfp_client_interface.cc
@@ -22,7 +22,7 @@
#include "aidl/hfp_client_interface_aidl.h"
#include "hal_version_manager.h"
#include "hfp_client_interface.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#include "osi/include/properties.h"
using ::bluetooth::audio::aidl::hfp::HfpDecodingTransport;
diff --git a/system/audio_hal_interface/hidl/hearing_aid_software_encoding_hidl.cc b/system/audio_hal_interface/hidl/hearing_aid_software_encoding_hidl.cc
index 9599cc9..48abb4a 100644
--- a/system/audio_hal_interface/hidl/hearing_aid_software_encoding_hidl.cc
+++ b/system/audio_hal_interface/hidl/hearing_aid_software_encoding_hidl.cc
@@ -20,7 +20,7 @@
#include "audio_hearing_aid_hw/include/audio_hearing_aid_hw.h"
#include "client_interface_hidl.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#include "osi/include/properties.h"
namespace {
diff --git a/system/audio_hal_interface/hidl/le_audio_software_hidl.cc b/system/audio_hal_interface/hidl/le_audio_software_hidl.cc
index d938c69..8bc4b6a 100644
--- a/system/audio_hal_interface/hidl/le_audio_software_hidl.cc
+++ b/system/audio_hal_interface/hidl/le_audio_software_hidl.cc
@@ -19,7 +19,7 @@
#include "le_audio_software_hidl.h"
-#include "osi/include/log.h"
+#include "os/log.h"
namespace bluetooth {
namespace audio {
diff --git a/system/audio_hal_interface/le_audio_software.cc b/system/audio_hal_interface/le_audio_software.cc
index 35a85d4..6a999e9 100644
--- a/system/audio_hal_interface/le_audio_software.cc
+++ b/system/audio_hal_interface/le_audio_software.cc
@@ -28,7 +28,7 @@
#include "bta/le_audio/codec_manager.h"
#include "hal_version_manager.h"
#include "hidl/le_audio_software_hidl.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#include "osi/include/properties.h"
namespace bluetooth {
diff --git a/system/bta/Android.bp b/system/bta/Android.bp
index fcaae40..7528526 100644
--- a/system/bta/Android.bp
+++ b/system/bta/Android.bp
@@ -237,6 +237,7 @@
":TestMockBtif",
":TestMockDevice",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
":TestMockStackA2dp",
":TestMockStackAcl",
":TestMockStackAvct",
@@ -333,6 +334,7 @@
":TestMockBtif",
":TestMockDevice",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
":TestMockStackBtm",
":TestMockStackL2cap",
":TestMockStackMetrics",
@@ -386,8 +388,6 @@
"test/bta_hf_client_security_test.cc",
],
shared_libs: [
- "android.hardware.bluetooth.audio@2.0",
- "android.hardware.bluetooth.audio@2.1",
"libcrypto",
"libcutils",
"liblog",
@@ -828,6 +828,7 @@
":TestCommonMockFunctions",
":TestMockBtaLeAudioHalVerifier",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
":TestMockStackL2cap",
":TestStubOsi",
"le_audio/audio_hal_client/audio_hal_client_test.cc",
@@ -921,6 +922,7 @@
":TestCommonMockFunctions",
":TestMockBtaLeAudioHalVerifier",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
":TestMockStackL2cap",
":TestStubOsi",
"gatt/database.cc",
@@ -1225,6 +1227,7 @@
":TestMockBtif",
":TestMockDevice",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
":TestMockOsi",
":TestMockStack",
"gatt/bta_gattc_queue.cc",
diff --git a/system/bta/ag/bta_ag_act.cc b/system/bta/ag/bta_ag_act.cc
index 1089248..a79e078 100644
--- a/system/bta/ag/bta_ag_act.cc
+++ b/system/bta/ag/bta_ag_act.cc
@@ -40,13 +40,13 @@
#include "btif/include/btif_config.h"
#include "device/include/device_iot_config.h"
-#include "gd/storage/config_keys.h"
#include "osi/include/osi.h" // UNUSED_ATTR
#include "stack/include/bt_uuid16.h"
#include "stack/include/btm_sec_api_types.h"
#include "stack/include/l2c_api.h"
#include "stack/include/port_api.h"
#include "stack/include/sdp_api.h"
+#include "storage/config_keys.h"
#include "types/raw_address.h"
using namespace bluetooth::legacy::stack::sdp;
diff --git a/system/bta/ag/bta_ag_sdp.cc b/system/bta/ag/bta_ag_sdp.cc
index 52b8279..bbc6b71 100644
--- a/system/bta/ag/bta_ag_sdp.cc
+++ b/system/bta/ag/bta_ag_sdp.cc
@@ -34,7 +34,6 @@
#include "common/init_flags.h"
#include "device/include/interop.h"
#include "device/include/interop_config.h"
-#include "gd/storage/config_keys.h"
#include "internal_include/bt_target.h"
#include "os/log.h"
#include "osi/include/allocator.h"
@@ -44,6 +43,7 @@
#include "stack/include/bt_uuid16.h"
#include "stack/include/main_thread.h"
#include "stack/include/sdp_api.h"
+#include "storage/config_keys.h"
#include "types/bluetooth/uuid.h"
using namespace bluetooth::legacy::stack::sdp;
diff --git a/system/bta/av/bta_av_aact.cc b/system/bta/av/bta_av_aact.cc
index b66c9b4..5b19102 100644
--- a/system/bta/av/bta_av_aact.cc
+++ b/system/bta/av/bta_av_aact.cc
@@ -42,7 +42,6 @@
#include "btif/include/btif_storage.h"
#include "device/include/device_iot_config.h"
#include "device/include/interop.h"
-#include "gd/storage/config_keys.h"
#include "include/check.h"
#include "internal_include/bt_target.h"
#include "osi/include/allocator.h"
@@ -58,6 +57,7 @@
#include "stack/include/btm_client_interface.h"
#include "stack/include/btm_log_history.h"
#include "stack/include/l2c_api.h"
+#include "storage/config_keys.h"
#include "types/hci_role.h"
#include "types/raw_address.h"
diff --git a/system/bta/av/bta_av_cfg.cc b/system/bta/av/bta_av_cfg.cc
index 69a490e..c76d1ef 100644
--- a/system/bta/av/bta_av_cfg.cc
+++ b/system/bta/av/bta_av_cfg.cc
@@ -44,7 +44,6 @@
#define BTA_AVK_RC_SUPF_CT \
(AVRC_SUPF_CT_CAT1 | AVRC_SUPF_CT_BROWSE | \
AVRC_SUPF_CT_COVER_ART_GET_IMAGE_PROP | AVRC_SUPF_CT_COVER_ART_GET_IMAGE)
-#define BTA_AVK_RC_SUPF_CT_V15 (AVRC_SUPF_CT_CAT1 | AVRC_SUPF_CT_BROWSE)
#define BTA_AVK_RC_SUPF_TG (AVRC_SUPF_TG_CAT2)
@@ -140,10 +139,10 @@
const tBTA_AV_CFG* get_bta_avk_cfg() {
static const tBTA_AV_CFG bta_avk_cfg = {
- AVRC_CO_METADATA, /* AVRCP Company ID */
- BTA_AVK_RC_SUPF_CT_V15, /* AVRCP controller categories */
- BTA_AVK_RC_SUPF_TG, /* AVRCP target categories */
- 6, /* AVDTP audio channel max data queue size */
+ AVRC_CO_METADATA, /* AVRCP Company ID */
+ BTA_AVK_RC_SUPF_CT, /* AVRCP controller categories */
+ BTA_AVK_RC_SUPF_TG, /* AVRCP target categories */
+ 6, /* AVDTP audio channel max data queue size */
false, /* true, to accept AVRC 1.3 group nevigation command */
2, /* company id count in p_meta_co_ids */
(uint8_t)(avrcp_absolute_volume_is_enabled()
diff --git a/system/bta/av/bta_av_ci.cc b/system/bta/av/bta_av_ci.cc
index bfa4574..e598805 100644
--- a/system/bta/av/bta_av_ci.cc
+++ b/system/bta/av/bta_av_ci.cc
@@ -26,8 +26,8 @@
#define LOG_TAG "bt_bta_av"
#include "bta/av/bta_av_int.h"
+#include "os/log.h"
#include "osi/include/allocator.h"
-#include "osi/include/log.h"
#include "stack/include/bt_hdr.h"
/*******************************************************************************
diff --git a/system/bta/av/bta_av_main.cc b/system/bta/av/bta_av_main.cc
index 1e825f3..ccdb9b4 100644
--- a/system/bta/av/bta_av_main.cc
+++ b/system/bta/av/bta_av_main.cc
@@ -37,7 +37,6 @@
#include "btif/include/btif_av.h"
#include "btif/include/btif_av_co.h"
#include "btif/include/btif_config.h"
-#include "gd/storage/config_keys.h"
#include "internal_include/bt_target.h"
#include "os/log.h"
#include "osi/include/allocator.h"
@@ -48,6 +47,7 @@
#include "stack/include/bt_uuid16.h"
#include "stack/include/hci_error_code.h"
#include "stack/include/sdp_api.h"
+#include "storage/config_keys.h"
#include "types/hci_role.h"
#include "types/raw_address.h"
diff --git a/system/bta/csis/csis_client.cc b/system/bta/csis/csis_client.cc
index c74e945..9328de7 100644
--- a/system/bta/csis/csis_client.cc
+++ b/system/bta/csis/csis_client.cc
@@ -259,8 +259,6 @@
void Disconnect(const RawAddress& addr) override {
LOG_DEBUG("%s ", ADDRESS_TO_LOGGABLE_CSTR(addr));
- btif_storage_set_csis_autoconnect(addr, false);
-
auto device = FindDeviceByAddress(addr);
if (device == nullptr) {
LOG_WARN("Device not connected to profile %s",
@@ -656,17 +654,26 @@
return group_rank_map;
}
- void AddFromStorage(const RawAddress& addr, const std::vector<uint8_t>& in,
- bool autoconnect) {
+ void StartOpportunisticConnect(const RawAddress& address) {
+ /* Oportunistic works only for direct connect,
+ * but in fact this is background connect
+ */
+ LOG_INFO(": %s ", ADDRESS_TO_LOGGABLE_CSTR(address));
+ BTA_GATTC_Open(gatt_if_, address, BTM_BLE_DIRECT_CONNECTION, true);
+ }
+
+ void AddFromStorage(const RawAddress& addr, const std::vector<uint8_t>& in) {
auto group_rank_map = DeserializeSets(addr, in);
+ LOG_DEBUG(" %s, number of groups %d", ADDRESS_TO_LOGGABLE_CSTR(addr),
+ static_cast<int>(csis_groups_.size()));
+
auto device = FindDeviceByAddress(addr);
if (device == nullptr) {
device = std::make_shared<CsisDevice>(addr, false);
devices_.push_back(device);
}
- bool is_le_audio_device = false;
for (const auto& csis_group : csis_groups_) {
if (!csis_group->IsDeviceInTheGroup(device)) continue;
@@ -680,21 +687,11 @@
callbacks_->OnDeviceAvailable(device->addr, group_id,
csis_group->GetDesiredSize(), rank,
csis_group->GetUuid());
-
- if (csis_group->GetUuid() ==
- bluetooth::Uuid::From16Bit(UUID_COMMON_AUDIO_SERVICE)) {
- is_le_audio_device = true;
- }
}
}
- /* For now, if this is LeAudio device, CSIP is opportunistic profile. */
- bool is_opportunistic = is_le_audio_device;
-
- if (autoconnect) {
- BTA_GATTC_Open(gatt_if_, addr, BTM_BLE_BKG_CONNECT_ALLOW_LIST,
- is_opportunistic);
- }
+ /* For bonded devices, CSIP can be always opportunistic service */
+ StartOpportunisticConnect(addr);
}
void CleanUp() {
@@ -913,11 +910,6 @@
}
}
}
-
- if (device->first_connection) {
- device->first_connection = false;
- btif_storage_set_csis_autoconnect(device->addr, true);
- }
}
void OnGattWriteCcc(uint16_t conn_id, tGATT_STATUS status, uint16_t handle,
@@ -2140,7 +2132,6 @@
if (device->is_gatt_service_valid) {
instance->OnEncrypted(device);
} else {
- device->first_connection = true;
BTA_GATTC_ServiceSearchRequest(device->conn_id, &kCsisServiceUuid);
}
}
@@ -2155,7 +2146,6 @@
/* Invalidate service discovery results */
BtaGattQueue::Clean(device->conn_id);
- device->first_connection = true;
DeregisterNotifications(device);
device->ClearSvcData();
BTA_GATTC_ServiceSearchRequest(device->conn_id, &kCsisServiceUuid);
@@ -2407,14 +2397,13 @@
}
void CsisClient::AddFromStorage(const RawAddress& addr,
- const std::vector<uint8_t>& in,
- bool autoconnect) {
+ const std::vector<uint8_t>& in) {
if (!instance) {
LOG_ERROR("Not initialized yet!");
return;
}
- instance->AddFromStorage(addr, in, autoconnect);
+ instance->AddFromStorage(addr, in);
}
bool CsisClient::GetForStorage(const RawAddress& addr,
diff --git a/system/bta/csis/csis_client_test.cc b/system/bta/csis/csis_client_test.cc
index 6391cfa..d1d7c89 100644
--- a/system/bta/csis/csis_client_test.cc
+++ b/system/bta/csis/csis_client_test.cc
@@ -554,12 +554,8 @@
EXPECT_CALL(*callbacks, OnDeviceAvailable(address, _, _, _, _))
.Times(AtLeast(1));
- /* In testing only whe set info is empty, there is no CAP context. */
- bool is_opportunistic = (storage_buf.size() != 0);
-
EXPECT_CALL(gatt_interface,
- Open(gatt_if, address, BTM_BLE_BKG_CONNECT_ALLOW_LIST,
- is_opportunistic))
+ Open(gatt_if, address, BTM_BLE_DIRECT_CONNECTION, true))
.WillOnce(Invoke([this, conn_id](tGATT_IF client_if,
const RawAddress& remote_bda,
bool is_direct, bool opportunistic) {
@@ -568,7 +564,7 @@
}));
DeviceGroups::AddFromStorage(address, storage_group_buf);
- CsisClient::AddFromStorage(address, storage_buf, true);
+ CsisClient::AddFromStorage(address, storage_buf);
}
void InjectEncryptionEvent(const RawAddress& test_address, uint16_t conn_id) {
@@ -1387,11 +1383,9 @@
ASSERT_EQ(1, get_func_call_count("btif_storage_load_bonded_csis_devices"));
ASSERT_EQ(0, get_func_call_count("btif_storage_update_csis_info"));
- ASSERT_EQ(0, get_func_call_count("btif_storage_set_csis_autoconnect"));
TestConnect(test_address);
InjectConnectedEvent(test_address, 1);
GetSearchCompleteEvent(1);
- ASSERT_EQ(1, get_func_call_count("btif_storage_set_csis_autoconnect"));
ASSERT_EQ(1, get_func_call_count("btif_storage_update_csis_info"));
ASSERT_EQ(0, get_func_call_count("btif_storage_remove_csis_device"));
diff --git a/system/bta/csis/csis_types.h b/system/bta/csis/csis_types.h
index a1dd4da..af0b8cf 100644
--- a/system/bta/csis/csis_types.h
+++ b/system/bta/csis/csis_types.h
@@ -90,12 +90,6 @@
public:
RawAddress addr;
/*
- * This is true only during first connection to profile, until we store the
- * device.
- */
- bool first_connection;
-
- /*
* We are making active attempt to connect to this device, 'direct connect'.
*/
bool connecting_actively = false;
@@ -105,7 +99,7 @@
bool is_gatt_service_valid = false;
GattServiceDevice(const RawAddress& addr, bool first_connection)
- : addr(addr), first_connection(first_connection) {}
+ : addr(addr) {}
GattServiceDevice() : GattServiceDevice(RawAddress::kEmpty, false) {}
diff --git a/system/bta/dm/bta_dm_act.cc b/system/bta/dm/bta_dm_act.cc
index b85ca0c..f8f9616 100644
--- a/system/bta/dm/bta_dm_act.cc
+++ b/system/bta/dm/bta_dm_act.cc
@@ -38,6 +38,7 @@
#include "bta/dm/bta_dm_int.h"
#include "bta/dm/bta_dm_sec_int.h"
#include "bta/include/bta_api.h"
+#include "bta/include/bta_le_audio_api.h"
#include "bta/include/bta_sdp_api.h"
#include "bta/include/bta_sec_api.h"
#include "bta/sys/bta_sys.h"
@@ -1478,6 +1479,67 @@
}
}
+/** This function returns system context info */
+static tBTM_CONTRL_STATE bta_dm_obtain_system_context() {
+ uint32_t total_acl_num = bta_dm_cb.device_list.count;
+ uint32_t sniff_acl_num = BTM_PM_ReadSniffLinkCount();
+ uint32_t le_acl_num = BTM_PM_ReadBleLinkCount();
+ uint32_t active_acl_num = total_acl_num - sniff_acl_num - le_acl_num;
+ uint32_t le_adv_num =
+ bluetooth::shim::BTM_BleGetNumberOfAdvertisingInstancesInUse();
+ uint32_t le_scan_duty_cycle = BTM_PM_ReadBleScanDutyCycle();
+ bool is_inquiry_active = BTM_PM_DeviceInScanState();
+ bool is_le_audio_active = LeAudioClient::IsLeAudioClientInStreaming();
+ bool is_av_active = false;
+ bool is_sco_active = false;
+
+ for (int i = 0; i < bta_dm_cb.device_list.count; i++) {
+ tBTA_DM_PEER_DEVICE* p_dev = &bta_dm_cb.device_list.peer_device[i];
+ if (p_dev->conn_state == BTA_DM_CONNECTED && p_dev->is_av_active()) {
+ is_av_active = true;
+ break;
+ }
+ }
+ for (int j = 0; j < bta_dm_conn_srvcs.count; j++) {
+ /* check for SCO connected index */
+ if (bta_dm_conn_srvcs.conn_srvc[j].id == BTA_ID_AG ||
+ bta_dm_conn_srvcs.conn_srvc[j].id == BTA_ID_HS) {
+ if (bta_dm_conn_srvcs.conn_srvc[j].state == BTA_SYS_SCO_OPEN) {
+ is_sco_active = true;
+ break;
+ }
+ }
+ }
+
+ tBTM_CONTRL_STATE ctrl_state = 0;
+ set_num_acl_active_to_ctrl_state(active_acl_num, ctrl_state);
+ set_num_acl_sniff_to_ctrl_state(sniff_acl_num, ctrl_state);
+ set_num_acl_le_to_ctrl_state(le_acl_num, ctrl_state);
+ set_num_le_adv_to_ctrl_state(le_adv_num, ctrl_state);
+ set_le_scan_mode_to_ctrl_state(le_scan_duty_cycle, ctrl_state);
+
+ if (is_inquiry_active) {
+ ctrl_state |= BTM_CONTRL_INQUIRY;
+ }
+ if (is_sco_active) {
+ ctrl_state |= BTM_CONTRL_SCO;
+ }
+ if (is_av_active) {
+ ctrl_state |= BTM_CONTRL_A2DP;
+ }
+ if (is_le_audio_active) {
+ ctrl_state |= BTM_CONTRL_LE_AUDIO;
+ }
+ LOG_DEBUG(
+ "active_acl_num %d sniff_acl_num %d le_acl_num %d le_adv_num %d "
+ "le_scan_duty %d inquiry %d sco %d a2dp %d le_audio %d ctrl_state "
+ "0x%" PRIx32,
+ active_acl_num, sniff_acl_num, le_acl_num, le_adv_num, le_scan_duty_cycle,
+ is_inquiry_active, is_sco_active, is_av_active, is_le_audio_active,
+ ctrl_state);
+ return ctrl_state;
+}
+
/*******************************************************************************
*
* Function bta_ble_enable_scan_cmpl
@@ -1496,7 +1558,11 @@
tBTA_STATUS st = (status == HCI_SUCCESS) ? BTA_SUCCESS : BTA_FAILURE;
tBTM_CONTRL_STATE ctrl_state = BTM_CONTRL_UNKNOWN;
- if (BTA_SUCCESS == st) ctrl_state = bta_dm_pm_obtain_controller_state();
+ if (BTA_SUCCESS == st) {
+ ctrl_state = IS_FLAG_ENABLED(bt_system_context_report)
+ ? bta_dm_obtain_system_context()
+ : bta_dm_pm_obtain_controller_state();
+ }
if (bta_dm_cb.p_energy_info_cback)
bta_dm_cb.p_energy_info_cback(tx_time, rx_time, idle_time, energy_used,
diff --git a/system/bta/dm/bta_dm_disc.cc b/system/bta/dm/bta_dm_disc.cc
index 2313b0f..2874b49 100644
--- a/system/bta/dm/bta_dm_disc.cc
+++ b/system/bta/dm/bta_dm_disc.cc
@@ -35,7 +35,6 @@
#include "common/init_flags.h"
#include "common/strings.h"
#include "device/include/interop.h"
-#include "gd/storage/config_keys.h"
#include "include/bind_helpers.h"
#include "include/check.h"
#include "internal_include/bt_target.h"
@@ -58,6 +57,7 @@
#include "stack/include/hidh_api.h"
#include "stack/include/sdp_status.h"
#include "stack/sdp/sdpint.h" // is_sdp_pbap_pce_disabled
+#include "storage/config_keys.h"
#include "types/raw_address.h"
#ifdef TARGET_FLOSS
diff --git a/system/bta/dm/bta_dm_pm.cc b/system/bta/dm/bta_dm_pm.cc
index fb011e1..6e40ad35 100644
--- a/system/bta/dm/bta_dm_pm.cc
+++ b/system/bta/dm/bta_dm_pm.cc
@@ -938,8 +938,12 @@
/* HH has the per connection SSR preference, already read the SSR params
* from BTA HH */
if (current_ssr_index == BTA_DM_PM_SSR_HH) {
+ tAclLinkSpec link_spec;
+ link_spec.addrt.bda = peer_addr;
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ link_spec.transport = BT_TRANSPORT_BR_EDR;
if (GetInterfaceToProfiles()->profileSpecific_HACK->bta_hh_read_ssr_param(
- peer_addr, &p_spec_cur->max_lat, &p_spec_cur->min_rmt_to) ==
+ link_spec, &p_spec_cur->max_lat, &p_spec_cur->min_rmt_to) ==
BTA_HH_ERR) {
continue;
}
diff --git a/system/bta/gatt/bta_gatts_queue.cc b/system/bta/gatt/bta_gatts_queue.cc
index 33317c6..a7911d8 100644
--- a/system/bta/gatt/bta_gatts_queue.cc
+++ b/system/bta/gatt/bta_gatts_queue.cc
@@ -21,7 +21,7 @@
#include <unordered_set>
#include "bta_gatt_server_queue.h"
-#include "osi/include/log.h"
+#include "os/log.h"
using gatts_operation = BtaGattServerQueue::gatts_operation;
using bluetooth::Uuid;
diff --git a/system/bta/hd/bta_hd_api.cc b/system/bta/hd/bta_hd_api.cc
index 52c0a02..cb89595 100644
--- a/system/bta/hd/bta_hd_api.cc
+++ b/system/bta/hd/bta_hd_api.cc
@@ -30,9 +30,10 @@
#if defined(BTA_HD_INCLUDED) && (BTA_HD_INCLUDED == TRUE)
#include "bta/hd/bta_hd_int.h"
+#include "common/init_flags.h"
+#include "os/log.h"
#include "osi/include/allocator.h"
#include "osi/include/compat.h"
-#include "osi/include/log.h"
#include "stack/include/bt_hdr.h"
#include "types/raw_address.h"
diff --git a/system/bta/hearing_aid/hearing_aid_audio_source.cc b/system/bta/hearing_aid/hearing_aid_audio_source.cc
index 7143dc8..c0d85c9 100644
--- a/system/bta/hearing_aid/hearing_aid_audio_source.cc
+++ b/system/bta/hearing_aid/hearing_aid_audio_source.cc
@@ -29,7 +29,7 @@
#include "bta/include/bta_hearing_aid_api.h"
#include "common/repeating_timer.h"
#include "common/time_util.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#include "osi/include/wakelock.h"
#include "stack/include/main_thread.h"
#include "udrv/include/uipc.h"
diff --git a/system/bta/hf_client/bta_hf_client_at.cc b/system/bta/hf_client/bta_hf_client_at.cc
index 969950a..eefa473 100644
--- a/system/bta/hf_client/bta_hf_client_at.cc
+++ b/system/bta/hf_client/bta_hf_client_at.cc
@@ -21,9 +21,9 @@
#include "bta/hf_client/bta_hf_client_int.h"
#include "internal_include/bt_trace.h"
+#include "os/log.h"
#include "osi/include/allocator.h"
#include "osi/include/compat.h"
-#include "osi/include/log.h"
#include "osi/include/properties.h"
#include "stack/include/acl_api.h"
#include "stack/include/port_api.h"
diff --git a/system/bta/hh/bta_hh_act.cc b/system/bta/hh/bta_hh_act.cc
index 8bd649f..52431f6 100644
--- a/system/bta/hh/bta_hh_act.cc
+++ b/system/bta/hh/bta_hh_act.cc
@@ -214,7 +214,8 @@
/* if not added before */
if (p_cb->hid_handle == BTA_HH_INVALID_HANDLE) {
/* add device/update attr_mask information */
- if (HID_HostAddDev(p_cb->addr, attr_mask, &hdl) == HID_SUCCESS) {
+ if (HID_HostAddDev(p_cb->link_spec.addrt.bda, attr_mask, &hdl) ==
+ HID_SUCCESS) {
status = BTA_HH_OK;
/* update cb_index[] map */
bta_hh_cb.cb_index[hdl] = p_cb->index;
@@ -292,7 +293,7 @@
bta_hh_update_di_info(p_cb, BTA_HH_VENDOR_ID_INVALID, 0, 0, 0, 0);
}
- ret = HID_HostGetSDPRecord(p_cb->addr, bta_hh_cb.p_disc_db,
+ ret = HID_HostGetSDPRecord(p_cb->link_spec.addrt.bda, bta_hh_cb.p_disc_db,
p_bta_hh_cfg->sdp_db_size, bta_hh_sdp_cback);
if (ret == HID_SUCCESS) {
status = BTA_HH_OK;
@@ -330,7 +331,7 @@
/* Do DI discovery first */
if (get_legacy_stack_sdp_api()->device_id.SDP_DiDiscover(
- p_data->api_conn.bd_addr, bta_hh_cb.p_disc_db,
+ p_data->api_conn.link_spec.addrt.bda, bta_hh_cb.p_disc_db,
p_bta_hh_cfg->sdp_db_size, bta_hh_di_sdp_cback) == SDP_SUCCESS) {
/* SDP search started successfully
* Connection will be triggered at the end of successful SDP search
@@ -377,7 +378,7 @@
/* initialize call back data */
memset((void*)&conn_dat, 0, sizeof(tBTA_HH_CONN));
conn_dat.handle = p_cb->hid_handle;
- conn_dat.bda = p_cb->addr;
+ conn_dat.link_spec = p_cb->link_spec;
/* if SDP compl success */
if (status == BTA_HH_OK) {
@@ -461,7 +462,8 @@
if (p_cb->hid_handle == BTA_HH_INVALID_HANDLE) {
uint8_t hdl;
- if (HID_HostAddDev(p_cb->addr, p_cb->attr_mask, &hdl) == HID_SUCCESS) {
+ if (HID_HostAddDev(p_cb->link_spec.addrt.bda, p_cb->attr_mask, &hdl) ==
+ HID_SUCCESS) {
/* update device CB with newly register device handle */
bta_hh_add_device_to_list(p_cb, hdl, p_cb->attr_mask, NULL,
p_cb->sub_class,
@@ -496,7 +498,7 @@
bluetooth::Uuid remote_uuids[BT_MAX_NUM_UUIDS] = {};
bt_property_t remote_properties = {BT_PROPERTY_UUIDS, sizeof(remote_uuids),
&remote_uuids};
- const RawAddress& bd_addr = p_data->api_conn.bd_addr;
+ const RawAddress& bd_addr = p_data->api_conn.link_spec.addrt.bda;
// Find the device type
tBT_DEVICE_TYPE dev_type;
@@ -552,7 +554,7 @@
// Initiate HID host connection
if (p_cb->is_le_device) {
- bta_hh_le_open_conn(p_cb, bd_addr);
+ bta_hh_le_open_conn(p_cb, p_data->api_conn.link_spec);
} else {
bta_hh_bredr_conn(p_cb, p_data);
}
@@ -568,13 +570,13 @@
* Returns void
*
******************************************************************************/
-void btif_hh_remove_device(RawAddress bd_addr);
+void btif_hh_remove_device(tAclLinkSpec link_spec);
void bta_hh_api_disc_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) {
CHECK(p_cb != nullptr);
if (p_cb->is_le_device) {
LOG_DEBUG("Host initiating close to le device:%s",
- ADDRESS_TO_LOGGABLE_CSTR(p_cb->addr));
+ ADDRESS_TO_LOGGABLE_CSTR(p_cb->link_spec));
bta_hh_le_api_disc_act(p_cb);
@@ -585,10 +587,11 @@
tHID_STATUS status = HID_HostCloseDev(hid_handle);
if (status != HID_SUCCESS) {
LOG_WARN("Failed closing classic device:%s status:%s",
- ADDRESS_TO_LOGGABLE_CSTR(p_cb->addr), hid_status_text(status).c_str());
+ ADDRESS_TO_LOGGABLE_CSTR(p_cb->link_spec),
+ hid_status_text(status).c_str());
} else {
LOG_DEBUG("Host initiated close to classic device:%s",
- ADDRESS_TO_LOGGABLE_CSTR(p_cb->addr));
+ ADDRESS_TO_LOGGABLE_CSTR(p_cb->link_spec));
}
tBTA_HH bta_hh = {
.dev_status = {.status =
@@ -616,7 +619,7 @@
memset((void*)&conn, 0, sizeof(tBTA_HH_CONN));
conn.handle = dev_handle;
- conn.bda = p_cb->addr;
+ conn.link_spec = p_cb->link_spec;
/* increase connection number */
bta_hh_cb.cnt_num++;
@@ -628,7 +631,7 @@
conn.attr_mask = p_cb->attr_mask;
conn.app_id = p_cb->app_id;
- BTM_LogHistory(kBtmLogTag, p_cb->addr, "Opened",
+ BTM_LogHistory(kBtmLogTag, p_cb->link_spec.addrt.bda, "Opened",
base::StringPrintf(
"%s initiator:%s", (p_cb->is_le_device) ? "le" : "classic",
(p_cb->incoming_conn) ? "remote" : "local"));
@@ -636,7 +639,7 @@
if (!p_cb->is_le_device)
{
/* inform role manager */
- bta_sys_conn_open(BTA_ID_HH, p_cb->app_id, p_cb->addr);
+ bta_sys_conn_open(BTA_ID_HH, p_cb->app_id, p_cb->link_spec.addrt.bda);
/* set protocol mode when not default report mode */
if (p_cb->mode != BTA_HH_PROTO_RPT_MODE) {
@@ -688,7 +691,7 @@
p_cb->incoming_hid_handle = dev_handle;
memset(&conn_data, 0, sizeof(tBTA_HH_API_CONN));
- conn_data.bd_addr = p_cb->addr;
+ conn_data.link_spec = p_cb->link_spec;
bta_hh_cb.p_cur = p_cb;
bta_hh_bredr_conn(p_cb, (tBTA_HH_DATA*)&conn_data);
}
@@ -712,7 +715,7 @@
bta_hh_co_data((uint8_t)p_data->hid_cback.hdr.layer_specific, p_rpt,
pdata->len, p_cb->mode, p_cb->sub_class,
- p_cb->dscp_info.ctry_code, p_cb->addr, p_cb->app_id);
+ p_cb->dscp_info.ctry_code, p_cb->link_spec, p_cb->app_id);
osi_free_and_reset((void**)&pdata);
}
@@ -766,7 +769,7 @@
bta_hh.conn.status =
p_data->hid_cback.data ? BTA_HH_ERR_PROTO : BTA_HH_OK;
bta_hh.conn.handle = p_cb->hid_handle;
- bta_hh.conn.bda = p_cb->addr;
+ bta_hh.conn.link_spec = p_cb->link_spec;
(*bta_hh_cb.p_cback)(p_cb->w4_evt, &bta_hh);
bta_hh_trace_dev_db();
p_cb->w4_evt = 0;
@@ -779,7 +782,7 @@
}
/* transaction achknoledgement received, inform PM for mode change */
- bta_sys_idle(BTA_ID_HH, p_cb->app_id, p_cb->addr);
+ bta_sys_idle(BTA_ID_HH, p_cb->app_id, p_cb->link_spec.addrt.bda);
return;
}
/*******************************************************************************
@@ -838,8 +841,8 @@
}
/* inform PM for mode change */
- bta_sys_busy(BTA_ID_HH, p_cb->app_id, p_cb->addr);
- bta_sys_idle(BTA_ID_HH, p_cb->app_id, p_cb->addr);
+ bta_sys_busy(BTA_ID_HH, p_cb->app_id, p_cb->link_spec.addrt.bda);
+ bta_sys_idle(BTA_ID_HH, p_cb->app_id, p_cb->link_spec.addrt.bda);
(*bta_hh_cb.p_cback)(p_cb->w4_evt, (tBTA_HH*)&hs_data);
@@ -866,7 +869,7 @@
conn_dat.handle = p_cb->hid_handle;
conn_dat.status =
(reason == HID_ERR_AUTH_FAILED) ? BTA_HH_ERR_AUTH_FAILED : BTA_HH_ERR;
- conn_dat.bda = p_cb->addr;
+ conn_dat.link_spec = p_cb->link_spec;
HID_HostCloseDev(p_cb->hid_handle);
/* Report OPEN fail event */
@@ -916,14 +919,14 @@
base::StringPrintf("%s %s %s", (l2cap_conn_fail) ? "l2cap_conn_fail" : "",
(l2cap_req_fail) ? "l2cap_req_fail" : "",
(l2cap_cfg_fail) ? "l2cap_cfg_fail" : "");
- BTM_LogHistory(kBtmLogTag, p_cb->addr, "Closed",
+ BTM_LogHistory(kBtmLogTag, p_cb->link_spec.addrt.bda, "Closed",
base::StringPrintf("%s reason %s %s",
(p_cb->is_le_device) ? "le" : "classic",
hid_status_text(hid_status).c_str(),
overlay_fail.c_str()));
/* inform role manager */
- bta_sys_conn_close(BTA_ID_HH, p_cb->app_id, p_cb->addr);
+ bta_sys_conn_close(BTA_ID_HH, p_cb->app_id, p_cb->link_spec.addrt.bda);
/* update total conn number */
bta_hh_cb.cnt_num--;
@@ -994,17 +997,18 @@
switch (p_dev_info->sub_event) {
case BTA_HH_ADD_DEV_EVT: /* add a device */
- dev_info.bda = p_dev_info->bda;
+ dev_info.link_spec = p_dev_info->link_spec;
/* initialize callback data */
if (p_cb->hid_handle == BTA_HH_INVALID_HANDLE) {
- if (BTM_UseLeLink(p_data->api_conn.bd_addr)) {
+ if (BTM_UseLeLink(p_data->api_conn.link_spec.addrt.bda)) {
p_cb->is_le_device = true;
dev_info.handle = bta_hh_le_add_device(p_cb, p_dev_info);
if (dev_info.handle != BTA_HH_INVALID_HANDLE)
dev_info.status = BTA_HH_OK;
} else
- if (HID_HostAddDev(p_dev_info->bda, p_dev_info->attr_mask,
+ if (HID_HostAddDev(p_dev_info->link_spec.addrt.bda,
+ p_dev_info->attr_mask,
&dev_handle) == HID_SUCCESS) {
dev_info.handle = dev_handle;
dev_info.status = BTA_HH_OK;
@@ -1034,7 +1038,7 @@
break;
case BTA_HH_RMV_DEV_EVT: /* remove device */
dev_info.handle = (uint8_t)p_dev_info->hdr.layer_specific;
- dev_info.bda = p_cb->addr;
+ dev_info.link_spec = p_cb->link_spec;
if (p_cb->is_le_device) {
bta_hh_le_remove_dev_bg_conn(p_cb);
@@ -1164,12 +1168,12 @@
/* if not control type transaction, notify PM for energy control */
if (p_data->api_sndcmd.t_type != HID_TRANS_CONTROL) {
/* inform PM for mode change */
- bta_sys_busy(BTA_ID_HH, p_cb->app_id, p_cb->addr);
- bta_sys_idle(BTA_ID_HH, p_cb->app_id, p_cb->addr);
+ bta_sys_busy(BTA_ID_HH, p_cb->app_id, p_cb->link_spec.addrt.bda);
+ bta_sys_idle(BTA_ID_HH, p_cb->app_id, p_cb->link_spec.addrt.bda);
} else if (api_sndcmd_param == BTA_HH_CTRL_SUSPEND) {
- bta_sys_sco_close(BTA_ID_HH, p_cb->app_id, p_cb->addr);
+ bta_sys_sco_close(BTA_ID_HH, p_cb->app_id, p_cb->link_spec.addrt.bda);
} else if (api_sndcmd_param == BTA_HH_CTRL_EXIT_SUSPEND) {
- bta_sys_busy(BTA_ID_HH, p_cb->app_id, p_cb->addr);
+ bta_sys_busy(BTA_ID_HH, p_cb->app_id, p_cb->link_spec.addrt.bda);
}
}
}
@@ -1235,7 +1239,9 @@
p_buf->hdr.event = sm_event;
p_buf->hdr.layer_specific = (uint16_t)dev_handle;
p_buf->data = data;
- p_buf->addr = addr;
+ p_buf->link_spec.addrt.bda = addr;
+ p_buf->link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ p_buf->link_spec.transport = BT_TRANSPORT_BR_EDR;
p_buf->p_data = pdata;
bta_sys_sendmsg(p_buf);
diff --git a/system/bta/hh/bta_hh_api.cc b/system/bta/hh/bta_hh_api.cc
index f7d2a74..8696b5a 100644
--- a/system/bta/hh/bta_hh_api.cc
+++ b/system/bta/hh/bta_hh_api.cc
@@ -107,7 +107,7 @@
* Returns void
*
******************************************************************************/
-void BTA_HhOpen(const RawAddress& dev_bda) {
+void BTA_HhOpen(const tAclLinkSpec& link_spec) {
tBTA_HH_API_CONN* p_buf =
(tBTA_HH_API_CONN*)osi_calloc(sizeof(tBTA_HH_API_CONN));
tBTA_HH_PROTO_MODE mode = BTA_HH_PROTO_RPT_MODE;
@@ -115,7 +115,7 @@
p_buf->hdr.event = BTA_HH_API_OPEN_EVT;
p_buf->hdr.layer_specific = BTA_HH_INVALID_HANDLE;
p_buf->mode = mode;
- p_buf->bd_addr = dev_bda;
+ p_buf->link_spec = link_spec;
bta_sys_sendmsg((void*)p_buf);
}
@@ -244,7 +244,7 @@
* Description This function send DATA transaction to HID device.
*
* Parameter dev_handle: device handle
- * dev_bda: remote device address
+ * link_spec : remote device acl link specification
* p_data: data to be sent in the DATA transaction; or
* the data to be write into the Output Report of a LE
* HID device. The report is identified the report ID
@@ -256,8 +256,8 @@
* Returns void
*
******************************************************************************/
-void BTA_HhSendData(uint8_t dev_handle, UNUSED_ATTR const RawAddress& dev_bda,
- BT_HDR* p_data) {
+void BTA_HhSendData(uint8_t dev_handle,
+ UNUSED_ATTR const tAclLinkSpec& link_spec, BT_HDR* p_data) {
if (p_data->layer_specific != BTA_HH_RPTT_OUTPUT) {
LOG_ERROR(
"ERROR! Wrong report type! Write Command only valid for output "
@@ -298,7 +298,7 @@
* Returns void
*
******************************************************************************/
-void BTA_HhAddDev(const RawAddress& bda, tBTA_HH_ATTR_MASK attr_mask,
+void BTA_HhAddDev(const tAclLinkSpec& link_spec, tBTA_HH_ATTR_MASK attr_mask,
uint8_t sub_class, uint8_t app_id,
tBTA_HH_DEV_DSCP_INFO dscp_info) {
size_t len = sizeof(tBTA_HH_MAINT_DEV) + dscp_info.descriptor.dl_len;
@@ -311,7 +311,7 @@
p_buf->attr_mask = (uint16_t)attr_mask;
p_buf->sub_class = sub_class;
p_buf->app_id = app_id;
- p_buf->bda = bda;
+ p_buf->link_spec = link_spec;
memcpy(&p_buf->dscp_info, &dscp_info, sizeof(tBTA_HH_DEV_DSCP_INFO));
if (dscp_info.descriptor.dl_len != 0 && dscp_info.descriptor.dsc_list) {
diff --git a/system/bta/hh/bta_hh_int.h b/system/bta/hh/bta_hh_int.h
index de9f3cf..17af1b1 100644
--- a/system/bta/hh/bta_hh_int.h
+++ b/system/bta/hh/bta_hh_int.h
@@ -82,21 +82,21 @@
typedef struct {
BT_HDR_RIGID hdr;
- RawAddress bd_addr;
+ tAclLinkSpec link_spec;
tBTA_HH_PROTO_MODE mode;
} tBTA_HH_API_CONN;
/* internal event data from BTE HID callback */
typedef struct {
BT_HDR_RIGID hdr;
- RawAddress addr;
+ tAclLinkSpec link_spec;
uint32_t data;
BT_HDR* p_data;
} tBTA_HH_CBACK_DATA;
typedef struct {
BT_HDR_RIGID hdr;
- RawAddress bda;
+ tAclLinkSpec link_spec;
uint16_t attr_mask;
uint16_t sub_event;
uint8_t sub_class;
@@ -181,7 +181,7 @@
/* device control block */
typedef struct {
tBTA_HH_DEV_DSCP_INFO dscp_info; /* report descriptor and DI information */
- RawAddress addr; /* BD-Addr of the HID device */
+ tAclLinkSpec link_spec; /* ACL link specification of the HID device */
uint16_t attr_mask; /* attribute mask */
uint16_t w4_evt; /* W4_handshake event name */
uint8_t index; /* index number referenced to handle index */
@@ -266,8 +266,8 @@
void bta_hh_open_failure(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data);
/* utility functions */
-uint8_t bta_hh_find_cb(const RawAddress& bda);
-tBTA_HH_DEV_CB* bta_hh_get_cb(const RawAddress& bda);
+uint8_t bta_hh_find_cb(const tAclLinkSpec& link_spec);
+tBTA_HH_DEV_CB* bta_hh_get_cb(const tAclLinkSpec& link_spec);
bool bta_hh_tod_spt(tBTA_HH_DEV_CB* p_cb, uint8_t sub_class);
void bta_hh_clean_up_kdev(tBTA_HH_DEV_CB* p_cb);
@@ -289,14 +289,14 @@
void bta_hh_api_disable(void);
void bta_hh_disc_cmpl(void);
-tBTA_HH_STATUS bta_hh_read_ssr_param(const RawAddress& bd_addr,
+tBTA_HH_STATUS bta_hh_read_ssr_param(const tAclLinkSpec& link_spec,
uint16_t* p_max_ssr_lat,
uint16_t* p_min_ssr_tout);
/* functions for LE HID */
void bta_hh_le_enable(void);
void bta_hh_le_deregister(void);
-void bta_hh_le_open_conn(tBTA_HH_DEV_CB* p_cb, const RawAddress& remote_bda);
+void bta_hh_le_open_conn(tBTA_HH_DEV_CB* p_cb, const tAclLinkSpec& link_spec);
void bta_hh_le_api_disc_act(tBTA_HH_DEV_CB* p_cb);
void bta_hh_le_get_dscp_act(tBTA_HH_DEV_CB* p_cb);
void bta_hh_le_write_dev_act(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data);
diff --git a/system/bta/hh/bta_hh_le.cc b/system/bta/hh/bta_hh_le.cc
index 68f97e6..b9a5117 100644
--- a/system/bta/hh/bta_hh_le.cc
+++ b/system/bta/hh/bta_hh_le.cc
@@ -241,7 +241,7 @@
* Parameters:
*
******************************************************************************/
-void bta_hh_le_open_conn(tBTA_HH_DEV_CB* p_cb, const RawAddress& remote_bda) {
+void bta_hh_le_open_conn(tBTA_HH_DEV_CB* p_cb, const tAclLinkSpec& link_spec) {
tBTA_HH_STATUS status = BTA_HH_ERR_NO_RES;
/* update cb_index[] map */
@@ -251,12 +251,12 @@
return;
}
- p_cb->addr = remote_bda;
+ p_cb->link_spec = link_spec;
bta_hh_cb.le_cb_index[BTA_HH_GET_LE_CB_IDX(p_cb->hid_handle)] = p_cb->index;
p_cb->in_use = true;
- BTA_GATTC_Open(bta_hh_cb.gatt_if, remote_bda, BTM_BLE_DIRECT_CONNECTION,
- false);
+ BTA_GATTC_Open(bta_hh_cb.gatt_if, link_spec.addrt.bda,
+ BTM_BLE_DIRECT_CONNECTION, false);
}
/*******************************************************************************
@@ -284,12 +284,15 @@
* Description Utility function find a device control block by BD address.
*
******************************************************************************/
-static tBTA_HH_DEV_CB* bta_hh_le_find_dev_cb_by_bda(const RawAddress& bda) {
+static tBTA_HH_DEV_CB* bta_hh_le_find_dev_cb_by_bda(
+ const tAclLinkSpec& link_spec) {
uint8_t i;
tBTA_HH_DEV_CB* p_dev_cb = &bta_hh_cb.kdev[0];
for (i = 0; i < BTA_HH_MAX_DEVICE; i++, p_dev_cb++) {
- if (p_dev_cb->in_use && p_dev_cb->addr == bda) return p_dev_cb;
+ if (p_dev_cb->in_use &&
+ p_dev_cb->link_spec.addrt.bda == link_spec.addrt.bda)
+ return p_dev_cb;
}
return NULL;
}
@@ -510,7 +513,7 @@
rpt_entry.srvc_inst_id = p_rpt->srvc_inst_id;
rpt_entry.char_inst_id = p_rpt->char_inst_id;
- bta_hh_le_co_rpt_info(p_dev_cb->addr, &rpt_entry, p_dev_cb->app_id);
+ bta_hh_le_co_rpt_info(p_dev_cb->link_spec, &rpt_entry, p_dev_cb->app_id);
}
if (p_rpt->index < BTA_HH_LE_RPT_MAX - 1)
@@ -539,7 +542,8 @@
for (int i = 0; i < BTA_HH_LE_RPT_MAX; i++, p_rpt++) {
if (p_rpt->rpt_type == BTA_HH_RPTT_INPUT) {
if (register_ba && p_rpt->uuid == GATT_UUID_BATTERY_LEVEL) {
- BTA_GATTC_RegisterForNotifications(bta_hh_cb.gatt_if, p_dev_cb->addr,
+ 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 */
@@ -547,14 +551,16 @@
if (p_rpt->uuid == GATT_UUID_HID_REPORT &&
p_rpt->client_cfg_value == GATT_CLT_CONFIG_NOTIFICATION) {
LOG_VERBOSE("---> Deregister Report ID:%d", p_rpt->rpt_id);
- BTA_GATTC_DeregisterForNotifications(
- bta_hh_cb.gatt_if, p_dev_cb->addr, p_rpt->char_inst_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) {
LOG_VERBOSE("<--- Register Boot Report ID:%d", p_rpt->rpt_id);
- BTA_GATTC_RegisterForNotifications(bta_hh_cb.gatt_if, p_dev_cb->addr,
+ BTA_GATTC_RegisterForNotifications(bta_hh_cb.gatt_if,
+ p_dev_cb->link_spec.addrt.bda,
p_rpt->char_inst_id);
}
} else if (proto_mode == BTA_HH_PROTO_RPT_MODE) {
@@ -562,12 +568,14 @@
p_rpt->uuid == GATT_UUID_HID_BT_MOUSE_INPUT) &&
p_rpt->client_cfg_value == GATT_CLT_CONFIG_NOTIFICATION) {
LOG_VERBOSE("--> Deregister Boot Report ID:%d", p_rpt->rpt_id);
- BTA_GATTC_DeregisterForNotifications(
- bta_hh_cb.gatt_if, p_dev_cb->addr, p_rpt->char_inst_id);
+ BTA_GATTC_DeregisterForNotifications(bta_hh_cb.gatt_if,
+ p_dev_cb->link_spec.addrt.bda,
+ p_rpt->char_inst_id);
} else if (p_rpt->uuid == GATT_UUID_HID_REPORT &&
p_rpt->client_cfg_value == GATT_CLT_CONFIG_NOTIFICATION) {
LOG_VERBOSE("<--- Register Report ID:%d", p_rpt->rpt_id);
- BTA_GATTC_RegisterForNotifications(bta_hh_cb.gatt_if, p_dev_cb->addr,
+ BTA_GATTC_RegisterForNotifications(bta_hh_cb.gatt_if,
+ p_dev_cb->link_spec.addrt.bda,
p_rpt->char_inst_id);
}
}
@@ -592,13 +600,15 @@
if (p_rpt->uuid == GATT_UUID_HID_REPORT &&
p_rpt->client_cfg_value == GATT_CLT_CONFIG_NOTIFICATION) {
LOG_VERBOSE("---> Deregister Report ID:%d", p_rpt->rpt_id);
- BTA_GATTC_DeregisterForNotifications(bta_hh_cb.gatt_if, p_dev_cb->addr,
+ BTA_GATTC_DeregisterForNotifications(bta_hh_cb.gatt_if,
+ p_dev_cb->link_spec.addrt.bda,
p_rpt->char_inst_id);
} else if ((p_rpt->uuid == GATT_UUID_HID_BT_KB_INPUT ||
p_rpt->uuid == GATT_UUID_HID_BT_MOUSE_INPUT) &&
p_rpt->client_cfg_value == GATT_CLT_CONFIG_NOTIFICATION) {
LOG_VERBOSE("---> Deregister Boot Report ID:%d", p_rpt->rpt_id);
- BTA_GATTC_DeregisterForNotifications(bta_hh_cb.gatt_if, p_dev_cb->addr,
+ BTA_GATTC_DeregisterForNotifications(bta_hh_cb.gatt_if,
+ p_dev_cb->link_spec.addrt.bda,
p_rpt->char_inst_id);
}
}
@@ -867,7 +877,11 @@
******************************************************************************/
static void bta_hh_le_dis_cback(const RawAddress& addr,
tDIS_VALUE* p_dis_value) {
- tBTA_HH_DEV_CB* p_cb = bta_hh_le_find_dev_cb_by_bda(addr);
+ tAclLinkSpec link_spec;
+ link_spec.addrt.bda = addr;
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ link_spec.transport = BT_TRANSPORT_LE;
+ tBTA_HH_DEV_CB* p_cb = bta_hh_le_find_dev_cb_by_bda(link_spec);
if (p_cb == nullptr) {
LOG_WARN("Unknown address");
@@ -909,12 +923,13 @@
*
******************************************************************************/
static void bta_hh_le_pri_service_discovery(tBTA_HH_DEV_CB* p_cb) {
- bta_hh_le_co_reset_rpt_cache(p_cb->addr, p_cb->app_id);
+ bta_hh_le_co_reset_rpt_cache(p_cb->link_spec, p_cb->app_id);
p_cb->disc_active |= (BTA_HH_LE_DISC_HIDS | BTA_HH_LE_DISC_DIS);
/* read DIS info */
- if (!DIS_ReadDISInfo(p_cb->addr, bta_hh_le_dis_cback, DIS_ATTR_PNP_ID_BIT)) {
+ if (!DIS_ReadDISInfo(p_cb->link_spec.addrt.bda, bta_hh_le_dis_cback,
+ DIS_ATTR_PNP_ID_BIT)) {
LOG_ERROR("read DIS failed");
p_cb->disc_active &= ~BTA_HH_LE_DISC_DIS;
}
@@ -939,7 +954,12 @@
UNUSED_ATTR tBT_TRANSPORT transport,
UNUSED_ATTR void* p_ref_data,
tBTM_STATUS result) {
- tBTA_HH_DEV_CB* p_dev_cb = bta_hh_get_cb(*bd_addr);
+ tAclLinkSpec link_spec;
+ link_spec.addrt.bda = *bd_addr;
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ link_spec.transport = transport;
+
+ tBTA_HH_DEV_CB* p_dev_cb = bta_hh_get_cb(link_spec);
if (p_dev_cb == nullptr) {
LOG_ERROR("unexpected encryption callback, ignore");
return;
@@ -965,7 +985,7 @@
******************************************************************************/
void bta_hh_security_cmpl(tBTA_HH_DEV_CB* p_cb,
UNUSED_ATTR const tBTA_HH_DATA* p_buf) {
- LOG_VERBOSE("addr:%s, status:%d", ADDRESS_TO_LOGGABLE_CSTR(p_cb->addr),
+ LOG_VERBOSE("addr:%s, status:%d", ADDRESS_TO_LOGGABLE_CSTR(p_cb->link_spec),
p_cb->status);
if (p_cb->status == BTA_HH_OK) {
if (p_cb->hid_srvc.state < BTA_HH_SERVICE_DISCOVERED) {
@@ -974,7 +994,7 @@
/* start loading the cache if not in stack */
tBTA_HH_RPT_CACHE_ENTRY* p_rpt_cache;
uint8_t num_rpt = 0;
- if ((p_rpt_cache = bta_hh_le_co_cache_load(p_cb->addr, &num_rpt,
+ if ((p_rpt_cache = bta_hh_le_co_cache_load(p_cb->link_spec, &num_rpt,
p_cb->app_id)) != NULL) {
LOG_DEBUG("Cache found, no need to perform service discovery");
bta_hh_process_cache_rpt(p_cb, p_rpt_cache, num_rpt);
@@ -1063,35 +1083,37 @@
******************************************************************************/
void bta_hh_start_security(tBTA_HH_DEV_CB* p_cb,
UNUSED_ATTR const tBTA_HH_DATA* p_buf) {
- LOG_VERBOSE("addr:%s", ADDRESS_TO_LOGGABLE_CSTR(p_cb->addr));
- if (BTM_SecIsSecurityPending(p_cb->addr)) {
+ LOG_VERBOSE("addr:%s", ADDRESS_TO_LOGGABLE_CSTR(p_cb->link_spec.addrt.bda));
+ if (BTM_SecIsSecurityPending(p_cb->link_spec.addrt.bda)) {
/* if security collision happened, wait for encryption done */
p_cb->security_pending = true;
return;
}
/* if link has been encrypted */
- if (BTM_IsEncrypted(p_cb->addr, BT_TRANSPORT_LE)) {
+ if (BTM_IsEncrypted(p_cb->link_spec.addrt.bda, BT_TRANSPORT_LE)) {
LOG_DEBUG("addr:%s already encrypted",
- ADDRESS_TO_LOGGABLE_CSTR(p_cb->addr));
+ ADDRESS_TO_LOGGABLE_CSTR(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->addr, BT_TRANSPORT_LE)) {
+ else if (BTM_IsLinkKeyKnown(p_cb->link_spec.addrt.bda, BT_TRANSPORT_LE)) {
LOG_DEBUG("addr:%s bonded, not encrypted",
- ADDRESS_TO_LOGGABLE_CSTR(p_cb->addr));
+ ADDRESS_TO_LOGGABLE_CSTR(p_cb->link_spec.addrt.bda));
p_cb->status = BTA_HH_ERR_AUTH_FAILED;
- BTM_SetEncryption(p_cb->addr, BT_TRANSPORT_LE, bta_hh_le_encrypt_cback,
- NULL, BTM_BLE_SEC_ENCRYPT);
+ BTM_SetEncryption(p_cb->link_spec.addrt.bda, BT_TRANSPORT_LE,
+ bta_hh_le_encrypt_cback, NULL, BTM_BLE_SEC_ENCRYPT);
}
/* unbonded device, report security error here */
else {
- LOG_DEBUG("addr:%s not bonded", ADDRESS_TO_LOGGABLE_CSTR(p_cb->addr));
+ LOG_DEBUG("addr:%s not bonded",
+ ADDRESS_TO_LOGGABLE_CSTR(p_cb->link_spec.addrt.bda));
p_cb->status = BTA_HH_ERR_AUTH_FAILED;
bta_hh_clear_service_cache(p_cb);
- BTM_SetEncryption(p_cb->addr, BT_TRANSPORT_LE, bta_hh_le_encrypt_cback,
- NULL, BTM_BLE_SEC_ENCRYPT_NO_MITM);
+ BTM_SetEncryption(p_cb->link_spec.addrt.bda, BT_TRANSPORT_LE,
+ bta_hh_le_encrypt_cback, NULL,
+ BTM_BLE_SEC_ENCRYPT_NO_MITM);
}
}
@@ -1150,7 +1172,12 @@
*
******************************************************************************/
static void bta_hh_le_close(const tBTA_GATTC_CLOSE& gattc_data) {
- tBTA_HH_DEV_CB* p_cb = bta_hh_le_find_dev_cb_by_bda(gattc_data.remote_bda);
+ tAclLinkSpec link_spec;
+ link_spec.addrt.bda = gattc_data.remote_bda;
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ link_spec.transport = BT_TRANSPORT_LE;
+
+ tBTA_HH_DEV_CB* p_cb = bta_hh_le_find_dev_cb_by_bda(link_spec);
if (p_cb == nullptr) {
LOG_WARN("unknown device:%s",
ADDRESS_TO_LOGGABLE_CSTR(gattc_data.remote_bda));
@@ -1356,14 +1383,14 @@
tBTA_HH_DEV_CB* p_dev_cb = (tBTA_HH_DEV_CB*)data;
if (interop_match_addr(INTEROP_HID_PREF_CONN_SUP_TIMEOUT_3S,
- (RawAddress*)&p_dev_cb->addr)) {
+ (RawAddress*)&p_dev_cb->link_spec.addrt.bda)) {
if (timeout < 300) timeout = 300;
}
- BTM_BleSetPrefConnParams(p_dev_cb->addr, min_interval, max_interval, latency,
- timeout);
- L2CA_UpdateBleConnParams(p_dev_cb->addr, min_interval, max_interval, latency,
- timeout, 0, 0);
+ BTM_BleSetPrefConnParams(p_dev_cb->link_spec.addrt.bda, min_interval,
+ max_interval, latency, timeout);
+ L2CA_UpdateBleConnParams(p_dev_cb->link_spec.addrt.bda, min_interval,
+ max_interval, latency, timeout, 0, 0);
}
/*******************************************************************************
@@ -1593,7 +1620,7 @@
bta_hh_co_data((uint8_t)p_dev_cb->hid_handle, p_buf, p_data->len,
p_dev_cb->mode, 0, /* no sub class*/
- p_dev_cb->dscp_info.ctry_code, p_dev_cb->addr, app_id);
+ p_dev_cb->dscp_info.ctry_code, p_dev_cb->link_spec, app_id);
if (p_buf != p_data->value) osi_free(p_buf);
}
@@ -1610,11 +1637,12 @@
void bta_hh_le_open_fail(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) {
const tBTA_HH_LE_CLOSE* le_close = &p_data->le_close;
- BTM_LogHistory(kBtmLogTag, p_cb->addr, "Open failed",
+ BTM_LogHistory(kBtmLogTag, p_cb->link_spec.addrt.bda, "Open failed",
base::StringPrintf(
"%s reason %s", (p_cb->is_le_device) ? "le" : "classic",
gatt_disconnection_reason_text(le_close->reason).c_str()));
- LOG_WARN("Open failed for device:%s", ADDRESS_TO_LOGGABLE_CSTR(p_cb->addr));
+ LOG_WARN("Open failed for device:%s",
+ ADDRESS_TO_LOGGABLE_CSTR(p_cb->link_spec.addrt.bda));
/* open failure in the middle of service discovery, clear all services */
if (p_cb->disc_active & BTA_HH_LE_DISC_HIDS) {
@@ -1633,7 +1661,7 @@
tBTA_HH data = {
.conn =
{
- .bda = p_cb->addr,
+ .link_spec = p_cb->link_spec,
.status = (le_close->reason != GATT_CONN_OK) ? BTA_HH_ERR
: p_cb->status,
.handle = p_cb->hid_handle,
@@ -1659,7 +1687,7 @@
void bta_hh_gatt_close(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* p_data) {
const tBTA_HH_LE_CLOSE* le_close = &p_data->le_close;
- BTM_LogHistory(kBtmLogTag, p_cb->addr, "Closed",
+ BTM_LogHistory(kBtmLogTag, p_cb->link_spec.addrt.bda, "Closed",
base::StringPrintf(
"%s reason %s", (p_cb->is_le_device) ? "le" : "classic",
gatt_disconnection_reason_text(le_close->reason).c_str()));
@@ -1686,7 +1714,7 @@
case GATT_CONN_TIMEOUT:
LOG_DEBUG(
"gd_acl: add into acceptlist for reconnection device:%s reason:%s",
- ADDRESS_TO_LOGGABLE_CSTR(p_cb->addr),
+ ADDRESS_TO_LOGGABLE_CSTR(p_cb->link_spec),
gatt_disconnection_reason_text(le_close->reason).c_str());
// gd removes from bg list after successful connection
// Correct the cached state to allow re-add to acceptlist.
@@ -1702,7 +1730,7 @@
LOG_DEBUG(
"gd_acl: SKIP add into acceptlist for reconnection device:%s "
"reason:%s",
- ADDRESS_TO_LOGGABLE_CSTR(p_cb->addr),
+ ADDRESS_TO_LOGGABLE_CSTR(p_cb->link_spec),
gatt_disconnection_reason_text(le_close->reason).c_str());
break;
}
@@ -2007,7 +2035,7 @@
******************************************************************************/
static void bta_hh_le_add_dev_bg_conn(tBTA_HH_DEV_CB* p_cb) {
/* Add device into BG connection to accept remote initiated connection */
- BTA_GATTC_Open(bta_hh_cb.gatt_if, p_cb->addr,
+ BTA_GATTC_Open(bta_hh_cb.gatt_if, p_cb->link_spec.addrt.bda,
BTM_BLE_BKG_CONNECT_ALLOW_LIST, false);
p_cb->in_bg_conn = true;
}
@@ -2060,26 +2088,27 @@
void bta_hh_le_remove_dev_bg_conn(tBTA_HH_DEV_CB* p_dev_cb) {
if (p_dev_cb->in_bg_conn) {
LOG_DEBUG("Removing from background connection device:%s",
- ADDRESS_TO_LOGGABLE_CSTR(p_dev_cb->addr));
+ ADDRESS_TO_LOGGABLE_CSTR(p_dev_cb->link_spec));
p_dev_cb->in_bg_conn = false;
- BTA_GATTC_CancelOpen(bta_hh_cb.gatt_if, p_dev_cb->addr, false);
+ BTA_GATTC_CancelOpen(bta_hh_cb.gatt_if, p_dev_cb->link_spec.addrt.bda,
+ false);
}
/* deregister all notifications */
bta_hh_le_deregister_input_notif(p_dev_cb);
}
-static void bta_hh_le_service_changed(RawAddress remote_bda) {
- tBTA_HH_DEV_CB* p_cb = bta_hh_le_find_dev_cb_by_bda(remote_bda);
+static void bta_hh_le_service_changed(tAclLinkSpec link_spec) {
+ tBTA_HH_DEV_CB* p_cb = bta_hh_le_find_dev_cb_by_bda(link_spec);
if (p_cb == nullptr) {
LOG_WARN("Received close event with unknown device:%s",
- ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
+ ADDRESS_TO_LOGGABLE_CSTR(link_spec));
return;
}
/* Forget the cached reports */
- bta_hh_le_co_reset_rpt_cache(p_cb->addr, p_cb->app_id);
+ bta_hh_le_co_reset_rpt_cache(p_cb->link_spec, p_cb->app_id);
p_cb->dscp_info.descriptor.dsc_list = NULL;
osi_free_and_reset((void**)&p_cb->hid_srvc.rpt_map);
p_cb->hid_srvc = {};
@@ -2103,10 +2132,10 @@
bta_hh_sm_execute(p_cb, BTA_HH_GATT_CLOSE_EVT, &data);
}
-static void bta_hh_le_service_discovery_done(RawAddress remote_bda) {
- tBTA_HH_DEV_CB* p_cb = bta_hh_le_find_dev_cb_by_bda(remote_bda);
+static void bta_hh_le_service_discovery_done(tAclLinkSpec link_spec) {
+ tBTA_HH_DEV_CB* p_cb = bta_hh_le_find_dev_cb_by_bda(link_spec);
if (p_cb == nullptr) {
- LOG_WARN("unknown device:%s", ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
+ LOG_WARN("unknown device:%s", ADDRESS_TO_LOGGABLE_CSTR(link_spec));
return;
}
@@ -2118,7 +2147,7 @@
.status = GATT_SUCCESS,
.conn_id = p_cb->conn_id,
.client_if = bta_hh_cb.gatt_if,
- .remote_bda = remote_bda,
+ .remote_bda = link_spec.addrt.bda,
.transport = BT_TRANSPORT_LE,
.mtu = 0,
};
@@ -2139,6 +2168,10 @@
******************************************************************************/
static void bta_hh_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) {
tBTA_HH_DEV_CB* p_dev_cb;
+ tAclLinkSpec link_spec;
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ link_spec.transport = BT_TRANSPORT_LE;
+
LOG_VERBOSE("event:%s", gatt_client_event_text(event).c_str());
if (p_data == NULL) return;
@@ -2149,7 +2182,9 @@
break;
case BTA_GATTC_OPEN_EVT: /* 2 */
- p_dev_cb = bta_hh_le_find_dev_cb_by_bda(p_data->open.remote_bda);
+ link_spec.addrt.bda = p_data->open.remote_bda;
+ link_spec.transport = p_data->open.transport;
+ p_dev_cb = bta_hh_le_find_dev_cb_by_bda(link_spec);
if (p_dev_cb) {
bta_hh_sm_execute(p_dev_cb, BTA_HH_GATT_OPEN_EVT,
(tBTA_HH_DATA*)&p_data->open);
@@ -2169,15 +2204,18 @@
break;
case BTA_GATTC_SRVC_CHG_EVT:
- bta_hh_le_service_changed(p_data->remote_bda);
+ link_spec.addrt.bda = p_data->remote_bda;
+ bta_hh_le_service_changed(link_spec);
break;
case BTA_GATTC_SRVC_DISC_DONE_EVT:
- bta_hh_le_service_discovery_done(p_data->remote_bda);
+ link_spec.addrt.bda = p_data->remote_bda;
+ bta_hh_le_service_discovery_done(link_spec);
break;
case BTA_GATTC_ENC_CMPL_CB_EVT: /* 17 */
- p_dev_cb = bta_hh_le_find_dev_cb_by_bda(p_data->enc_cmpl.remote_bda);
+ link_spec.addrt.bda = p_data->enc_cmpl.remote_bda;
+ p_dev_cb = bta_hh_le_find_dev_cb_by_bda(link_spec);
if (p_dev_cb) {
bta_hh_sm_execute(p_dev_cb, BTA_HH_GATT_ENC_CMPL_EVT,
(tBTA_HH_DATA*)&p_data->enc_cmpl);
diff --git a/system/bta/hh/bta_hh_main.cc b/system/bta/hh/bta_hh_main.cc
index fa0074f..9862f4f 100644
--- a/system/bta/hh/bta_hh_main.cc
+++ b/system/bta/hh/bta_hh_main.cc
@@ -208,7 +208,7 @@
case BTA_HH_API_OPEN_EVT:
cback_event = BTA_HH_OPEN_EVT;
/* build cback data */
- cback_data.conn.bda = ((tBTA_HH_API_CONN*)p_data)->bd_addr;
+ cback_data.conn.link_spec = ((tBTA_HH_API_CONN*)p_data)->link_spec;
cback_data.conn.status = BTA_HH_ERR_DB_FULL;
cback_data.conn.handle = BTA_HH_INVALID_HANDLE;
break;
@@ -217,7 +217,7 @@
cback_event = p_data->api_maintdev.sub_event;
if (p_data->api_maintdev.sub_event == BTA_HH_ADD_DEV_EVT) {
- cback_data.dev_info.bda = p_data->api_maintdev.bda;
+ cback_data.dev_info.link_spec = p_data->api_maintdev.link_spec;
cback_data.dev_info.status = BTA_HH_ERR_DB_FULL;
cback_data.dev_info.handle = BTA_HH_INVALID_HANDLE;
} else {
@@ -308,11 +308,11 @@
/* all events processed in state machine need to find corresponding
CB before proceed */
if (p_msg->event == BTA_HH_API_OPEN_EVT) {
- index = bta_hh_find_cb(((tBTA_HH_API_CONN*)p_msg)->bd_addr);
+ index = bta_hh_find_cb(((tBTA_HH_API_CONN*)p_msg)->link_spec);
} else if (p_msg->event == BTA_HH_API_MAINT_DEV_EVT) {
/* if add device */
if (((tBTA_HH_MAINT_DEV*)p_msg)->sub_event == BTA_HH_ADD_DEV_EVT) {
- index = bta_hh_find_cb(((tBTA_HH_MAINT_DEV*)p_msg)->bda);
+ index = bta_hh_find_cb(((tBTA_HH_MAINT_DEV*)p_msg)->link_spec);
} else /* else remove device by handle */ {
index = bta_hh_dev_handle_to_cb_idx((uint8_t)p_msg->layer_specific);
/* If BT disable is done while the HID device is connected and
@@ -330,7 +330,7 @@
}
}
} else if (p_msg->event == BTA_HH_INT_OPEN_EVT) {
- index = bta_hh_find_cb(((tBTA_HH_CBACK_DATA*)p_msg)->addr);
+ index = bta_hh_find_cb(((tBTA_HH_CBACK_DATA*)p_msg)->link_spec);
} else {
index = bta_hh_dev_handle_to_cb_idx((uint8_t)p_msg->layer_specific);
}
diff --git a/system/bta/hh/bta_hh_utils.cc b/system/bta/hh/bta_hh_utils.cc
index 0a71f69..abf6c12 100644
--- a/system/bta/hh/bta_hh_utils.cc
+++ b/system/bta/hh/bta_hh_utils.cc
@@ -57,13 +57,14 @@
* Returns void
*
******************************************************************************/
-uint8_t bta_hh_find_cb(const RawAddress& bda) {
+uint8_t bta_hh_find_cb(const tAclLinkSpec& link_spec) {
uint8_t xx;
/* See how many active devices there are. */
for (xx = 0; xx < BTA_HH_MAX_DEVICE; xx++) {
/* check if any active/known devices is a match */
- if ((bda == bta_hh_cb.kdev[xx].addr && !bda.IsEmpty())) {
+ if ((link_spec.addrt.bda == bta_hh_cb.kdev[xx].link_spec.addrt.bda &&
+ !link_spec.addrt.bda.IsEmpty())) {
#if (BTA_HH_DEBUG == TRUE)
LOG_VERBOSE("found kdev_cb[%d] hid_handle=%d", xx,
bta_hh_cb.kdev[xx].hid_handle);
@@ -81,7 +82,7 @@
/* if no active device match, find a spot for it */
for (xx = 0; xx < BTA_HH_MAX_DEVICE; xx++) {
if (!bta_hh_cb.kdev[xx].in_use) {
- bta_hh_cb.kdev[xx].addr = bda;
+ bta_hh_cb.kdev[xx].link_spec = link_spec;
break;
}
}
@@ -95,8 +96,8 @@
return xx;
}
-tBTA_HH_DEV_CB* bta_hh_get_cb(const RawAddress& bda) {
- uint8_t idx = bta_hh_find_cb(bda);
+tBTA_HH_DEV_CB* bta_hh_get_cb(const tAclLinkSpec& link_spec) {
+ uint8_t idx = bta_hh_find_cb(link_spec);
if (idx == BTA_HH_IDX_INVALID) {
return nullptr;
}
@@ -245,12 +246,12 @@
* Returns tBTA_HH_STATUS operation status
*
******************************************************************************/
-tBTA_HH_STATUS bta_hh_read_ssr_param(const RawAddress& bd_addr,
+tBTA_HH_STATUS bta_hh_read_ssr_param(const tAclLinkSpec& link_spec,
uint16_t* p_max_ssr_lat,
uint16_t* p_min_ssr_tout) {
- tBTA_HH_DEV_CB* p_cb = bta_hh_get_cb(bd_addr);
+ tBTA_HH_DEV_CB* p_cb = bta_hh_get_cb(link_spec);
if (p_cb == nullptr) {
- LOG_WARN("Unable to find device:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ LOG_WARN("Unable to find device:%s", ADDRESS_TO_LOGGABLE_CSTR(link_spec));
return BTA_HH_ERR;
}
@@ -261,9 +262,9 @@
uint16_t ssr_max_latency;
if (get_btm_client_interface().link_controller.BTM_GetLinkSuperTout(
- p_cb->addr, &ssr_max_latency) != BTM_SUCCESS) {
+ p_cb->link_spec.addrt.bda, &ssr_max_latency) != BTM_SUCCESS) {
LOG_WARN("Unable to get supervision timeout for peer:%s",
- ADDRESS_TO_LOGGABLE_CSTR(p_cb->addr));
+ ADDRESS_TO_LOGGABLE_CSTR(p_cb->link_spec));
return BTA_HH_ERR;
}
ssr_max_latency = BTA_HH_GET_DEF_SSR_MAX_LAT(ssr_max_latency);
@@ -275,7 +276,7 @@
ssr_max_latency = BTA_HH_SSR_MAX_LATENCY_DEF;
char remote_name[BTM_MAX_REM_BD_NAME_LEN] = "";
- if (btif_storage_get_stored_remote_name(bd_addr, remote_name)) {
+ if (btif_storage_get_stored_remote_name(link_spec.addrt.bda, remote_name)) {
if (interop_match_name(INTEROP_HID_HOST_LIMIT_SNIFF_INTERVAL,
remote_name)) {
if (ssr_max_latency > kSsrMaxLatency /* slots * 0.625ms */) {
diff --git a/system/bta/include/bta_csis_api.h b/system/bta/include/bta_csis_api.h
index 8f23582..e56d5cc 100644
--- a/system/bta/include/bta_csis_api.h
+++ b/system/bta/include/bta_csis_api.h
@@ -35,7 +35,7 @@
static void Initialize(bluetooth::csis::CsisClientCallbacks* callbacks,
base::Closure initCb);
static void AddFromStorage(const RawAddress& addr,
- const std::vector<uint8_t>& in, bool autoconnect);
+ const std::vector<uint8_t>& in);
static bool GetForStorage(const RawAddress& addr, std::vector<uint8_t>& out);
static void CleanUp();
static CsisClient* Get();
diff --git a/system/bta/include/bta_hh_api.h b/system/bta/include/bta_hh_api.h
index c017075..66b841e 100644
--- a/system/bta/include/bta_hh_api.h
+++ b/system/bta/include/bta_hh_api.h
@@ -28,7 +28,7 @@
#include "stack/include/bt_hdr.h"
#include "stack/include/hiddefs.h"
#include "stack/include/l2c_api.h"
-#include "types/raw_address.h"
+#include "types/ble_address_with_type.h"
/*****************************************************************************
* Constants and Type Definitions
@@ -232,7 +232,7 @@
/* callback event data for BTA_HH_OPEN_EVT */
typedef struct {
- RawAddress bda; /* HID device bd address */
+ tAclLinkSpec link_spec; /* HID device ACL link specification */
tBTA_HH_STATUS status; /* operation status */
uint8_t handle; /* device handle */
bool le_hid; /* is LE devices? */
@@ -358,7 +358,7 @@
* Returns void
*
******************************************************************************/
-void BTA_HhOpen(const RawAddress& dev_bda);
+void BTA_HhOpen(const tAclLinkSpec& link_spec);
/*******************************************************************************
*
@@ -480,7 +480,7 @@
* Returns void
*
******************************************************************************/
-void BTA_HhSendData(uint8_t dev_handle, const RawAddress& dev_bda,
+void BTA_HhSendData(uint8_t dev_handle, const tAclLinkSpec& link_spec,
BT_HDR* p_buf);
/*******************************************************************************
@@ -505,7 +505,7 @@
* Returns void
*
******************************************************************************/
-void BTA_HhAddDev(const RawAddress& bda, tBTA_HH_ATTR_MASK attr_mask,
+void BTA_HhAddDev(const tAclLinkSpec& link_spec, tBTA_HH_ATTR_MASK attr_mask,
uint8_t sub_class, uint8_t app_id,
tBTA_HH_DEV_DSCP_INFO dscp_info);
/*******************************************************************************
diff --git a/system/bta/include/bta_hh_co.h b/system/bta/include/bta_hh_co.h
index 2ddaf68..eb805b1 100644
--- a/system/bta/include/bta_hh_co.h
+++ b/system/bta/include/bta_hh_co.h
@@ -51,7 +51,7 @@
******************************************************************************/
void bta_hh_co_data(uint8_t dev_handle, uint8_t* p_rpt, uint16_t len,
tBTA_HH_PROTO_MODE mode, uint8_t sub_class,
- uint8_t ctry_code, const RawAddress& peer_addr,
+ uint8_t ctry_code, const tAclLinkSpec& link_spec,
uint8_t app_id);
/*******************************************************************************
@@ -102,14 +102,14 @@
* information in NV if device is bonded and load it back when
* stack reboot.
*
- * Parameters remote_bda - remote device address
+ * Parameters link_spec - acl link specification
* p_entry - report entry pointer
* app_id - application id
*
* Returns void.
*
******************************************************************************/
-void bta_hh_le_co_rpt_info(const RawAddress& remote_bda,
+void bta_hh_le_co_rpt_info(const tAclLinkSpec& link_spec,
tBTA_HH_RPT_CACHE_ENTRY* p_entry, uint8_t app_id);
/*******************************************************************************
@@ -121,14 +121,14 @@
* is completed, bta_hh_le_ci_cache_load() is called by the
* application.
*
- * Parameters remote_bda - remote device address
+ * Parameters link_spec - acl link specification
* p_num_rpt: number of cached report
* app_id - application id
*
* Returns the acched report array
*
******************************************************************************/
-tBTA_HH_RPT_CACHE_ENTRY* bta_hh_le_co_cache_load(const RawAddress& remote_bda,
+tBTA_HH_RPT_CACHE_ENTRY* bta_hh_le_co_cache_load(const tAclLinkSpec& link_spec,
uint8_t* p_num_rpt,
uint8_t app_id);
@@ -138,11 +138,12 @@
*
* Description This callout function is to reset the HOGP device cache.
*
- * Parameters remote_bda - remote device address
+ * Parameters link_spec - acl link specification
*
* Returns none
*
******************************************************************************/
-void bta_hh_le_co_reset_rpt_cache(const RawAddress& remote_bda, uint8_t app_id);
+void bta_hh_le_co_reset_rpt_cache(const tAclLinkSpec& link_spec,
+ uint8_t app_id);
#endif /* BTA_HH_CO_H */
diff --git a/system/bta/include/bta_le_audio_api.h b/system/bta/include/bta_le_audio_api.h
index c5e4cef..0dc61ae 100644
--- a/system/bta/include/bta_le_audio_api.h
+++ b/system/bta/include/bta_le_audio_api.h
@@ -67,6 +67,7 @@
virtual void SetInVoipCall(bool in_call) = 0;
virtual void SetUnicastMonitorMode(uint8_t direction, bool enable) = 0;
virtual bool IsInVoipCall() = 0;
+ virtual bool IsInStreaming() = 0;
virtual void SendAudioProfilePreferences(
const int group_id, bool is_output_preference_le_audio,
bool is_duplex_preference_le_audio) = 0;
@@ -91,4 +92,5 @@
static bool GetAsesForStorage(const RawAddress& addr,
std::vector<uint8_t>& out);
static bool IsLeAudioClientRunning();
+ static bool IsLeAudioClientInStreaming();
};
diff --git a/system/bta/le_audio/audio_hal_client/audio_sink_hal_client.cc b/system/bta/le_audio/audio_hal_client/audio_sink_hal_client.cc
index f44218e..ac51648 100644
--- a/system/bta/le_audio/audio_hal_client/audio_sink_hal_client.cc
+++ b/system/bta/le_audio/audio_hal_client/audio_sink_hal_client.cc
@@ -22,7 +22,7 @@
#include "audio_hal_interface/le_audio_software.h"
#include "bta/le_audio/codec_manager.h"
#include "common/time_util.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#include "osi/include/wakelock.h"
#include "stack/include/main_thread.h"
diff --git a/system/bta/le_audio/broadcaster/broadcaster.cc b/system/bta/le_audio/broadcaster/broadcaster.cc
index 9f9612f..315939e 100644
--- a/system/bta/le_audio/broadcaster/broadcaster.cc
+++ b/system/bta/le_audio/broadcaster/broadcaster.cc
@@ -128,8 +128,8 @@
broadcasts_.clear();
callbacks_ = nullptr;
is_iso_running_ = false;
- queued_start_broadcast_request_.ClearQueuedBroadcast();
- queued_create_broadcast_request_.ClearQueuedBroadcast();
+ queued_start_broadcast_request_ = std::nullopt;
+ queued_create_broadcast_request_ = std::nullopt;
if (le_audio_source_hal_client_) {
le_audio_source_hal_client_->Stop();
@@ -378,15 +378,10 @@
LeAudioLtvMap public_ltv;
std::vector<LeAudioLtvMap> subgroup_ltvs;
- if (queued_create_broadcast_request_.IsQueuedBroadcast()) {
+ if (queued_create_broadcast_request_) {
LOG_ERROR("Not processed yet queued broadcast");
- return;
- }
-
- if (is_iso_running_) {
- queued_create_broadcast_request_.SetCreateBroadcastRequest(
- is_public, broadcast_name, broadcast_code, public_metadata,
- subgroup_quality, subgroup_metadata);
+ callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid,
+ false);
return;
}
@@ -397,6 +392,8 @@
public_metadata.data(), public_metadata.size(), is_metadata_valid);
if (!is_metadata_valid) {
LOG_ERROR("Invalid metadata provided.");
+ callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid,
+ false);
return;
}
// Prepare public features byte
@@ -438,6 +435,8 @@
auto ltv = LeAudioLtvMap::Parse(metadata.data(), metadata.size(), is_metadata_valid);
if (!is_metadata_valid) {
LOG_ERROR("Invalid metadata provided.");
+ callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid,
+ false);
return;
}
@@ -448,6 +447,8 @@
if (stream_context_vec) {
if (stream_context_vec.value().size() < 2) {
LOG_ERROR("kLeAudioMetadataTypeStreamingAudioContext size < 2");
+ callbacks_->OnBroadcastCreated(
+ bluetooth::le_audio::kBroadcastIdInvalid, false);
return;
}
auto pp = stream_context_vec.value().data();
@@ -460,6 +461,8 @@
if (stream_context_vec) {
if (stream_context_vec.value().size() < 2) {
LOG_ERROR("kLeAudioMetadataTypeStreamingAudioContext size < 2");
+ callbacks_->OnBroadcastCreated(
+ bluetooth::le_audio::kBroadcastIdInvalid, false);
return;
}
@@ -478,70 +481,79 @@
subgroup_ltvs.push_back(ltv);
}
- if (CodecManager::GetInstance()->GetCodecLocation() ==
- CodecLocation::ADSP) {
- auto offload_config =
- CodecManager::GetInstance()->GetBroadcastOffloadConfig();
- if (offload_config == nullptr) {
- LOG_ERROR("No valid broadcast offload config");
- return;
+ auto codec_qos_pair = [](AudioContexts context_type)
+ -> std::optional<
+ std::pair<const BroadcastCodecWrapper, const BroadcastQosConfig>> {
+ if (CodecManager::GetInstance()->GetCodecLocation() ==
+ CodecLocation::ADSP) {
+ auto offload_config =
+ CodecManager::GetInstance()->GetBroadcastOffloadConfig();
+ if (offload_config == nullptr) {
+ return std::nullopt;
+ }
+ return std::make_pair(
+ BroadcastCodecWrapper(
+ {.coding_format = le_audio::types::kLeAudioCodingFormatLC3,
+ .vendor_company_id =
+ le_audio::types::kLeAudioVendorCompanyIdUndefined,
+ .vendor_codec_id =
+ le_audio::types::kLeAudioVendorCodecIdUndefined},
+ {.num_channels =
+ static_cast<uint8_t>(offload_config->stream_map.size()),
+ .sample_rate = offload_config->sampling_rate,
+ .bits_per_sample = offload_config->bits_per_sample,
+ .data_interval_us = offload_config->frame_duration},
+ offload_config->octets_per_frame),
+ BroadcastQosConfig(offload_config->retransmission_number,
+ offload_config->max_transport_latency));
+ } else {
+ return le_audio::broadcaster::getStreamConfigForContext(context_type);
}
- BroadcastCodecWrapper codec_config(
- {.coding_format = le_audio::types::kLeAudioCodingFormatLC3,
- .vendor_company_id =
- le_audio::types::kLeAudioVendorCompanyIdUndefined,
- .vendor_codec_id = le_audio::types::kLeAudioVendorCodecIdUndefined},
- {.num_channels =
- static_cast<uint8_t>(offload_config->stream_map.size()),
- .sample_rate = offload_config->sampling_rate,
- .bits_per_sample = offload_config->bits_per_sample,
- .data_interval_us = offload_config->frame_duration},
- offload_config->octets_per_frame);
- BroadcastQosConfig qos_config(offload_config->retransmission_number,
- offload_config->max_transport_latency);
+ }(context_type);
- BroadcastStateMachineConfig msg = {
- .is_public = is_public,
- .broadcast_id = broadcast_id,
- .broadcast_name = broadcast_name,
- .streaming_phy = GetStreamingPhy(),
- .codec_wrapper = codec_config,
- .qos_config = qos_config,
- .announcement = prepareBasicAnnouncement(codec_config, subgroup_ltvs),
- .broadcast_code = std::move(broadcast_code)};
- if (is_public) {
- msg.public_announcement =
- preparePublicAnnouncement(public_features, public_ltv);
- }
- pending_broadcasts_.push_back(
- std::move(BroadcastStateMachine::CreateInstance(std::move(msg))));
- } else {
- auto codec_qos_pair =
- le_audio::broadcaster::getStreamConfigForContext(context_type);
- BroadcastStateMachineConfig msg = {
- .is_public = is_public,
- .broadcast_id = broadcast_id,
- .broadcast_name = broadcast_name,
- .streaming_phy = GetStreamingPhy(),
- .codec_wrapper = codec_qos_pair.first,
- .qos_config = codec_qos_pair.second,
- .announcement =
- prepareBasicAnnouncement(codec_qos_pair.first, subgroup_ltvs),
- .broadcast_code = std::move(broadcast_code)};
- if (is_public) {
- msg.public_announcement =
- preparePublicAnnouncement(public_features, public_ltv);
- }
- /* Create the broadcaster instance - we'll receive it's init state in the
- * async callback
- */
- pending_broadcasts_.push_back(
- std::move(BroadcastStateMachine::CreateInstance(std::move(msg))));
+ if (!codec_qos_pair) {
+ LOG_ERROR("No valid broadcast offload config");
+ return;
}
+ BroadcastStateMachineConfig msg = {
+ .is_public = is_public,
+ .broadcast_id = broadcast_id,
+ .broadcast_name = broadcast_name,
+ .streaming_phy = GetStreamingPhy(),
+ .codec_wrapper = codec_qos_pair->first,
+ .qos_config = codec_qos_pair->second,
+ .announcement =
+ prepareBasicAnnouncement(codec_qos_pair->first, subgroup_ltvs),
+ .broadcast_code = std::move(broadcast_code)};
+ if (is_public) {
+ msg.public_announcement =
+ preparePublicAnnouncement(public_features, public_ltv);
+ }
+
+ // If there is ongoing ISO traffic, it might be a unicast stream
+ if (is_iso_running_) {
+ LOG_INFO("Iso is still active. Queueing broadcast creation for later.");
+ if (queued_create_broadcast_request_) {
+ LOG_WARN(
+ "Already queued. Updating queued broadcast creation with the new "
+ "configuration.");
+ }
+ queued_create_broadcast_request_ = std::move(msg);
+ return;
+ }
+
+ InstantiateBroadcast(std::move(msg));
+ }
+
+ void InstantiateBroadcast(BroadcastStateMachineConfig msg) {
LOG_INFO("CreateAudioBroadcast");
- // Notify the error instead just fail silently
+ /* Put the new broadcast on the initialization queue, notify the error and
+ * drop the pending broadcast data if init fails.
+ */
+ pending_broadcasts_.push_back(
+ BroadcastStateMachine::CreateInstance(std::move(msg)));
if (!pending_broadcasts_.back()->Initialize()) {
pending_broadcasts_.pop_back();
callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid,
@@ -578,13 +590,13 @@
void StartAudioBroadcast(uint32_t broadcast_id) override {
LOG_INFO("Starting broadcast_id=%d", broadcast_id);
- if (queued_start_broadcast_request_.IsQueuedBroadcast()) {
+ if (queued_start_broadcast_request_) {
LOG_ERROR("Not processed yet start broadcast request");
return;
}
if (is_iso_running_) {
- queued_start_broadcast_request_.SetStartBroadcastRequest(broadcast_id);
+ queued_start_broadcast_request_ = broadcast_id;
return;
}
@@ -761,14 +773,20 @@
void IsoTrafficEventCb(bool is_active) {
is_iso_running_ = is_active;
LOG_INFO("is_iso_running: %d", is_iso_running_);
-
if (!is_iso_running_) {
- if (queued_start_broadcast_request_.IsQueuedBroadcast()) {
- queued_start_broadcast_request_.StartAudioBroadcast();
- }
+ if (queued_start_broadcast_request_) {
+ auto broadcast_id = *queued_start_broadcast_request_;
+ queued_start_broadcast_request_ = std::nullopt;
- if (queued_create_broadcast_request_.IsQueuedBroadcast()) {
- queued_create_broadcast_request_.CreateAudioBroadcast();
+ LOG_INFO("Start queued broadcast.");
+ StartAudioBroadcast(broadcast_id);
+ }
+ if (queued_create_broadcast_request_) {
+ auto broadcast_msg = std::move(*queued_create_broadcast_request_);
+ queued_create_broadcast_request_ = std::nullopt;
+
+ LOG_INFO("Create queued broadcast.");
+ InstantiateBroadcast(std::move(broadcast_msg));
}
}
}
@@ -1121,102 +1139,11 @@
std::vector<std::unique_ptr<le_audio::CodecInterface>> sw_enc_;
} audio_receiver_;
- static class QueuedCreateBroadcastRequest {
- public:
- bool IsQueuedBroadcast() {
- LOG_INFO();
-
- return is_queued_;
- }
-
- void ClearQueuedBroadcast() {
- LOG_INFO();
-
- is_queued_ = false;
- }
-
- void SetCreateBroadcastRequest(
- bool is_public, const std::string& broadcast_name,
- const std::optional<bluetooth::le_audio::BroadcastCode>& broadcast_code,
- const std::vector<uint8_t>& public_metadata,
- const std::vector<uint8_t>& subgroup_quality,
- const std::vector<std::vector<uint8_t>>& subgroup_metadata) {
- LOG_INFO();
-
- is_public_ = is_public;
- broadcast_name_ = broadcast_name;
- broadcast_code_ = broadcast_code;
- public_metadata_ = public_metadata;
- subgroup_quality_ = subgroup_quality;
- subgroup_metadata_ = subgroup_metadata;
-
- is_queued_ = true;
- }
-
- void CreateAudioBroadcast() {
- if (!instance) return;
-
- LOG_INFO("Create queued broadcast");
-
- is_queued_ = false;
-
- instance->CreateAudioBroadcast(is_public_, broadcast_name_,
- broadcast_code_, public_metadata_,
- subgroup_quality_, subgroup_metadata_);
- }
-
- private:
- /* Queued broadcast data */
- bool is_queued_;
- bool is_public_;
- std::string broadcast_name_;
- std::optional<bluetooth::le_audio::BroadcastCode> broadcast_code_;
- std::vector<uint8_t> public_metadata_;
- std::vector<uint8_t> subgroup_quality_;
- std::vector<std::vector<uint8_t>> subgroup_metadata_;
- } queued_create_broadcast_request_;
-
- static class QueuedStartBroadcastRequest {
- public:
- bool IsQueuedBroadcast() {
- LOG_INFO();
-
- return is_queued_;
- }
-
- void ClearQueuedBroadcast() {
- LOG_INFO();
-
- is_queued_ = false;
- }
-
- void SetStartBroadcastRequest(uint32_t broadcast_id) {
- LOG_INFO();
-
- broadcast_id_ = broadcast_id;
-
- is_queued_ = true;
- }
-
- void StartAudioBroadcast() {
- if (!instance) return;
-
- LOG_INFO("Start queued broadcast");
-
- is_queued_ = false;
-
- instance->StartAudioBroadcast(broadcast_id_);
- }
-
- private:
- /* Queued broadcast data */
- bool is_queued_;
- uint32_t broadcast_id_;
- } queued_start_broadcast_request_;
-
bluetooth::le_audio::LeAudioBroadcasterCallbacks* callbacks_;
std::map<uint32_t, std::unique_ptr<BroadcastStateMachine>> broadcasts_;
std::vector<std::unique_ptr<BroadcastStateMachine>> pending_broadcasts_;
+ std::optional<BroadcastStateMachineConfig> queued_create_broadcast_request_;
+ std::optional<uint32_t> queued_start_broadcast_request_;
/* Some BIG params are set globally */
uint8_t current_phy_;
@@ -1235,10 +1162,6 @@
LeAudioBroadcasterImpl::audio_receiver_;
LeAudioBroadcasterImpl::BroadcastAdvertisingCallbacks
LeAudioBroadcasterImpl::state_machine_adv_callbacks_;
-LeAudioBroadcasterImpl::QueuedCreateBroadcastRequest
- LeAudioBroadcasterImpl::queued_create_broadcast_request_;
-LeAudioBroadcasterImpl::QueuedStartBroadcastRequest
- LeAudioBroadcasterImpl::queued_start_broadcast_request_;
} /* namespace */
void LeAudioBroadcaster::Initialize(
@@ -1269,10 +1192,7 @@
/* Register for active traffic */
IsoManager::GetInstance()->RegisterOnIsoTrafficActiveCallback(
[](bool is_active) {
- if (!instance) {
- return;
- }
- instance->IsoTrafficEventCb(is_active);
+ if (instance) instance->IsoTrafficEventCb(is_active);
});
}
diff --git a/system/bta/le_audio/broadcaster/state_machine.cc b/system/bta/le_audio/broadcaster/state_machine.cc
index 64effcb..8decd18 100644
--- a/system/bta/le_audio/broadcaster/state_machine.cc
+++ b/system/bta/le_audio/broadcaster/state_machine.cc
@@ -29,7 +29,7 @@
#include "bta/le_audio/le_audio_types.h"
#include "common/strings.h"
#include "hci/le_advertising_manager.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#include "osi/include/properties.h"
#include "stack/include/btm_iso_api.h"
diff --git a/system/bta/le_audio/client.cc b/system/bta/le_audio/client.cc
index 54c3695..0dd9dbe 100644
--- a/system/bta/le_audio/client.cc
+++ b/system/bta/le_audio/client.cc
@@ -21,6 +21,7 @@
#include <lc3.h>
#include <deque>
+#include <map>
#include <mutex>
#include <optional>
@@ -739,6 +740,7 @@
ToString(group->cig.GetState()).c_str());
if (group->IsEmpty() &&
(group->cig.GetState() == le_audio::types::CigState::NONE)) {
+ lastNotifiedGroupStreamStatusMap_.erase(group->group_id_);
aseGroups_.Remove(group->group_id_);
}
}
@@ -1042,6 +1044,11 @@
bool IsInVoipCall() override { return in_voip_call_; }
+ bool IsInStreaming() override {
+ return audio_sender_state_ == AudioState::STARTED ||
+ audio_receiver_state_ == AudioState::STARTED;
+ }
+
void SetUnicastMonitorMode(uint8_t direction, bool enable) override {
if (!IS_FLAG_ENABLED(leaudio_broadcast_audio_handover_policies)) {
LOG_WARN("Monitor mode is disabled, Set Unicast Monitor mode is ignored");
@@ -1315,8 +1322,8 @@
/* Reset sink listener notified status */
sink_monitor_notified_status_ = std::nullopt;
- callbacks_->OnGroupStatus(active_group_id_, GroupStatus::ACTIVE);
SendAudioGroupSelectableCodecConfigChanged(group);
+ callbacks_->OnGroupStatus(active_group_id_, GroupStatus::ACTIVE);
}
void SetEnableState(const RawAddress& address, bool enabled) override {
@@ -3840,6 +3847,7 @@
}
groupStateMachine_->Cleanup();
aseGroups_.Cleanup();
+ lastNotifiedGroupStreamStatusMap_.clear();
leAudioDevices_.Cleanup(gatt_if_);
if (gatt_if_) BTA_GATTC_AppDeregister(gatt_if_);
@@ -5415,6 +5423,30 @@
stream_setup_start_timestamp_ = 0;
}
+ void notifyGroupStreamStatus(int group_id,
+ GroupStreamStatus groupStreamStatus) {
+ if (!IS_FLAG_ENABLED(leaudio_callback_on_group_stream_status)) {
+ return;
+ }
+
+ GroupStreamStatus newGroupStreamStatus = GroupStreamStatus::IDLE;
+ if (groupStreamStatus == GroupStreamStatus::STREAMING) {
+ newGroupStreamStatus = GroupStreamStatus::STREAMING;
+ }
+
+ auto it = lastNotifiedGroupStreamStatusMap_.find(group_id);
+
+ if (it != lastNotifiedGroupStreamStatusMap_.end()) {
+ if (it->second != newGroupStreamStatus) {
+ callbacks_->OnGroupStreamStatus(group_id, newGroupStreamStatus);
+ it->second = newGroupStreamStatus;
+ }
+ } else {
+ callbacks_->OnGroupStreamStatus(group_id, newGroupStreamStatus);
+ lastNotifiedGroupStreamStatusMap_.emplace(group_id, newGroupStreamStatus);
+ }
+ }
+
void OnStateMachineStatusReportCb(int group_id, GroupStreamStatus status) {
LOG_INFO(
"status: %d , group_id: %d, audio_sender_state %s, "
@@ -5423,6 +5455,9 @@
bluetooth::common::ToString(audio_sender_state_).c_str(),
bluetooth::common::ToString(audio_receiver_state_).c_str());
LeAudioDeviceGroup* group = aseGroups_.FindById(group_id);
+
+ notifyGroupStreamStatus(group_id, status);
+
switch (status) {
case GroupStreamStatus::STREAMING: {
ASSERT_LOG(group_id == active_group_id_, "invalid group id %d!=%d",
@@ -5709,6 +5744,8 @@
base::WeakPtrFactory<LeAudioClientImpl> weak_factory_{this};
+ std::map<int, GroupStreamStatus> lastNotifiedGroupStreamStatusMap_;
+
void ClientAudioInterfaceRelease() {
if (le_audio_source_hal_client_) {
le_audio_source_hal_client_->Stop();
@@ -5990,6 +6027,13 @@
bool LeAudioClient::IsLeAudioClientRunning(void) { return instance != nullptr; }
+bool LeAudioClient::IsLeAudioClientInStreaming(void) {
+ if (!instance) {
+ return false;
+ }
+ return instance->IsInStreaming();
+}
+
LeAudioClient* LeAudioClient::Get() {
CHECK(instance);
return instance;
diff --git a/system/bta/le_audio/client_linux.cc b/system/bta/le_audio/client_linux.cc
index f905add..946deed 100644
--- a/system/bta/le_audio/client_linux.cc
+++ b/system/bta/le_audio/client_linux.cc
@@ -79,3 +79,4 @@
return false;
}
bool LeAudioClient::IsLeAudioClientRunning() { return false; }
+bool LeAudioClient::IsLeAudioClientInStreaming() { return false; }
diff --git a/system/bta/le_audio/codec_interface.cc b/system/bta/le_audio/codec_interface.cc
index 5a0baf3..b4ede54b 100644
--- a/system/bta/le_audio/codec_interface.cc
+++ b/system/bta/le_audio/codec_interface.cc
@@ -25,7 +25,7 @@
#include <optional>
#include <vector>
-#include "osi/include/log.h"
+#include "os/log.h"
namespace le_audio {
diff --git a/system/bta/le_audio/codec_manager.cc b/system/bta/le_audio/codec_manager.cc
index ecd18aa..c01d34a 100644
--- a/system/bta/le_audio/codec_manager.cc
+++ b/system/bta/le_audio/codec_manager.cc
@@ -21,7 +21,7 @@
#include "device/include/controller.h"
#include "le_audio_set_configuration_provider.h"
#include "le_audio_utils.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#include "osi/include/properties.h"
#include "stack/include/hcimsgs.h"
diff --git a/system/bta/le_audio/content_control_id_keeper.cc b/system/bta/le_audio/content_control_id_keeper.cc
index 2ff0bad..75042b9 100644
--- a/system/bta/le_audio/content_control_id_keeper.cc
+++ b/system/bta/le_audio/content_control_id_keeper.cc
@@ -23,7 +23,7 @@
#include "common/strings.h"
#include "le_audio_types.h"
-#include "osi/include/log.h"
+#include "os/log.h"
namespace {
diff --git a/system/bta/le_audio/devices.h b/system/bta/le_audio/devices.h
index 5738794..db16262 100644
--- a/system/bta/le_audio/devices.h
+++ b/system/bta/le_audio/devices.h
@@ -37,8 +37,8 @@
#include "gatt_api.h"
#include "le_audio_log_history.h"
#include "le_audio_types.h"
+#include "os/log.h"
#include "osi/include/alarm.h"
-#include "osi/include/log.h"
#include "osi/include/properties.h"
#include "raw_address.h"
diff --git a/system/bta/le_audio/le_audio_client_test.cc b/system/bta/le_audio/le_audio_client_test.cc
index 2af50d4..7d9c5f6 100644
--- a/system/bta/le_audio/le_audio_client_test.cc
+++ b/system/bta/le_audio/le_audio_client_test.cc
@@ -45,7 +45,7 @@
#include "mock_device_groups.h"
#include "mock_iso_manager.h"
#include "mock_state_machine.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#include "test/common/mock_functions.h"
#define TEST_BT com::android::bluetooth::flags
@@ -56,6 +56,7 @@
using testing::AtMost;
using testing::DoAll;
using testing::Expectation;
+using testing::InSequence;
using testing::Invoke;
using testing::Matcher;
using testing::Mock;
@@ -263,6 +264,9 @@
(ConnectionState state, const RawAddress& address), (override));
MOCK_METHOD((void), OnGroupStatus, (int group_id, GroupStatus group_status),
(override));
+ MOCK_METHOD((void), OnGroupStreamStatus,
+ (int group_id, GroupStreamStatus group_stream_status),
+ (override));
MOCK_METHOD((void), OnGroupNodeStatus,
(const RawAddress& bd_addr, int group_id,
GroupNodeStatus node_status),
@@ -8705,6 +8709,297 @@
SyncOnMainLoop();
}
+TEST_F_WITH_FLAGS(UnicastTest, GroupStreamStatus,
+ REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(
+ TEST_BT, leaudio_callback_on_group_stream_status))) {
+ int group_id = bluetooth::groups::kGroupUnknown;
+
+ InSequence s;
+
+ /* Check if all states are properly notified */
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE))
+ .Times(1);
+ state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::IDLE);
+
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id, GroupStreamStatus::STREAMING))
+ .Times(1);
+ state_machine_callbacks_->StatusReportCb(group_id,
+ GroupStreamStatus::STREAMING);
+
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE))
+ .Times(1);
+ state_machine_callbacks_->StatusReportCb(group_id,
+ GroupStreamStatus::RELEASING);
+
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id, GroupStreamStatus::STREAMING))
+ .Times(1);
+ state_machine_callbacks_->StatusReportCb(group_id,
+ GroupStreamStatus::STREAMING);
+
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE))
+ .Times(1);
+ state_machine_callbacks_->StatusReportCb(group_id,
+ GroupStreamStatus::SUSPENDING);
+
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id, GroupStreamStatus::STREAMING))
+ .Times(1);
+ state_machine_callbacks_->StatusReportCb(group_id,
+ GroupStreamStatus::STREAMING);
+
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE))
+ .Times(1);
+ state_machine_callbacks_->StatusReportCb(group_id,
+ GroupStreamStatus::SUSPENDED);
+
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id, GroupStreamStatus::STREAMING))
+ .Times(1);
+ state_machine_callbacks_->StatusReportCb(group_id,
+ GroupStreamStatus::STREAMING);
+
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE))
+ .Times(1);
+ state_machine_callbacks_->StatusReportCb(
+ group_id, GroupStreamStatus::CONFIGURED_AUTONOMOUS);
+
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id, GroupStreamStatus::STREAMING))
+ .Times(1);
+ state_machine_callbacks_->StatusReportCb(group_id,
+ GroupStreamStatus::STREAMING);
+
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE))
+ .Times(1);
+ state_machine_callbacks_->StatusReportCb(
+ group_id, GroupStreamStatus::CONFIGURED_BY_USER);
+
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id, GroupStreamStatus::STREAMING))
+ .Times(1);
+ state_machine_callbacks_->StatusReportCb(group_id,
+ GroupStreamStatus::STREAMING);
+
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE))
+ .Times(1);
+ state_machine_callbacks_->StatusReportCb(group_id,
+ GroupStreamStatus::DESTROYED);
+
+ /* Check if there are no resending of the same state */
+ state_machine_callbacks_->StatusReportCb(group_id,
+ GroupStreamStatus::RELEASING);
+ state_machine_callbacks_->StatusReportCb(group_id,
+ GroupStreamStatus::SUSPENDING);
+ state_machine_callbacks_->StatusReportCb(group_id,
+ GroupStreamStatus::SUSPENDED);
+ state_machine_callbacks_->StatusReportCb(
+ group_id, GroupStreamStatus::CONFIGURED_AUTONOMOUS);
+ state_machine_callbacks_->StatusReportCb(
+ group_id, GroupStreamStatus::CONFIGURED_BY_USER);
+ state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::IDLE);
+
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id, GroupStreamStatus::STREAMING))
+ .Times(1);
+ state_machine_callbacks_->StatusReportCb(group_id,
+ GroupStreamStatus::STREAMING);
+ state_machine_callbacks_->StatusReportCb(group_id,
+ GroupStreamStatus::STREAMING);
+}
+
+TEST_F_WITH_FLAGS(UnicastTest, GroupStreamStatusManyGroups,
+ REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(
+ TEST_BT, leaudio_callback_on_group_stream_status))) {
+ uint8_t group_size = 2;
+ int group_id_1 = 1;
+ int group_id_2 = 2;
+
+ // Report working CSIS
+ ON_CALL(mock_csis_client_module_, IsCsisClientRunning())
+ .WillByDefault(Return(true));
+
+ ON_CALL(mock_csis_client_module_, GetDesiredSize(_))
+ .WillByDefault(Return(group_size));
+
+ // First group - First earbud
+ const RawAddress test_address0 = GetTestAddress(0);
+ EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true))
+ .Times(1);
+ ConnectCsisDevice(test_address0, 1 /*conn_id*/,
+ codec_spec_conf::kLeAudioLocationFrontLeft,
+ codec_spec_conf::kLeAudioLocationFrontLeft, group_size,
+ group_id_1, 1 /* rank*/);
+
+ // First group - Second earbud
+ const RawAddress test_address1 = GetTestAddress(1);
+ EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true))
+ .Times(1);
+ ConnectCsisDevice(test_address1, 2 /*conn_id*/,
+ codec_spec_conf::kLeAudioLocationFrontRight,
+ codec_spec_conf::kLeAudioLocationFrontRight, group_size,
+ group_id_1, 2 /* rank*/, true /*connect_through_csis*/);
+
+ // Second group - First earbud
+ const RawAddress test_address2 = GetTestAddress(2);
+ EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address2, true))
+ .Times(1);
+ ConnectCsisDevice(test_address2, 3 /*conn_id*/,
+ codec_spec_conf::kLeAudioLocationFrontLeft,
+ codec_spec_conf::kLeAudioLocationFrontLeft, group_size,
+ group_id_2, 1 /* rank*/);
+
+ // Second group - Second earbud
+ const RawAddress test_address3 = GetTestAddress(3);
+ EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address3, true))
+ .Times(1);
+ ConnectCsisDevice(test_address3, 4 /*conn_id*/,
+ codec_spec_conf::kLeAudioLocationFrontRight,
+ codec_spec_conf::kLeAudioLocationFrontRight, group_size,
+ group_id_2, 2 /* rank*/, true /*connect_through_csis*/);
+
+ InSequence s;
+
+ // Group 1 IDLE
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id_1, GroupStreamStatus::IDLE))
+ .Times(1);
+ state_machine_callbacks_->StatusReportCb(group_id_1, GroupStreamStatus::IDLE);
+
+ // Group 2 IDLE
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id_2, GroupStreamStatus::IDLE))
+ .Times(1);
+ state_machine_callbacks_->StatusReportCb(group_id_2, GroupStreamStatus::IDLE);
+
+ // Group 1 active and start streaming
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id_1, GroupStreamStatus::STREAMING))
+ .Times(1);
+ LeAudioClient::Get()->GroupSetActive(group_id_1);
+ SyncOnMainLoop();
+ StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id_1);
+ SyncOnMainLoop();
+ Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_);
+
+ // Group 2 active
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id_1, GroupStreamStatus::IDLE))
+ .Times(1);
+ LeAudioClient::Get()->GroupSetActive(group_id_2);
+ SyncOnMainLoop();
+ Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_);
+
+ // Group 2 start streaming
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id_2, GroupStreamStatus::STREAMING))
+ .Times(1);
+ StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id_2);
+ SyncOnMainLoop();
+ Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_);
+}
+
+TEST_F_WITH_FLAGS(UnicastTest, GroupStreamStatusResendAfterRemove,
+ REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(
+ TEST_BT, leaudio_callback_on_group_stream_status))) {
+ uint8_t group_size = 2;
+ int group_id = 1;
+
+ // Report working CSIS
+ ON_CALL(mock_csis_client_module_, IsCsisClientRunning())
+ .WillByDefault(Return(true));
+
+ ON_CALL(mock_csis_client_module_, GetDesiredSize(_))
+ .WillByDefault(Return(group_size));
+
+ // First earbud
+ const RawAddress test_address0 = GetTestAddress(0);
+ EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true))
+ .Times(1);
+ ConnectCsisDevice(test_address0, 1 /*conn_id*/,
+ codec_spec_conf::kLeAudioLocationFrontLeft,
+ codec_spec_conf::kLeAudioLocationFrontLeft, group_size,
+ group_id, 1 /* rank*/);
+
+ // Second earbud
+ const RawAddress test_address1 = GetTestAddress(1);
+ EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true))
+ .Times(1);
+ ConnectCsisDevice(test_address1, 2 /*conn_id*/,
+ codec_spec_conf::kLeAudioLocationFrontRight,
+ codec_spec_conf::kLeAudioLocationFrontRight, group_size,
+ group_id, 2 /* rank*/, true /*connect_through_csis*/);
+
+ Mock::VerifyAndClearExpectations(&mock_btif_storage_);
+
+ InSequence s;
+
+ // Activate group, start streaming and immediately stop
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id, GroupStreamStatus::STREAMING))
+ .Times(1);
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE))
+ .Times(1);
+ LeAudioClient::Get()->GroupSetActive(group_id);
+ SyncOnMainLoop();
+ state_machine_callbacks_->StatusReportCb(group_id,
+ GroupStreamStatus::STREAMING);
+ Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_);
+
+ // No resend
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE))
+ .Times(0);
+ state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::IDLE);
+
+ // No resend after removing only one device
+ /*
+ * StopStream will put calls on main_loop so to keep the correct order
+ * of operations and to avoid races we put the test command on main_loop as
+ * well.
+ */
+ do_in_main_thread(FROM_HERE, base::BindOnce(
+ [](LeAudioClient* client,
+ const RawAddress& test_address0) {
+ client->RemoveDevice(test_address0);
+ },
+ LeAudioClient::Get(), test_address0));
+ SyncOnMainLoop();
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE))
+ .Times(0);
+ state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::IDLE);
+ Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_);
+
+ // Resend after removing last device
+ /*
+ * StopStream will put calls on main_loop so to keep the correct order
+ * of operations and to avoid races we put the test command on main_loop as
+ * well.
+ */
+ do_in_main_thread(FROM_HERE, base::BindOnce(
+ [](LeAudioClient* client,
+ const RawAddress& test_address1) {
+ client->RemoveDevice(test_address1);
+ },
+ LeAudioClient::Get(), test_address1));
+ SyncOnMainLoop();
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupStreamStatus(group_id, GroupStreamStatus::IDLE))
+ .Times(1);
+ state_machine_callbacks_->StatusReportCb(group_id, GroupStreamStatus::IDLE);
+ Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_);
+}
+
TEST_F_WITH_FLAGS(UnicastTestHandoverMode,
SetSinkMonitorModeWhileUnicastIsActive,
REQUIRES_FLAGS_ENABLED(ACONFIG_FLAG(
diff --git a/system/bta/le_audio/le_audio_health_status.cc b/system/bta/le_audio/le_audio_health_status.cc
index 3de70b5..5e548b0 100644
--- a/system/bta/le_audio/le_audio_health_status.cc
+++ b/system/bta/le_audio/le_audio_health_status.cc
@@ -21,7 +21,7 @@
#include "bta/include/bta_groups.h"
#include "common/strings.h"
#include "main/shim/metrics_api.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#include "osi/include/properties.h"
using bluetooth::common::ToString;
diff --git a/system/bta/le_audio/le_audio_log_history.cc b/system/bta/le_audio/le_audio_log_history.cc
index fae625f..fe9dafd 100644
--- a/system/bta/le_audio/le_audio_log_history.cc
+++ b/system/bta/le_audio/le_audio_log_history.cc
@@ -26,7 +26,7 @@
#include "common/circular_buffer.h"
#include "common/strings.h"
#include "main/shim/dumpsys.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#include "osi/include/osi.h"
#include "osi/include/properties.h"
diff --git a/system/bta/le_audio/le_audio_set_configuration_provider_json.cc b/system/bta/le_audio/le_audio_set_configuration_provider_json.cc
index d333820..6d506c2 100644
--- a/system/bta/le_audio/le_audio_set_configuration_provider_json.cc
+++ b/system/bta/le_audio/le_audio_set_configuration_provider_json.cc
@@ -28,7 +28,7 @@
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include "le_audio_set_configuration_provider.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#include "osi/include/osi.h"
#include "osi/include/properties.h"
diff --git a/system/bta/le_audio/le_audio_utils.cc b/system/bta/le_audio/le_audio_utils.cc
index d050681..01ffcca 100644
--- a/system/bta/le_audio/le_audio_utils.cc
+++ b/system/bta/le_audio/le_audio_utils.cc
@@ -19,7 +19,7 @@
#include "bta/le_audio/content_control_id_keeper.h"
#include "common/strings.h"
#include "le_audio_types.h"
-#include "osi/include/log.h"
+#include "os/log.h"
using bluetooth::common::ToString;
using le_audio::types::AudioContexts;
@@ -45,10 +45,15 @@
case AUDIO_USAGE_CALL_ASSISTANT:
return LeAudioContextType::CONVERSATIONAL;
case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
- if (content_type == AUDIO_CONTENT_TYPE_SPEECH)
+ if (content_type == AUDIO_CONTENT_TYPE_SPEECH) {
return LeAudioContextType::CONVERSATIONAL;
- else
- return LeAudioContextType::MEDIA;
+ }
+
+ if (content_type == AUDIO_CONTENT_TYPE_SONIFICATION) {
+ return LeAudioContextType::RINGTONE;
+ }
+
+ return LeAudioContextType::MEDIA;
case AUDIO_USAGE_GAME:
return LeAudioContextType::GAME;
case AUDIO_USAGE_NOTIFICATION:
diff --git a/system/bta/le_audio/storage_helper.cc b/system/bta/le_audio/storage_helper.cc
index 8214eab..92b9cbc 100644
--- a/system/bta/le_audio/storage_helper.cc
+++ b/system/bta/le_audio/storage_helper.cc
@@ -21,7 +21,7 @@
#include "client_parser.h"
#include "common/strings.h"
#include "le_audio_types.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#include "stack/include/bt_types.h"
using le_audio::types::hdl_pair;
diff --git a/system/bta/sys/bta_sys_conn.cc b/system/bta/sys/bta_sys_conn.cc
index 2acbd0d..3c4759f 100644
--- a/system/bta/sys/bta_sys_conn.cc
+++ b/system/bta/sys/bta_sys_conn.cc
@@ -28,7 +28,7 @@
#include "bta/sys/bta_sys_int.h"
#include "internal_include/bt_target.h"
#include "main/shim/dumpsys.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#include "osi/include/osi.h" // UNUSED_ATTR
#include "stack/include/btm_api.h"
#include "types/hci_role.h"
diff --git a/system/bta/sys/bta_sys_main.cc b/system/bta/sys/bta_sys_main.cc
index 50c2f8a..5882416 100644
--- a/system/bta/sys/bta_sys_main.cc
+++ b/system/bta/sys/bta_sys_main.cc
@@ -33,9 +33,9 @@
#include "bta/sys/bta_sys_int.h"
#include "include/hardware/bluetooth.h"
#include "internal_include/bt_target.h"
+#include "os/log.h"
#include "osi/include/alarm.h"
#include "osi/include/allocator.h"
-#include "osi/include/log.h"
#include "stack/include/bt_hdr.h"
#include "stack/include/main_thread.h"
diff --git a/system/bta/test/bta_ag_sco_test.cc b/system/bta/test/bta_ag_sco_test.cc
index 2ef8abb..d3bdb93 100644
--- a/system/bta/test/bta_ag_sco_test.cc
+++ b/system/bta/test/bta_ag_sco_test.cc
@@ -27,6 +27,7 @@
bool btm_peer_supports_esco_ev3(const RawAddress& remote_bda) { return true; }
tBTM_CB btm_cb;
LeAudioClient* LeAudioClient::Get() { return nullptr; }
+bool LeAudioClient::IsLeAudioClientInStreaming() { return false; }
const RawAddress kRawAddress({0x11, 0x22, 0x33, 0x44, 0x55, 0x66});
diff --git a/system/bta/test/bta_dip_test.cc b/system/bta/test/bta_dip_test.cc
index 3ad0f12..b9b4cfa 100644
--- a/system/bta/test/bta_dip_test.cc
+++ b/system/bta/test/bta_dip_test.cc
@@ -194,6 +194,16 @@
ASSERT_EQ(record.dip.product, 0);
ASSERT_EQ(record.dip.version, 0);
ASSERT_EQ(record.dip.primary_record, true);
+
+ // a size zero for boolean won't be accepted
+ g_attr_vendor_product_primary_record.attr_len_type =
+ (BOOLEAN_DESC_TYPE << 12) | 0;
+
+ record = {};
+
+ g_attr_vendor_product_primary_record.attr_value.v.u8 = 1;
+ bluetooth::testing::bta_create_dip_sdp_record(&record, &g_rec);
+ ASSERT_EQ(record.dip.primary_record, false);
}
diff --git a/system/bta/test/bta_hh_test.cc b/system/bta/test/bta_hh_test.cc
index b9b2b55..21c07f8 100644
--- a/system/bta/test/bta_hh_test.cc
+++ b/system/bta/test/bta_hh_test.cc
@@ -21,10 +21,12 @@
#include "bta/dm/bta_dm_int.h"
#include "bta/hh/bta_hh_int.h"
#include "bta/include/bta_hh_api.h"
+#include "bta/include/bta_le_audio_api.h"
#include "osi/include/allocator.h"
#include "test/common/mock_functions.h"
#include "test/mock/mock_osi_allocator.h"
+bool LeAudioClient::IsLeAudioClientInStreaming() { return false; }
namespace {
std::array<uint8_t, 32> data32 = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
@@ -77,7 +79,9 @@
.offset = 0,
.layer_specific = 0,
},
- .addr = RawAddress::kEmpty,
+ .link_spec.addrt.bda = RawAddress::kEmpty,
+ .link_spec.addrt.type = BLE_ADDR_PUBLIC,
+ .link_spec.transport = BT_TRANSPORT_AUTO,
.data = 32,
.p_data = static_cast<BT_HDR*>(osi_calloc(32 + sizeof(BT_HDR))),
},
diff --git a/system/btcore/src/osi_module.cc b/system/btcore/src/osi_module.cc
index 9481c87..6a9f939 100644
--- a/system/btcore/src/osi_module.cc
+++ b/system/btcore/src/osi_module.cc
@@ -19,10 +19,11 @@
#define LOG_TAG "bt_osi_module"
#include "btcore/include/osi_module.h"
+
#include "btcore/include/module.h"
+#include "os/log.h"
#include "osi/include/alarm.h"
#include "osi/include/future.h"
-#include "osi/include/log.h"
#include "osi/include/osi.h"
#include "osi/include/wakelock.h"
diff --git a/system/btif/Android.bp b/system/btif/Android.bp
index bc64535..fe330ca 100644
--- a/system/btif/Android.bp
+++ b/system/btif/Android.bp
@@ -613,11 +613,13 @@
":TestMockBtu",
":TestMockHci",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
":TestMockStack",
":TestMockUdrv",
"test/btif_hh_test.cc",
],
generated_headers: [
+ "BluetoothGeneratedBundlerSchema_h_bfbs",
"BluetoothGeneratedDumpsysDataSchema_h",
],
header_libs: ["libbluetooth_headers"],
@@ -736,11 +738,13 @@
":TestMockBtu",
":TestMockHci",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
":TestMockStack",
":TestMockUdrv",
"test/btif_core_test.cc",
],
generated_headers: [
+ "BluetoothGeneratedBundlerSchema_h_bfbs",
"BluetoothGeneratedDumpsysDataSchema_h",
],
header_libs: ["libbluetooth_headers"],
diff --git a/system/btif/co/bta_hh_co.cc b/system/btif/co/bta_hh_co.cc
index 366fe5f..8884857f 100644
--- a/system/btif/co/bta_hh_co.cc
+++ b/system/btif/co/bta_hh_co.cc
@@ -33,12 +33,12 @@
#include "bta_hh_api.h"
#include "btif_hh.h"
#include "device/include/controller.h"
-#include "gd/storage/config_keys.h"
#include "include/check.h"
#include "os/log.h"
#include "osi/include/allocator.h"
#include "osi/include/compat.h"
#include "osi/include/osi.h"
+#include "storage/config_keys.h"
#include "types/raw_address.h"
const char* dev_path = "/dev/uhid";
@@ -275,7 +275,7 @@
ev.type = UHID_DESTROY;
uhid_write(p_dev->fd, &ev);
LOG_DEBUG("Closing fd=%d, addr:%s", p_dev->fd,
- ADDRESS_TO_LOGGABLE_CSTR(p_dev->bd_addr));
+ ADDRESS_TO_LOGGABLE_CSTR(p_dev->link_spec));
close(p_dev->fd);
p_dev->fd = -1;
}
@@ -362,7 +362,7 @@
/* Todo: Disconnect if loop exited due to a failure */
LOG_INFO("Polling thread stopped for device %s",
- ADDRESS_TO_LOGGABLE_CSTR(p_dev->bd_addr));
+ ADDRESS_TO_LOGGABLE_CSTR(p_dev->link_spec));
p_dev->hh_poll_thread_id = -1;
p_dev->hh_keep_polling = 0;
uhid_fd_close(p_dev);
@@ -412,7 +412,7 @@
LOG_INFO(
"Found an existing device with the same handle dev_status=%d, "
"address=%s, attr_mask=0x%04x, sub_class=0x%02x, app_id=%d",
- p_dev->dev_status, ADDRESS_TO_LOGGABLE_CSTR(p_dev->bd_addr),
+ p_dev->dev_status, ADDRESS_TO_LOGGABLE_CSTR(p_dev->link_spec),
p_dev->attr_mask, p_dev->sub_class, p_dev->app_id);
if (!uhid_fd_open(p_dev)) {
@@ -478,7 +478,7 @@
******************************************************************************/
void bta_hh_co_close(btif_hh_device_t* p_dev) {
LOG_INFO("Closing device handle=%d, status=%d, address=%s", p_dev->dev_handle,
- p_dev->dev_status, ADDRESS_TO_LOGGABLE_CSTR(p_dev->bd_addr));
+ p_dev->dev_status, ADDRESS_TO_LOGGABLE_CSTR(p_dev->link_spec));
/* Clear the queues */
fixed_queue_flush(p_dev->get_rpt_id_queue, osi_free);
@@ -517,8 +517,8 @@
******************************************************************************/
void bta_hh_co_data(uint8_t dev_handle, uint8_t* p_rpt, uint16_t len,
tBTA_HH_PROTO_MODE mode, uint8_t sub_class,
- uint8_t ctry_code, UNUSED_ATTR const RawAddress& peer_addr,
- uint8_t app_id) {
+ uint8_t ctry_code,
+ UNUSED_ATTR const tAclLinkSpec& link_spec, uint8_t app_id) {
btif_hh_device_t* p_dev;
LOG_VERBOSE(
@@ -590,7 +590,7 @@
strlcpy((char*)ev.u.create.name, dev_name, sizeof(ev.u.create.name));
// TODO (b/258090765) fix: ToString -> ToColonSepHexString
snprintf((char*)ev.u.create.uniq, sizeof(ev.u.create.uniq), "%s",
- p_dev->bd_addr.ToString().c_str());
+ p_dev->link_spec.addrt.bda.ToString().c_str());
// Write controller address to phys field to correlate the hid device with a
// specific bluetooth controller.
@@ -752,12 +752,12 @@
* Returns void.
*
******************************************************************************/
-void bta_hh_le_co_rpt_info(const RawAddress& remote_bda,
+void bta_hh_le_co_rpt_info(const tAclLinkSpec& link_spec,
tBTA_HH_RPT_CACHE_ENTRY* p_entry,
UNUSED_ATTR uint8_t app_id) {
unsigned idx = 0;
- std::string addrstr = remote_bda.ToString();
+ std::string addrstr = link_spec.addrt.ToString();
const char* bdstr = addrstr.c_str();
size_t len = btif_config_get_bin_length(bdstr, BTIF_STORAGE_KEY_HID_REPORT);
@@ -775,7 +775,7 @@
btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_REPORT_VERSION,
BTA_HH_CACHE_REPORT_VERSION);
LOG_VERBOSE("%s() - Saving report; dev=%s, idx=%d", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(remote_bda), idx);
+ ADDRESS_TO_LOGGABLE_CSTR(link_spec), idx);
}
}
@@ -795,10 +795,10 @@
* Returns the cached report array
*
******************************************************************************/
-tBTA_HH_RPT_CACHE_ENTRY* bta_hh_le_co_cache_load(const RawAddress& remote_bda,
+tBTA_HH_RPT_CACHE_ENTRY* bta_hh_le_co_cache_load(const tAclLinkSpec& link_spec,
uint8_t* p_num_rpt,
UNUSED_ATTR uint8_t app_id) {
- std::string addrstr = remote_bda.ToString();
+ std::string addrstr = link_spec.addrt.ToString();
const char* bdstr = addrstr.c_str();
size_t len = btif_config_get_bin_length(bdstr, BTIF_STORAGE_KEY_HID_REPORT);
@@ -813,14 +813,14 @@
&cache_version);
if (cache_version != BTA_HH_CACHE_REPORT_VERSION) {
- bta_hh_le_co_reset_rpt_cache(remote_bda, app_id);
+ bta_hh_le_co_reset_rpt_cache(link_spec, app_id);
return NULL;
}
*p_num_rpt = len / sizeof(tBTA_HH_RPT_CACHE_ENTRY);
LOG_VERBOSE("%s() - Loaded %d reports; dev=%s", __func__, *p_num_rpt,
- ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
+ ADDRESS_TO_LOGGABLE_CSTR(link_spec));
return sReportCache;
}
@@ -836,13 +836,13 @@
* Returns none
*
******************************************************************************/
-void bta_hh_le_co_reset_rpt_cache(const RawAddress& remote_bda,
+void bta_hh_le_co_reset_rpt_cache(const tAclLinkSpec& link_spec,
UNUSED_ATTR uint8_t app_id) {
- std::string addrstr = remote_bda.ToString();
+ std::string addrstr = link_spec.addrt.ToString();
const char* bdstr = addrstr.c_str();
btif_config_remove(bdstr, BTIF_STORAGE_KEY_HID_REPORT);
btif_config_remove(bdstr, BTIF_STORAGE_KEY_HID_REPORT_VERSION);
LOG_VERBOSE("%s() - Reset cache for bda %s", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
+ ADDRESS_TO_LOGGABLE_CSTR(link_spec));
}
diff --git a/system/btif/include/btif_api.h b/system/btif/include/btif_api.h
index 2a7df05..54106e0 100644
--- a/system/btif/include/btif_api.h
+++ b/system/btif/include/btif_api.h
@@ -266,13 +266,28 @@
/*******************************************************************************
*
* Function btif_dm_get_connection_state
+ * btif_dm_get_connection_state_sync
*
- * Description Returns whether the remote device is currently connected
+ * Description Returns bitmask on remote device connection state indicating
+ * connection and encryption. The `_sync` version properly
+ * synchronizes the state and is the preferred mechanism.
+ * NOTE: Currently no address resolution is attempted upon
+ * LE random addresses.
*
- * Returns 0 if not connected
+ * Returns '000 (0x0000) if not connected
+ * '001 (0x0001) Connected with no encryption to remote
+ * device on BR/EDR or LE ACL
+ * '011 (0x0003) Connected with encryption to remote
+ * device on BR/EDR ACL
+ * '101 (0x0005) Connected with encruption to remote
+ * device on LE ACL
+ * '111 (0x0007) Connected with encruption to remote
+ * device on both BR/EDR and LE ACLs
+ * All other values are reserved
*
******************************************************************************/
uint16_t btif_dm_get_connection_state(const RawAddress& bd_addr);
+uint16_t btif_dm_get_connection_state_sync(const RawAddress& bd_addr);
/*******************************************************************************
*
diff --git a/system/btif/include/btif_common.h b/system/btif/include/btif_common.h
index c4a55b3..b10b845 100644
--- a/system/btif/include/btif_common.h
+++ b/system/btif/include/btif_common.h
@@ -29,7 +29,7 @@
#include "abstract_message_loop.h"
#include "bta/include/bta_api.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#include "osi/include/osi.h"
#include "stack/include/bt_hdr.h"
#include "types/raw_address.h"
diff --git a/system/btif/include/btif_hh.h b/system/btif/include/btif_hh.h
index c69cc48..dbe3749 100644
--- a/system/btif/include/btif_hh.h
+++ b/system/btif/include/btif_hh.h
@@ -29,6 +29,7 @@
#include "macros.h"
#include "osi/include/alarm.h"
#include "osi/include/fixed_queue.h"
+#include "types/ble_address_with_type.h"
#include "types/raw_address.h"
/*******************************************************************************
@@ -86,7 +87,7 @@
typedef struct {
bthh_connection_state_t dev_status;
uint8_t dev_handle;
- RawAddress bd_addr;
+ tAclLinkSpec link_spec;
tBTA_HH_ATTR_MASK attr_mask;
uint8_t sub_class;
uint8_t app_id;
@@ -105,7 +106,7 @@
/* Control block to maintain properties of devices */
typedef struct {
uint8_t dev_handle;
- RawAddress bd_addr;
+ tAclLinkSpec link_spec;
tBTA_HH_ATTR_MASK attr_mask;
} btif_hh_added_device_t;
@@ -119,7 +120,7 @@
uint32_t device_num;
btif_hh_added_device_t added_devices[BTIF_HH_MAX_ADDED_DEV];
bool service_dereg_active;
- RawAddress pending_conn_address;
+ tAclLinkSpec pending_link_spec;
} btif_hh_cb_t;
/*******************************************************************************
@@ -129,10 +130,11 @@
extern btif_hh_cb_t btif_hh_cb;
btif_hh_device_t* btif_hh_find_connected_dev_by_handle(uint8_t handle);
-void btif_hh_remove_device(RawAddress bd_addr);
-bool btif_hh_add_added_dev(const RawAddress& bda, tBTA_HH_ATTR_MASK attr_mask);
-bt_status_t btif_hh_virtual_unplug(const RawAddress* bd_addr);
-void btif_hh_disconnect(RawAddress* bd_addr);
+void btif_hh_remove_device(const tAclLinkSpec& link_spec);
+bool btif_hh_add_added_dev(const tAclLinkSpec& link_spec,
+ tBTA_HH_ATTR_MASK attr_mask);
+bt_status_t btif_hh_virtual_unplug(const tAclLinkSpec* link_spec);
+void btif_hh_disconnect(const tAclLinkSpec* link_spec);
void btif_hh_setreport(btif_hh_device_t* p_dev, bthh_report_type_t r_type,
uint16_t size, uint8_t* report);
void btif_hh_senddata(btif_hh_device_t* p_dev, uint16_t size, uint8_t* report);
diff --git a/system/btif/include/btif_storage.h b/system/btif/include/btif_storage.h
index 8bd9b4ea..394cd5b 100644
--- a/system/btif/include/btif_storage.h
+++ b/system/btif/include/btif_storage.h
@@ -391,8 +391,6 @@
void btif_storage_load_bonded_groups(void);
void btif_storage_remove_groups(const RawAddress& address);
-void btif_storage_set_csis_autoconnect(const RawAddress& addr,
- bool autoconnect);
void btif_storage_update_csis_info(const RawAddress& addr);
void btif_storage_load_bonded_csis_devices();
void btif_storage_remove_csis_device(const RawAddress& address);
diff --git a/system/btif/include/core_callbacks.h b/system/btif/include/core_callbacks.h
index ddeaf5e..421211b 100644
--- a/system/btif/include/core_callbacks.h
+++ b/system/btif/include/core_callbacks.h
@@ -107,9 +107,9 @@
// that profiles can register themselves to.
struct HACK_ProfileInterface {
// HID hacks
- bt_status_t (*btif_hh_connect)(const RawAddress* bd_addr);
- bt_status_t (*btif_hh_virtual_unplug)(const RawAddress* bd_addr);
- tBTA_HH_STATUS (*bta_hh_read_ssr_param)(const RawAddress& bd_addr,
+ bt_status_t (*btif_hh_connect)(const tAclLinkSpec* link_spec);
+ bt_status_t (*btif_hh_virtual_unplug)(const tAclLinkSpec* link_spec);
+ tBTA_HH_STATUS (*bta_hh_read_ssr_param)(const tAclLinkSpec& link_spec,
uint16_t* p_max_ssr_lat,
uint16_t* p_min_ssr_tout);
diff --git a/system/btif/include/mock_core_callbacks.h b/system/btif/include/mock_core_callbacks.h
index 5e88fe3..5e154c0 100644
--- a/system/btif/include/mock_core_callbacks.h
+++ b/system/btif/include/mock_core_callbacks.h
@@ -96,13 +96,13 @@
MockCodecInterface mock_codec_lc3Codec;
HACK_ProfileInterface mock_HACK_profile_interface = {
- .btif_hh_connect = [](const RawAddress* /* bd_addr */) -> bt_status_t {
+ .btif_hh_connect = [](const tAclLinkSpec* /* link_spec */) -> bt_status_t {
return BT_STATUS_SUCCESS;
},
- .btif_hh_virtual_unplug = [](const RawAddress* /* bd_addr */)
+ .btif_hh_virtual_unplug = [](const tAclLinkSpec* /* link_spec */)
-> bt_status_t { return BT_STATUS_SUCCESS; },
.bta_hh_read_ssr_param =
- [](const RawAddress& /* bd_addr */, uint16_t* /* p_max_ssr_lat */,
+ [](const tAclLinkSpec& /* link_spec */, uint16_t* /* p_max_ssr_lat */,
uint16_t* /* p_min_ssr_tout */) -> tBTA_HH_STATUS {
return BTA_HH_OK;
},
diff --git a/system/btif/src/bluetooth.cc b/system/btif/src/bluetooth.cc
index 9c1fa40..efd77da 100644
--- a/system/btif/src/bluetooth.cc
+++ b/system/btif/src/bluetooth.cc
@@ -27,6 +27,7 @@
#define LOG_TAG "bt_btif"
+#include <android_bluetooth_flags.h>
#include <base/logging.h>
#include <hardware/bluetooth.h>
#include <hardware/bluetooth_headset_interface.h>
@@ -88,7 +89,6 @@
#include "device/include/device_iot_config.h"
#include "device/include/interop.h"
#include "device/include/interop_config.h"
-#include "gd/storage/config_keys.h"
#include "include/check.h"
#include "internal_include/bt_target.h"
#include "main/shim/dumpsys.h"
@@ -110,6 +110,7 @@
#include "stack/include/hidh_api.h"
#include "stack/include/main_thread.h"
#include "stack/include/pan_api.h"
+#include "storage/config_keys.h"
#include "types/raw_address.h"
using bluetooth::csis::CsisClientInterface;
@@ -174,7 +175,7 @@
bt_status_t btif_hh_execute_service(bool b_enable);
bt_status_t btif_hf_client_execute_service(bool b_enable);
bt_status_t btif_sdp_execute_service(bool b_enable);
-bt_status_t btif_hh_connect(const RawAddress* bd_addr);
+bt_status_t btif_hh_connect(const tAclLinkSpec* link_spec);
bt_status_t btif_hd_execute_service(bool b_enable);
/*******************************************************************************
@@ -303,7 +304,12 @@
void removeDeviceFromProfiles(const RawAddress& bd_addr) override {
/*special handling for HID devices */
#if (defined(BTA_HH_INCLUDED) && (BTA_HH_INCLUDED == TRUE))
- btif_hh_remove_device(bd_addr);
+ tAclLinkSpec link_spec;
+ link_spec.addrt.bda = bd_addr;
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ link_spec.transport = BT_TRANSPORT_AUTO;
+
+ btif_hh_remove_device(link_spec);
#endif
#if (defined(BTA_HD_INCLUDED) && (BTA_HD_INCLUDED == TRUE))
btif_hd_remove_device(bd_addr);
@@ -655,7 +661,11 @@
if (bd_addr == nullptr) return 0;
- return btif_dm_get_connection_state(*bd_addr);
+ if (IS_FLAG_ENABLED(api_get_connection_state_sync_on_main)) {
+ return btif_dm_get_connection_state_sync(*bd_addr);
+ } else {
+ return btif_dm_get_connection_state(*bd_addr);
+ }
}
static int pin_reply(const RawAddress* bd_addr, uint8_t accept, uint8_t pin_len,
diff --git a/system/btif/src/btif_a2dp.cc b/system/btif/src/btif_a2dp.cc
index 4308d63..0e6f217 100644
--- a/system/btif/src/btif_a2dp.cc
+++ b/system/btif/src/btif_a2dp.cc
@@ -35,7 +35,7 @@
#include "btif_hf.h"
#include "btif_util.h"
#include "internal_include/bt_trace.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#include "types/raw_address.h"
void btif_a2dp_on_idle(const RawAddress& peer_addr) {
diff --git a/system/btif/src/btif_av.cc b/system/btif/src/btif_av.cc
index dacdf5f..4b5fdd5 100644
--- a/system/btif/src/btif_av.cc
+++ b/system/btif/src/btif_av.cc
@@ -1145,7 +1145,8 @@
if (a2dp_offload_enabled_) {
tBTM_BLE_VSC_CB vsc_cb = {};
BTM_BleGetVendorCapabilities(&vsc_cb);
- bool supports_a2dp_hw_offload_v2 = vsc_cb.version_supported >= 0x0103;
+ bool supports_a2dp_hw_offload_v2 =
+ vsc_cb.version_supported >= 0x0104 && vsc_cb.a2dp_offload_v2_support;
bluetooth::audio::a2dp::update_codec_offloading_capabilities(
offloading_preference, supports_a2dp_hw_offload_v2);
}
diff --git a/system/btif/src/btif_bqr.cc b/system/btif/src/btif_bqr.cc
index b8a5fab..5ee7a9d 100644
--- a/system/btif/src/btif_bqr.cc
+++ b/system/btif/src/btif_bqr.cc
@@ -30,6 +30,7 @@
#include "btif_storage.h"
#include "btm_api.h"
#include "btm_ble_api.h"
+#include "common/init_flags.h"
#include "common/leaky_bonded_queue.h"
#include "common/time_util.h"
#include "core_callbacks.h"
diff --git a/system/btif/src/btif_config.cc b/system/btif/src/btif_config.cc
index cf14bcd..9f304f8 100644
--- a/system/btif/src/btif_config.cc
+++ b/system/btif/src/btif_config.cc
@@ -36,12 +36,12 @@
#include "btif_metrics_logging.h"
#include "common/address_obfuscator.h"
#include "common/metric_id_allocator.h"
-#include "gd/storage/config_keys.h"
#include "include/check.h"
#include "main/shim/config.h"
#include "main/shim/shim.h"
#include "os/log.h"
#include "raw_address.h"
+#include "storage/config_keys.h"
#define TEMPORARY_SECTION_CAPACITY 10000
diff --git a/system/btif/src/btif_config_cache.cc b/system/btif/src/btif_config_cache.cc
index 8639295..c8f03cd 100644
--- a/system/btif/src/btif_config_cache.cc
+++ b/system/btif/src/btif_config_cache.cc
@@ -22,7 +22,7 @@
#include <unordered_set>
#include <vector>
-#include "gd/storage/config_keys.h"
+#include "storage/config_keys.h"
#include "types/raw_address.h"
namespace {
diff --git a/system/btif/src/btif_core.cc b/system/btif/src/btif_core.cc
index 64f6e2b..8fcfe45 100644
--- a/system/btif/src/btif_core.cc
+++ b/system/btif/src/btif_core.cc
@@ -49,7 +49,6 @@
#include "common/message_loop_thread.h"
#include "device/include/controller.h"
#include "device/include/device_iot_config.h"
-#include "gd/storage/config_keys.h"
#include "hci/controller_interface.h"
#include "internal_include/bt_target.h"
#include "internal_include/bt_trace.h"
@@ -62,6 +61,7 @@
#include "stack/include/bt_types.h"
#include "stack/include/btm_api.h"
#include "stack/include/btm_ble_api.h"
+#include "storage/config_keys.h"
#include "types/bluetooth/uuid.h"
#include "types/raw_address.h"
diff --git a/system/btif/src/btif_dm.cc b/system/btif/src/btif_dm.cc
index 0ac98f2..efbefd6 100644
--- a/system/btif/src/btif_dm.cc
+++ b/system/btif/src/btif_dm.cc
@@ -63,11 +63,11 @@
#include "btif_profile_storage.h"
#include "btif_storage.h"
#include "btif_util.h"
+#include "common/init_flags.h"
#include "common/lru_cache.h"
#include "common/metrics.h"
#include "device/include/controller.h"
#include "device/include/interop.h"
-#include "gd/storage/config_keys.h"
#include "include/check.h"
#include "internal_include/bt_target.h"
#include "internal_include/stack_config.h"
@@ -85,6 +85,7 @@
#include "stack/include/bt_octets.h"
#include "stack/include/bt_types.h"
#include "stack/include/bt_uuid16.h"
+#include "stack/include/btm_ble_addr.h"
#include "stack/include/btm_ble_api.h"
#include "stack/include/btm_ble_sec_api.h"
#include "stack/include/btm_ble_sec_api_types.h"
@@ -94,6 +95,7 @@
#include "stack/include/btm_sec_api_types.h"
#include "stack/include/smp_api.h"
#include "stack/sdp/sdpint.h"
+#include "storage/config_keys.h"
#include "types/raw_address.h"
#ifdef __ANDROID__
@@ -849,9 +851,13 @@
if (!IS_FLAG_ENABLED(connect_hid_after_service_discovery) &&
is_hid && (device_type & BT_DEVICE_TYPE_BLE) == 0) {
+ tAclLinkSpec link_spec;
+ link_spec.addrt.bda = bd_addr;
+ link_spec.addrt.type = addr_type;
+ link_spec.transport = transport;
const bt_status_t status =
GetInterfaceToProfiles()->profileSpecific_HACK->btif_hh_connect(
- &bd_addr);
+ &link_spec);
if (status != BT_STATUS_SUCCESS)
bond_state_changed(status, bd_addr, BT_BOND_STATE_NONE);
} else {
@@ -916,6 +922,50 @@
return rc;
}
+static uint16_t btif_dm_get_resolved_connection_state(
+ tBLE_BD_ADDR ble_bd_addr) {
+ uint16_t rc = 0;
+ if (maybe_resolve_address(&ble_bd_addr.bda, &ble_bd_addr.type)) {
+ if (BTA_DmGetConnectionState(ble_bd_addr.bda)) {
+ rc = 0x0001;
+ if (BTM_IsEncrypted(ble_bd_addr.bda, BT_TRANSPORT_BR_EDR)) {
+ rc |= ENCRYPTED_BREDR;
+ }
+ if (BTM_IsEncrypted(ble_bd_addr.bda, BT_TRANSPORT_LE)) {
+ rc |= ENCRYPTED_LE;
+ }
+
+ BTM_LogHistory(
+ kBtmLogTag, ble_bd_addr.bda, "RESOLVED connection state",
+ base::StringPrintf(
+ "connected:%c classic_encrypted:%c le_encrypted:%c",
+ (rc & 0x0001) ? 'T' : 'F', (rc & ENCRYPTED_BREDR) ? 'T' : 'F',
+ (rc & ENCRYPTED_LE) ? 'T' : 'F'));
+ }
+ }
+ return rc;
+}
+
+uint16_t btif_dm_get_connection_state_sync(const RawAddress& bd_addr) {
+ std::promise<uint16_t> promise;
+ std::future future = promise.get_future();
+
+ ASSERT(BT_STATUS_SUCCESS ==
+ do_in_main_thread(
+ FROM_HERE,
+ base::BindOnce(
+ [](const RawAddress bd_addr, std::promise<uint16_t> promise) {
+ // Experiment to try with maybe resolved address
+ btif_dm_get_resolved_connection_state({
+ .type = BLE_ADDR_RANDOM,
+ .bda = bd_addr,
+ });
+ promise.set_value(btif_dm_get_connection_state(bd_addr));
+ },
+ bd_addr, std::move(promise))));
+ return future.get();
+}
+
/******************************************************************************
*
* BTIF DM callback events
@@ -2834,8 +2884,13 @@
// there is a valid hid connection with this bd_addr. If yes VUP will be
// issued.
#if (BTA_HH_INCLUDED == TRUE)
+ tAclLinkSpec link_spec;
+ link_spec.addrt.bda = bd_addr;
+ link_spec.transport = BT_TRANSPORT_AUTO;
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+
if (GetInterfaceToProfiles()->profileSpecific_HACK->btif_hh_virtual_unplug(
- &bd_addr) != BT_STATUS_SUCCESS)
+ &link_spec) != BT_STATUS_SUCCESS)
#endif
{
LOG_DEBUG("Removing HH device");
diff --git a/system/btif/src/btif_gatt_client.cc b/system/btif/src/btif_gatt_client.cc
index 568095f..6796db0 100644
--- a/system/btif/src/btif_gatt_client.cc
+++ b/system/btif/src/btif_gatt_client.cc
@@ -44,13 +44,13 @@
#include "btif_gatt.h"
#include "btif_gatt_util.h"
#include "device/include/controller.h"
-#include "gd/storage/config_keys.h"
#include "include/check.h"
#include "os/log.h"
#include "osi/include/allocator.h"
#include "stack/include/acl_api.h"
#include "stack/include/acl_api_types.h"
#include "stack/include/main_thread.h"
+#include "storage/config_keys.h"
#include "types/ble_address_with_type.h"
#include "types/bluetooth/uuid.h"
#include "types/bt_transport.h"
diff --git a/system/btif/src/btif_hh.cc b/system/btif/src/btif_hh.cc
index 732899f..968af1a 100644
--- a/system/btif/src/btif_hh.cc
+++ b/system/btif/src/btif_hh.cc
@@ -248,7 +248,7 @@
p_buf = create_pbuf(len, data);
if (p_buf != NULL) {
p_buf->layer_specific = BTA_HH_RPTT_OUTPUT;
- BTA_HhSendData(p_dev->dev_handle, p_dev->bd_addr, p_buf);
+ BTA_HhSendData(p_dev->dev_handle, p_dev->link_spec, p_buf);
}
}
@@ -319,11 +319,12 @@
*
* Returns Device entry pointer in the device table
******************************************************************************/
-static btif_hh_device_t* btif_hh_find_dev_by_bda(const RawAddress& bd_addr) {
+static btif_hh_device_t* btif_hh_find_dev_by_bda(
+ const tAclLinkSpec& link_spec) {
uint32_t i;
for (i = 0; i < BTIF_HH_MAX_HID; i++) {
if (btif_hh_cb.devices[i].dev_status != BTHH_CONN_STATE_UNKNOWN &&
- btif_hh_cb.devices[i].bd_addr == bd_addr) {
+ btif_hh_cb.devices[i].link_spec.addrt.bda == link_spec.addrt.bda) {
return &btif_hh_cb.devices[i];
}
}
@@ -340,11 +341,11 @@
* Returns Device entry pointer in the device table
******************************************************************************/
static btif_hh_device_t* btif_hh_find_connected_dev_by_bda(
- const RawAddress& bd_addr) {
+ const tAclLinkSpec& link_spec) {
uint32_t i;
for (i = 0; i < BTIF_HH_MAX_HID; i++) {
if (btif_hh_cb.devices[i].dev_status == BTHH_CONN_STATE_CONNECTED &&
- btif_hh_cb.devices[i].bd_addr == bd_addr) {
+ btif_hh_cb.devices[i].link_spec.addrt.bda == link_spec.addrt.bda) {
return &btif_hh_cb.devices[i];
}
}
@@ -359,8 +360,8 @@
*
* Returns void
******************************************************************************/
-static void btif_hh_stop_vup_timer(RawAddress* bd_addr) {
- btif_hh_device_t* p_dev = btif_hh_find_connected_dev_by_bda(*bd_addr);
+static void btif_hh_stop_vup_timer(tAclLinkSpec* link_spec) {
+ btif_hh_device_t* p_dev = btif_hh_find_connected_dev_by_bda(*link_spec);
if (p_dev != NULL) {
LOG_VERBOSE("stop VUP timer");
@@ -376,10 +377,10 @@
*
* Returns void
******************************************************************************/
-static void btif_hh_start_vup_timer(const RawAddress* bd_addr) {
+static void btif_hh_start_vup_timer(const tAclLinkSpec* link_spec) {
LOG_VERBOSE("%s", __func__);
- btif_hh_device_t* p_dev = btif_hh_find_connected_dev_by_bda(*bd_addr);
+ btif_hh_device_t* p_dev = btif_hh_find_connected_dev_by_bda(*link_spec);
CHECK(p_dev != NULL);
alarm_free(p_dev->vup_timer);
@@ -388,7 +389,7 @@
btif_hh_timer_timeout, p_dev);
}
-static void hh_connect_complete(uint8_t handle, RawAddress& bda,
+static void hh_connect_complete(uint8_t handle, tAclLinkSpec& link_spec,
BTIF_HH_STATUS status) {
bthh_connection_state_t state = BTHH_CONN_STATE_CONNECTED;
btif_hh_cb.status = status;
@@ -397,24 +398,24 @@
state = BTHH_CONN_STATE_DISCONNECTED;
BTA_HhClose(handle);
}
- HAL_CBACK(bt_hh_callbacks, connection_state_cb, &bda, state);
+ HAL_CBACK(bt_hh_callbacks, connection_state_cb, &link_spec.addrt.bda, state);
}
static void hh_open_handler(tBTA_HH_CONN& conn) {
LOG_DEBUG("status = %d, handle = %d", conn.status, conn.handle);
- HAL_CBACK(bt_hh_callbacks, connection_state_cb, (RawAddress*)&conn.bda,
- BTHH_CONN_STATE_CONNECTING);
- btif_hh_cb.pending_conn_address = RawAddress::kEmpty;
+ HAL_CBACK(bt_hh_callbacks, connection_state_cb,
+ (RawAddress*)&conn.link_spec.addrt.bda, BTHH_CONN_STATE_CONNECTING);
+ btif_hh_cb.pending_link_spec = {};
if (conn.status != BTA_HH_OK) {
- btif_dm_hh_open_failed(&conn.bda);
- btif_hh_device_t* p_dev = btif_hh_find_dev_by_bda(conn.bda);
+ btif_dm_hh_open_failed(&conn.link_spec.addrt.bda);
+ btif_hh_device_t* p_dev = btif_hh_find_dev_by_bda(conn.link_spec);
if (p_dev != NULL) {
- btif_hh_stop_vup_timer(&(p_dev->bd_addr));
+ btif_hh_stop_vup_timer(&(p_dev->link_spec));
p_dev->dev_status = BTHH_CONN_STATE_DISCONNECTED;
}
- hh_connect_complete(conn.handle, conn.bda, BTIF_HH_DEV_DISCONNECTED);
+ hh_connect_complete(conn.handle, conn.link_spec, BTIF_HH_DEV_DISCONNECTED);
return;
}
@@ -422,7 +423,7 @@
if (!bta_hh_co_open(conn.handle, conn.sub_class, conn.attr_mask,
conn.app_id)) {
LOG_WARN("Failed to find the uhid driver");
- hh_connect_complete(conn.handle, conn.bda, BTIF_HH_DEV_DISCONNECTED);
+ hh_connect_complete(conn.handle, conn.link_spec, BTIF_HH_DEV_DISCONNECTED);
return;
}
@@ -431,18 +432,18 @@
/* The connect request must have come from device side and exceeded the
* connected HID device number. */
LOG_WARN("Cannot find device with handle %d", conn.handle);
- hh_connect_complete(conn.handle, conn.bda, BTIF_HH_DEV_DISCONNECTED);
+ hh_connect_complete(conn.handle, conn.link_spec, BTIF_HH_DEV_DISCONNECTED);
return;
}
LOG_INFO("Found device, getting dscp info for handle %d", conn.handle);
- p_dev->bd_addr = conn.bda;
+ p_dev->link_spec = conn.link_spec;
p_dev->dev_status = BTHH_CONN_STATE_CONNECTED;
- hh_connect_complete(conn.handle, conn.bda, BTIF_HH_DEV_CONNECTED);
+ hh_connect_complete(conn.handle, conn.link_spec, BTIF_HH_DEV_CONNECTED);
// Send set_idle if the peer_device is a keyboard
- if (check_cod_hid_major(conn.bda, COD_HID_KEYBOARD) ||
- check_cod_hid_major(conn.bda, COD_HID_COMBO)) {
+ if (check_cod_hid_major(conn.link_spec.addrt.bda, COD_HID_KEYBOARD) ||
+ check_cod_hid_major(conn.link_spec.addrt.bda, COD_HID_COMBO)) {
BTA_HhSetIdle(conn.handle, 0);
}
BTA_HhGetDscpInfo(conn.handle);
@@ -456,18 +457,21 @@
*
* Returns true if add successfully, otherwise false.
******************************************************************************/
-bool btif_hh_add_added_dev(const RawAddress& bda, tBTA_HH_ATTR_MASK attr_mask) {
+bool btif_hh_add_added_dev(const tAclLinkSpec& link_spec,
+ tBTA_HH_ATTR_MASK attr_mask) {
int i;
for (i = 0; i < BTIF_HH_MAX_ADDED_DEV; i++) {
- if (btif_hh_cb.added_devices[i].bd_addr == bda) {
- LOG(WARNING) << " Device " << ADDRESS_TO_LOGGABLE_STR(bda) << " already added";
+ if (btif_hh_cb.added_devices[i].link_spec.addrt.bda ==
+ link_spec.addrt.bda) {
+ LOG(WARNING) << " Device " << ADDRESS_TO_LOGGABLE_STR(link_spec)
+ << " already added";
return false;
}
}
for (i = 0; i < BTIF_HH_MAX_ADDED_DEV; i++) {
- if (btif_hh_cb.added_devices[i].bd_addr.IsEmpty()) {
- LOG(WARNING) << " Added device " << ADDRESS_TO_LOGGABLE_STR(bda);
- btif_hh_cb.added_devices[i].bd_addr = bda;
+ if (btif_hh_cb.added_devices[i].link_spec.addrt.bda.IsEmpty()) {
+ LOG(WARNING) << " Added device " << ADDRESS_TO_LOGGABLE_STR(link_spec);
+ btif_hh_cb.added_devices[i].link_spec = link_spec;
btif_hh_cb.added_devices[i].dev_handle = BTA_HH_INVALID_HANDLE;
btif_hh_cb.added_devices[i].attr_mask = attr_mask;
return true;
@@ -486,27 +490,28 @@
**
** Returns void
******************************************************************************/
-void btif_hh_remove_device(RawAddress bd_addr) {
+void btif_hh_remove_device(const tAclLinkSpec& link_spec) {
int i;
btif_hh_device_t* p_dev;
btif_hh_added_device_t* p_added_dev;
- LOG(INFO) << __func__ << ": bda = " << ADDRESS_TO_LOGGABLE_STR(bd_addr);
+ LOG(INFO) << __func__ << ": transport = " << link_spec.ToString();
for (i = 0; i < BTIF_HH_MAX_ADDED_DEV; i++) {
p_added_dev = &btif_hh_cb.added_devices[i];
- if (p_added_dev->bd_addr == bd_addr) {
+ if (p_added_dev->link_spec.addrt.bda == link_spec.addrt.bda) {
BTA_HhRemoveDev(p_added_dev->dev_handle);
- btif_storage_remove_hid_info(p_added_dev->bd_addr);
- p_added_dev->bd_addr = RawAddress::kEmpty;
+ btif_storage_remove_hid_info(p_added_dev->link_spec.addrt.bda);
+ p_added_dev->link_spec = {};
p_added_dev->dev_handle = BTA_HH_INVALID_HANDLE;
break;
}
}
- p_dev = btif_hh_find_dev_by_bda(bd_addr);
+ p_dev = btif_hh_find_dev_by_bda(link_spec);
if (p_dev == NULL) {
- LOG(WARNING) << " Oops, can't find device " << ADDRESS_TO_LOGGABLE_STR(bd_addr);
+ LOG(WARNING) << " Oops, can't find device "
+ << ADDRESS_TO_LOGGABLE_STR(link_spec);
return;
}
@@ -518,7 +523,7 @@
HAL_CBACK(bt_hh_callbacks, connection_state_cb, &bd_addr,
BTHH_CONN_STATE_DISCONNECTED);
},
- p_dev->bd_addr));
+ p_dev->link_spec.addrt.bda));
p_dev->dev_status = BTHH_CONN_STATE_UNKNOWN;
p_dev->dev_handle = BTA_HH_INVALID_HANDLE;
@@ -563,44 +568,44 @@
*
******************************************************************************/
-bt_status_t btif_hh_virtual_unplug(const RawAddress* bd_addr) {
+bt_status_t btif_hh_virtual_unplug(const tAclLinkSpec* link_spec) {
LOG_VERBOSE("%s", __func__);
btif_hh_device_t* p_dev;
- p_dev = btif_hh_find_dev_by_bda(*bd_addr);
+ p_dev = btif_hh_find_dev_by_bda(*link_spec);
if ((p_dev != NULL) && (p_dev->dev_status == BTHH_CONN_STATE_CONNECTED) &&
(p_dev->attr_mask & HID_VIRTUAL_CABLE)) {
LOG_VERBOSE("%s: Sending BTA_HH_CTRL_VIRTUAL_CABLE_UNPLUG for: %s",
- __func__, ADDRESS_TO_LOGGABLE_CSTR(*bd_addr));
+ __func__, ADDRESS_TO_LOGGABLE_CSTR(*link_spec));
/* start the timer */
- btif_hh_start_vup_timer(bd_addr);
+ btif_hh_start_vup_timer(link_spec);
p_dev->local_vup = true;
BTA_HhSendCtrl(p_dev->dev_handle, BTA_HH_CTRL_VIRTUAL_CABLE_UNPLUG);
return BT_STATUS_SUCCESS;
} else if ((p_dev != NULL) &&
(p_dev->dev_status == BTHH_CONN_STATE_CONNECTED)) {
LOG_ERROR("%s: Virtual unplug not supported, disconnecting device: %s",
- __func__, ADDRESS_TO_LOGGABLE_CSTR(*bd_addr));
+ __func__, ADDRESS_TO_LOGGABLE_CSTR(*link_spec));
/* start the timer */
- btif_hh_start_vup_timer(bd_addr);
+ btif_hh_start_vup_timer(link_spec);
p_dev->local_vup = true;
BTA_HhClose(p_dev->dev_handle);
return BT_STATUS_SUCCESS;
} else {
LOG_ERROR("%s: Error, device %s not opened, status = %d", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(*bd_addr), btif_hh_cb.status);
- if ((btif_hh_cb.pending_conn_address == *bd_addr) &&
+ ADDRESS_TO_LOGGABLE_CSTR(*link_spec), btif_hh_cb.status);
+ if ((btif_hh_cb.pending_link_spec.addrt.bda == link_spec->addrt.bda) &&
(btif_hh_cb.status == BTIF_HH_DEV_CONNECTING)) {
btif_hh_cb.status = (BTIF_HH_STATUS)BTIF_HH_DEV_DISCONNECTED;
- btif_hh_cb.pending_conn_address = RawAddress::kEmpty;
+ btif_hh_cb.pending_link_spec = {};
/* need to notify up-layer device is disconnected to avoid
* state out of sync with up-layer */
do_in_jni_thread(base::Bind(
- [](RawAddress bd_addrcb) {
- HAL_CBACK(bt_hh_callbacks, connection_state_cb, &bd_addrcb,
- BTHH_CONN_STATE_DISCONNECTED);
- },
- *bd_addr));
+ [](RawAddress bd_addrcb) {
+ HAL_CBACK(bt_hh_callbacks, connection_state_cb, &bd_addrcb,
+ BTHH_CONN_STATE_DISCONNECTED);
+ },
+ link_spec->addrt.bda));
}
return BT_STATUS_FAIL;
}
@@ -616,11 +621,12 @@
*
******************************************************************************/
-bt_status_t btif_hh_connect(const RawAddress* bd_addr) {
+bt_status_t btif_hh_connect(const tAclLinkSpec* link_spec) {
btif_hh_added_device_t* added_dev = NULL;
+
CHECK_BTHH_INIT();
LOG_VERBOSE("BTHH: %s", __func__);
- btif_hh_device_t* dev = btif_hh_find_dev_by_bda(*bd_addr);
+ btif_hh_device_t* dev = btif_hh_find_dev_by_bda(*link_spec);
if (!dev && btif_hh_cb.device_num >= BTIF_HH_MAX_HID) {
// No space for more HID device now.
LOG_WARN("%s: Error, exceeded the maximum supported HID device number %d",
@@ -629,9 +635,11 @@
}
for (int i = 0; i < BTIF_HH_MAX_ADDED_DEV; i++) {
- if (btif_hh_cb.added_devices[i].bd_addr == *bd_addr) {
+ if (btif_hh_cb.added_devices[i].link_spec.addrt.bda ==
+ link_spec->addrt.bda) {
added_dev = &btif_hh_cb.added_devices[i];
- LOG(WARNING) << __func__ << ": Device " << ADDRESS_TO_LOGGABLE_STR(*bd_addr)
+ LOG(WARNING) << __func__ << ": Device "
+ << ADDRESS_TO_LOGGABLE_STR(*link_spec)
<< " already added, attr_mask = 0x" << std::hex
<< added_dev->attr_mask;
}
@@ -641,9 +649,9 @@
if (added_dev->dev_handle == BTA_HH_INVALID_HANDLE) {
// No space for more HID device now.
LOG(ERROR) << __func__ << ": Error, device "
- << ADDRESS_TO_LOGGABLE_STR(*bd_addr)
+ << ADDRESS_TO_LOGGABLE_STR(*link_spec)
<< " added but addition failed";
- added_dev->bd_addr = RawAddress::kEmpty;
+ added_dev->link_spec = {};
added_dev->dev_handle = BTA_HH_INVALID_HANDLE;
return BT_STATUS_NOMEM;
}
@@ -651,7 +659,7 @@
if (dev && dev->dev_status == BTHH_CONN_STATE_CONNECTED) {
LOG_DEBUG("HidHost profile already connected for %s",
- ADDRESS_TO_LOGGABLE_CSTR((*bd_addr)));
+ ADDRESS_TO_LOGGABLE_CSTR((*link_spec)));
return BT_STATUS_SUCCESS;
}
@@ -661,15 +669,15 @@
not in
pagescan mode, we will do 2 retries to connect before giving up */
btif_hh_cb.status = BTIF_HH_DEV_CONNECTING;
- btif_hh_cb.pending_conn_address = *bd_addr;
- BTA_HhOpen(*bd_addr);
+ btif_hh_cb.pending_link_spec = *link_spec;
+ BTA_HhOpen(btif_hh_cb.pending_link_spec);
do_in_jni_thread(base::Bind(
[](RawAddress bd_addr) {
HAL_CBACK(bt_hh_callbacks, connection_state_cb, &bd_addr,
BTHH_CONN_STATE_CONNECTING);
},
- *bd_addr));
+ link_spec->addrt.bda));
return BT_STATUS_SUCCESS;
}
@@ -682,16 +690,16 @@
* Returns void
*
******************************************************************************/
-void btif_hh_disconnect(RawAddress* bd_addr) {
- CHECK(bd_addr != nullptr);
- const btif_hh_device_t* p_dev = btif_hh_find_connected_dev_by_bda(*bd_addr);
+void btif_hh_disconnect(tAclLinkSpec* link_spec) {
+ CHECK(link_spec != nullptr);
+ const btif_hh_device_t* p_dev = btif_hh_find_connected_dev_by_bda(*link_spec);
if (p_dev == nullptr) {
LOG_DEBUG("Unable to disconnect unknown HID device:%s",
- ADDRESS_TO_LOGGABLE_CSTR((*bd_addr)));
+ ADDRESS_TO_LOGGABLE_CSTR((*link_spec)));
return;
}
LOG_DEBUG("Disconnect and close request for HID device:%s",
- ADDRESS_TO_LOGGABLE_CSTR((*bd_addr)));
+ ADDRESS_TO_LOGGABLE_CSTR((*link_spec)));
BTA_HhClose(p_dev->dev_handle);
}
@@ -732,7 +740,7 @@
return;
}
p_buf->layer_specific = BTA_HH_RPTT_OUTPUT;
- BTA_HhSendData(p_dev->dev_handle, p_dev->bd_addr, p_buf);
+ BTA_HhSendData(p_dev->dev_handle, p_dev->link_spec, p_buf);
}
/*******************************************************************************
@@ -858,32 +866,32 @@
p_data->dev_status.status, p_data->dev_status.handle);
p_dev = btif_hh_find_connected_dev_by_handle(p_data->dev_status.handle);
if (p_dev != NULL) {
- HAL_CBACK(bt_hh_callbacks, connection_state_cb, &(p_dev->bd_addr),
- BTHH_CONN_STATE_DISCONNECTING);
+ HAL_CBACK(bt_hh_callbacks, connection_state_cb,
+ &(p_dev->link_spec.addrt.bda), BTHH_CONN_STATE_DISCONNECTING);
LOG_VERBOSE("%s: uhid fd=%d local_vup=%d", __func__, p_dev->fd,
p_dev->local_vup);
- btif_hh_stop_vup_timer(&(p_dev->bd_addr));
+ btif_hh_stop_vup_timer(&(p_dev->link_spec));
/* If this is a locally initiated VUP, remove the bond as ACL got
* disconnected while VUP being processed.
*/
if (p_dev->local_vup) {
p_dev->local_vup = false;
- BTA_DmRemoveDevice(p_dev->bd_addr);
+ BTA_DmRemoveDevice(p_dev->link_spec.addrt.bda);
} else if (p_data->dev_status.status == BTA_HH_HS_SERVICE_CHANGED) {
/* Local disconnection due to service change in the HOGP device.
HID descriptor would be read again, so remove it from cache. */
LOG_WARN(
"Removing cached descriptor due to service change, handle = %d",
p_data->dev_status.handle);
- btif_storage_remove_hid_info(p_dev->bd_addr);
+ btif_storage_remove_hid_info(p_dev->link_spec.addrt.bda);
}
btif_hh_cb.status = (BTIF_HH_STATUS)BTIF_HH_DEV_DISCONNECTED;
p_dev->dev_status = BTHH_CONN_STATE_DISCONNECTED;
bta_hh_co_close(p_dev);
- HAL_CBACK(bt_hh_callbacks, connection_state_cb, &(p_dev->bd_addr),
- p_dev->dev_status);
+ HAL_CBACK(bt_hh_callbacks, connection_state_cb,
+ &(p_dev->link_spec.addrt.bda), p_dev->dev_status);
} else {
LOG_WARN("Error: cannot find device with handle %d",
p_data->dev_status.handle);
@@ -901,7 +909,7 @@
uint8_t* data = (uint8_t*)(hdr + 1) + hdr->offset;
uint16_t len = hdr->len;
HAL_CBACK(bt_hh_callbacks, get_report_cb,
- (RawAddress*)&(p_dev->bd_addr),
+ (RawAddress*)&(p_dev->link_spec.addrt.bda),
(bthh_status_t)p_data->hs_data.status, data, len);
bta_hh_co_get_rpt_rsp(p_dev->dev_handle,
@@ -909,7 +917,7 @@
len);
} else { /* Handshake */
HAL_CBACK(bt_hh_callbacks, handshake_cb,
- (RawAddress*)&(p_dev->bd_addr),
+ (RawAddress*)&(p_dev->link_spec.addrt.bda),
(bthh_status_t)p_data->hs_data.status);
}
} else {
@@ -924,7 +932,8 @@
p_data->dev_status.status, p_data->dev_status.handle);
p_dev = btif_hh_find_connected_dev_by_handle(p_data->dev_status.handle);
if (p_dev != NULL) {
- HAL_CBACK(bt_hh_callbacks, handshake_cb, (RawAddress*)&(p_dev->bd_addr),
+ HAL_CBACK(bt_hh_callbacks, handshake_cb,
+ (RawAddress*)&(p_dev->link_spec.addrt.bda),
(bthh_status_t)p_data->hs_data.status);
bta_hh_co_set_rpt_rsp(p_dev->dev_handle, p_data->dev_status.status);
@@ -950,11 +959,12 @@
: "Unsupported");
if (p_data->hs_data.rsp_data.proto_mode != BTA_HH_PROTO_UNKNOWN) {
HAL_CBACK(bt_hh_callbacks, protocol_mode_cb,
- (RawAddress*)&(p_dev->bd_addr),
+ (RawAddress*)&(p_dev->link_spec.addrt.bda),
(bthh_status_t)p_data->hs_data.status,
(bthh_protocol_mode_t)p_data->hs_data.rsp_data.proto_mode);
} else {
- HAL_CBACK(bt_hh_callbacks, handshake_cb, (RawAddress*)&(p_dev->bd_addr),
+ HAL_CBACK(bt_hh_callbacks, handshake_cb,
+ (RawAddress*)&(p_dev->link_spec.addrt.bda),
(bthh_status_t)p_data->hs_data.status);
}
break;
@@ -964,7 +974,8 @@
p_data->dev_status.status, p_data->dev_status.handle);
p_dev = btif_hh_find_connected_dev_by_handle(p_data->dev_status.handle);
if (p_dev) {
- HAL_CBACK(bt_hh_callbacks, handshake_cb, (RawAddress*)&(p_dev->bd_addr),
+ HAL_CBACK(bt_hh_callbacks, handshake_cb,
+ (RawAddress*)&(p_dev->link_spec.addrt.bda),
(bthh_status_t)p_data->hs_data.status);
}
break;
@@ -975,7 +986,8 @@
p_data->hs_data.rsp_data.idle_rate);
p_dev = btif_hh_find_connected_dev_by_handle(p_data->hs_data.handle);
if (p_dev) {
- HAL_CBACK(bt_hh_callbacks, idle_time_cb, (RawAddress*)&(p_dev->bd_addr),
+ HAL_CBACK(bt_hh_callbacks, idle_time_cb,
+ (RawAddress*)&(p_dev->link_spec.addrt.bda),
(bthh_status_t)p_data->hs_data.status,
p_data->hs_data.rsp_data.idle_rate);
}
@@ -1009,7 +1021,7 @@
BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_BDNAME,
sizeof(bt_bdname_t), &bdname);
if (btif_storage_get_remote_device_property(
- &p_dev->bd_addr, &prop_name) == BT_STATUS_SUCCESS) {
+ &p_dev->link_spec.addrt.bda, &prop_name) == BT_STATUS_SUCCESS) {
cached_name = (char*)bdname.name;
} else {
cached_name = "Bluetooth HID";
@@ -1021,17 +1033,17 @@
p_data->dscp_info.version,
p_data->dscp_info.ctry_code, len,
p_data->dscp_info.descriptor.dsc_list);
- if (btif_hh_add_added_dev(p_dev->bd_addr, p_dev->attr_mask)) {
+ if (btif_hh_add_added_dev(p_dev->link_spec, p_dev->attr_mask)) {
tBTA_HH_DEV_DSCP_INFO dscp_info;
bt_status_t ret;
btif_hh_copy_hid_info(&dscp_info, &p_data->dscp_info);
VLOG(1) << "BTA_HH_GET_DSCP_EVT:bda = "
- << ADDRESS_TO_LOGGABLE_STR(p_dev->bd_addr);
- BTA_HhAddDev(p_dev->bd_addr, p_dev->attr_mask, p_dev->sub_class,
+ << ADDRESS_TO_LOGGABLE_STR(p_dev->link_spec.addrt.bda);
+ BTA_HhAddDev(p_dev->link_spec, p_dev->attr_mask, p_dev->sub_class,
p_dev->app_id, dscp_info);
// write hid info to nvram
ret = btif_storage_add_hid_device_info(
- &(p_dev->bd_addr), p_dev->attr_mask, p_dev->sub_class,
+ &(p_dev->link_spec.addrt.bda), p_dev->attr_mask, p_dev->sub_class,
p_dev->app_id, p_data->dscp_info.vendor_id,
p_data->dscp_info.product_id, p_data->dscp_info.version,
p_data->dscp_info.ctry_code, p_data->dscp_info.ssr_max_latency,
@@ -1078,11 +1090,12 @@
p_data->dev_info.status, p_data->dev_info.handle);
int i;
for (i = 0; i < BTIF_HH_MAX_ADDED_DEV; i++) {
- if (btif_hh_cb.added_devices[i].bd_addr == p_data->dev_info.bda) {
+ if (btif_hh_cb.added_devices[i].link_spec.addrt.bda ==
+ p_data->dev_info.link_spec.addrt.bda) {
if (p_data->dev_info.status == BTA_HH_OK) {
btif_hh_cb.added_devices[i].dev_handle = p_data->dev_info.handle;
} else {
- btif_hh_cb.added_devices[i].bd_addr = RawAddress::kEmpty;
+ btif_hh_cb.added_devices[i].link_spec = {};
btif_hh_cb.added_devices[i].dev_handle = BTA_HH_INVALID_HANDLE;
}
break;
@@ -1092,7 +1105,8 @@
case BTA_HH_RMV_DEV_EVT:
LOG_VERBOSE("BTA_HH_RMV_DEV_EVT: status = %d, handle = %d",
p_data->dev_info.status, p_data->dev_info.handle);
- VLOG(1) << "BTA_HH_RMV_DEV_EVT:bda = " << p_data->dev_info.bda;
+ VLOG(1) << "BTA_HH_RMV_DEV_EVT:bda = "
+ << p_data->dev_info.link_spec.addrt.bda;
break;
case BTA_HH_VC_UNPLUG_EVT:
@@ -1101,23 +1115,24 @@
p_dev = btif_hh_find_connected_dev_by_handle(p_data->dev_status.handle);
btif_hh_cb.status = (BTIF_HH_STATUS)BTIF_HH_DEV_DISCONNECTED;
if (p_dev != NULL) {
- VLOG(1) << "BTA_HH_VC_UNPLUG_EVT:bda = " << p_dev->bd_addr;
+ VLOG(1) << "BTA_HH_VC_UNPLUG_EVT:bda = " << p_dev->link_spec.addrt.bda;
/* Stop the VUP timer */
- btif_hh_stop_vup_timer(&(p_dev->bd_addr));
+ btif_hh_stop_vup_timer(&(p_dev->link_spec));
p_dev->dev_status = BTHH_CONN_STATE_DISCONNECTED;
LOG_VERBOSE("%s---Sending connection state change", __func__);
- HAL_CBACK(bt_hh_callbacks, connection_state_cb, &(p_dev->bd_addr),
- p_dev->dev_status);
+ HAL_CBACK(bt_hh_callbacks, connection_state_cb,
+ &(p_dev->link_spec.addrt.bda), p_dev->dev_status);
LOG_VERBOSE("%s---Removing HID bond", __func__);
/* If it is locally initiated VUP or remote device has its major COD as
Peripheral removed the bond.*/
- if (p_dev->local_vup || check_cod_hid(&(p_dev->bd_addr))) {
+ if (p_dev->local_vup || check_cod_hid(&(p_dev->link_spec.addrt.bda))) {
p_dev->local_vup = false;
- BTA_DmRemoveDevice(p_dev->bd_addr);
+ BTA_DmRemoveDevice(p_dev->link_spec.addrt.bda);
} else
- btif_hh_remove_device(p_dev->bd_addr);
- HAL_CBACK(bt_hh_callbacks, virtual_unplug_cb, &(p_dev->bd_addr),
+ btif_hh_remove_device(p_dev->link_spec);
+ HAL_CBACK(bt_hh_callbacks, virtual_unplug_cb,
+ &(p_dev->link_spec.addrt.bda),
(bthh_status_t)p_data->dev_status.status);
}
break;
@@ -1227,39 +1242,39 @@
static void btif_hh_handle_evt(uint16_t event, char* p_param) {
CHECK(p_param != nullptr);
- RawAddress* bd_addr = (RawAddress*)p_param;
+ tAclLinkSpec* p_link_spec = (tAclLinkSpec*)p_param;
switch (event) {
case BTIF_HH_CONNECT_REQ_EVT: {
LOG_DEBUG("Connect request received remote:%s",
- ADDRESS_TO_LOGGABLE_CSTR((*bd_addr)));
- if (btif_hh_connect(bd_addr) == BT_STATUS_SUCCESS) {
- HAL_CBACK(bt_hh_callbacks, connection_state_cb, bd_addr,
+ ADDRESS_TO_LOGGABLE_CSTR((*p_link_spec)));
+ if (btif_hh_connect(p_link_spec) == BT_STATUS_SUCCESS) {
+ HAL_CBACK(bt_hh_callbacks, connection_state_cb, &p_link_spec->addrt.bda,
BTHH_CONN_STATE_CONNECTING);
} else
- HAL_CBACK(bt_hh_callbacks, connection_state_cb, bd_addr,
+ HAL_CBACK(bt_hh_callbacks, connection_state_cb, &p_link_spec->addrt.bda,
BTHH_CONN_STATE_DISCONNECTED);
} break;
case BTIF_HH_DISCONNECT_REQ_EVT: {
LOG_DEBUG("Disconnect request received remote:%s",
- ADDRESS_TO_LOGGABLE_CSTR((*bd_addr)));
- btif_hh_disconnect(bd_addr);
- HAL_CBACK(bt_hh_callbacks, connection_state_cb, bd_addr,
+ ADDRESS_TO_LOGGABLE_CSTR((*p_link_spec)));
+ btif_hh_disconnect(p_link_spec);
+ HAL_CBACK(bt_hh_callbacks, connection_state_cb, &p_link_spec->addrt.bda,
BTHH_CONN_STATE_DISCONNECTING);
} break;
case BTIF_HH_VUP_REQ_EVT: {
LOG_DEBUG("Virtual unplug request received remote:%s",
- ADDRESS_TO_LOGGABLE_CSTR((*bd_addr)));
- if (btif_hh_virtual_unplug(bd_addr) != BT_STATUS_SUCCESS) {
+ ADDRESS_TO_LOGGABLE_CSTR((*p_link_spec)));
+ if (btif_hh_virtual_unplug(p_link_spec) != BT_STATUS_SUCCESS) {
LOG_WARN("Unable to virtual unplug device remote:%s",
- ADDRESS_TO_LOGGABLE_CSTR((*bd_addr)));
+ ADDRESS_TO_LOGGABLE_CSTR((*p_link_spec)));
}
} break;
default: {
LOG_WARN("Unknown event received:%d remote:%s", event,
- ADDRESS_TO_LOGGABLE_CSTR((*bd_addr)));
+ ADDRESS_TO_LOGGABLE_CSTR((*p_link_spec)));
} break;
}
}
@@ -1325,6 +1340,7 @@
******************************************************************************/
static bt_status_t connect(RawAddress* bd_addr) {
btif_hh_device_t* p_dev;
+ tAclLinkSpec link_spec;
if (btif_hh_cb.status == BTIF_HH_DEV_CONNECTING) {
LOG_WARN("%s: Error, HH status = %d", __func__, btif_hh_cb.status);
@@ -1334,8 +1350,12 @@
LOG_WARN("%s: Error, HH status = %d", __func__, btif_hh_cb.status);
return BT_STATUS_NOT_READY;
}
+ link_spec.addrt.bda = *bd_addr;
+ // Todo: fill with params received
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ link_spec.transport = BT_TRANSPORT_AUTO;
- p_dev = btif_hh_find_connected_dev_by_bda(*bd_addr);
+ p_dev = btif_hh_find_connected_dev_by_bda(link_spec);
if (p_dev) {
if (p_dev->dev_status == BTHH_CONN_STATE_CONNECTED ||
p_dev->dev_status == BTHH_CONN_STATE_CONNECTING) {
@@ -1350,7 +1370,7 @@
}
return btif_transfer_context(btif_hh_handle_evt, BTIF_HH_CONNECT_REQ_EVT,
- (char*)bd_addr, sizeof(RawAddress), NULL);
+ (char*)&link_spec, sizeof(tAclLinkSpec), NULL);
}
/*******************************************************************************
@@ -1366,14 +1386,19 @@
CHECK_BTHH_INIT();
LOG_VERBOSE("BTHH: %s", __func__);
btif_hh_device_t* p_dev;
+ tAclLinkSpec link_spec;
if (btif_hh_cb.status == BTIF_HH_DISABLED ||
btif_hh_cb.status == BTIF_HH_DISABLING) {
LOG_WARN("%s: Error, HH status = %d", __func__, btif_hh_cb.status);
return BT_STATUS_UNHANDLED;
}
+ link_spec.addrt.bda = *bd_addr;
+ // Todo: fill with params received
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ link_spec.transport = BT_TRANSPORT_AUTO;
- p_dev = btif_hh_find_connected_dev_by_bda(*bd_addr);
+ p_dev = btif_hh_find_connected_dev_by_bda(link_spec);
if (!p_dev) {
LOG_ERROR("%s: Error, device %s not opened.", __func__,
ADDRESS_TO_LOGGABLE_CSTR(*bd_addr));
@@ -1392,7 +1417,7 @@
}
return btif_transfer_context(btif_hh_handle_evt, BTIF_HH_DISCONNECT_REQ_EVT,
- (char*)bd_addr, sizeof(RawAddress), NULL);
+ (char*)&link_spec, sizeof(tAclLinkSpec), NULL);
}
/*******************************************************************************
@@ -1408,18 +1433,24 @@
CHECK_BTHH_INIT();
LOG_VERBOSE("BTHH: %s", __func__);
btif_hh_device_t* p_dev;
+ tAclLinkSpec link_spec;
if (btif_hh_cb.status == BTIF_HH_DISABLED) {
LOG_ERROR("%s: Error, HH status = %d", __func__, btif_hh_cb.status);
return BT_STATUS_FAIL;
}
- p_dev = btif_hh_find_dev_by_bda(*bd_addr);
+ link_spec.addrt.bda = *bd_addr;
+ // Todo: fill with params received
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ link_spec.transport = BT_TRANSPORT_AUTO;
+
+ p_dev = btif_hh_find_dev_by_bda(link_spec);
if (!p_dev) {
LOG_ERROR("%s: Error, device %s not opened.", __func__,
ADDRESS_TO_LOGGABLE_CSTR(*bd_addr));
return BT_STATUS_FAIL;
}
- btif_transfer_context(btif_hh_handle_evt, BTIF_HH_VUP_REQ_EVT, (char*)bd_addr,
- sizeof(RawAddress), NULL);
+ btif_transfer_context(btif_hh_handle_evt, BTIF_HH_VUP_REQ_EVT,
+ (char*)&link_spec, sizeof(tAclLinkSpec), NULL);
return BT_STATUS_SUCCESS;
}
@@ -1434,6 +1465,7 @@
*******************************************************************************/
static bt_status_t get_idle_time(RawAddress* bd_addr) {
CHECK_BTHH_INIT();
+ tAclLinkSpec link_spec;
LOG_VERBOSE("%s: addr = %s", __func__, ADDRESS_TO_LOGGABLE_CSTR(*bd_addr));
@@ -1441,8 +1473,12 @@
LOG_ERROR("%s: Error, HH status = %d", __func__, btif_hh_cb.status);
return BT_STATUS_FAIL;
}
+ link_spec.addrt.bda = *bd_addr;
+ // Todo: fill with params received
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ link_spec.transport = BT_TRANSPORT_AUTO;
- btif_hh_device_t* p_dev = btif_hh_find_connected_dev_by_bda(*bd_addr);
+ btif_hh_device_t* p_dev = btif_hh_find_connected_dev_by_bda(link_spec);
if (p_dev == NULL) return BT_STATUS_FAIL;
BTA_HhGetIdle(p_dev->dev_handle);
@@ -1460,6 +1496,7 @@
*******************************************************************************/
static bt_status_t set_idle_time(RawAddress* bd_addr, uint8_t idle_time) {
CHECK_BTHH_INIT();
+ tAclLinkSpec link_spec;
LOG_VERBOSE("%s: addr = %s, idle time = %d", __func__,
ADDRESS_TO_LOGGABLE_CSTR(*bd_addr), idle_time);
@@ -1468,8 +1505,12 @@
LOG_ERROR("%s: Error, HH status = %d", __func__, btif_hh_cb.status);
return BT_STATUS_FAIL;
}
+ link_spec.addrt.bda = *bd_addr;
+ // Todo: fill with params received
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ link_spec.transport = BT_TRANSPORT_AUTO;
- btif_hh_device_t* p_dev = btif_hh_find_connected_dev_by_bda(*bd_addr);
+ btif_hh_device_t* p_dev = btif_hh_find_connected_dev_by_bda(link_spec);
if (p_dev == NULL) {
LOG_WARN("%s: addr = %s not opened", __func__,
ADDRESS_TO_LOGGABLE_CSTR(*bd_addr));
@@ -1492,6 +1533,7 @@
static bt_status_t set_info(RawAddress* bd_addr, bthh_hid_info_t hid_info) {
CHECK_BTHH_INIT();
tBTA_HH_DEV_DSCP_INFO dscp_info;
+ tAclLinkSpec link_spec;
VLOG(1) << __func__ << " BTHH: addr = " << *bd_addr;
LOG_VERBOSE(
@@ -1516,8 +1558,13 @@
(uint8_t*)osi_malloc(dscp_info.descriptor.dl_len);
memcpy(dscp_info.descriptor.dsc_list, &(hid_info.dsc_list), hid_info.dl_len);
- if (btif_hh_add_added_dev(*bd_addr, hid_info.attr_mask)) {
- BTA_HhAddDev(*bd_addr, hid_info.attr_mask, hid_info.sub_class,
+ link_spec.addrt.bda = *bd_addr;
+ // Todo: fill with params received
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ link_spec.transport = BT_TRANSPORT_AUTO;
+
+ if (btif_hh_add_added_dev(link_spec, hid_info.attr_mask)) {
+ BTA_HhAddDev(link_spec, hid_info.attr_mask, hid_info.sub_class,
hid_info.app_id, dscp_info);
}
@@ -1538,6 +1585,7 @@
static bt_status_t get_protocol(RawAddress* bd_addr,
bthh_protocol_mode_t /* protocolMode */) {
CHECK_BTHH_INIT();
+ tAclLinkSpec link_spec;
VLOG(1) << __func__ << " BTHH: addr = " << ADDRESS_TO_LOGGABLE_STR(*bd_addr);
@@ -1545,8 +1593,12 @@
LOG_ERROR("%s: Error, HH status = %d", __func__, btif_hh_cb.status);
return BT_STATUS_FAIL;
}
+ link_spec.addrt.bda = *bd_addr;
+ // Todo: fill with params received
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ link_spec.transport = BT_TRANSPORT_AUTO;
- btif_hh_device_t* p_dev = btif_hh_find_connected_dev_by_bda(*bd_addr);
+ btif_hh_device_t* p_dev = btif_hh_find_connected_dev_by_bda(link_spec);
if (!p_dev) return BT_STATUS_FAIL;
BTA_HhGetProtoMode(p_dev->dev_handle);
@@ -1567,6 +1619,7 @@
CHECK_BTHH_INIT();
btif_hh_device_t* p_dev;
uint8_t proto_mode = protocolMode;
+ tAclLinkSpec link_spec;
VLOG(1) << __func__ << " BTHH: proto_mod=" << protocolMode
<< " addr = " << *bd_addr;
@@ -1575,8 +1628,12 @@
LOG_ERROR("%s: Error, HH status = %d", __func__, btif_hh_cb.status);
return BT_STATUS_FAIL;
}
+ link_spec.addrt.bda = *bd_addr;
+ // Todo: fill with params received
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ link_spec.transport = BT_TRANSPORT_AUTO;
- p_dev = btif_hh_find_connected_dev_by_bda(*bd_addr);
+ p_dev = btif_hh_find_connected_dev_by_bda(link_spec);
if (p_dev == NULL) {
LOG(WARNING) << " Error, device" << ADDRESS_TO_LOGGABLE_STR(*bd_addr) << " not opened";
return BT_STATUS_FAIL;
@@ -1605,6 +1662,7 @@
int bufferSize) {
CHECK_BTHH_INIT();
btif_hh_device_t* p_dev;
+ tAclLinkSpec link_spec;
VLOG(1) << __func__ << " BTHH: r_type = " << reportType
<< ", rpt_id = " << reportId << ", buf_size = " << bufferSize
@@ -1614,8 +1672,12 @@
LOG_ERROR("%s: Error, HH status = %d", __func__, btif_hh_cb.status);
return BT_STATUS_FAIL;
}
+ link_spec.addrt.bda = *bd_addr;
+ // Todo: fill with params received
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ link_spec.transport = BT_TRANSPORT_AUTO;
- p_dev = btif_hh_find_connected_dev_by_bda(*bd_addr);
+ p_dev = btif_hh_find_connected_dev_by_bda(link_spec);
if (p_dev == NULL) {
LOG(ERROR) << " Error, device" << ADDRESS_TO_LOGGABLE_STR(*bd_addr) << " not opened";
return BT_STATUS_FAIL;
@@ -1643,6 +1705,7 @@
char* report, uint16_t size) {
CHECK_BTHH_INIT();
btif_hh_device_t* p_dev;
+ tAclLinkSpec link_spec;
VLOG(1) << __func__ << " BTHH: addr=" << ADDRESS_TO_LOGGABLE_STR(*bd_addr);
@@ -1650,8 +1713,12 @@
LOG_ERROR("%s: Error, HH status = %d", __func__, btif_hh_cb.status);
return BT_STATUS_FAIL;
}
+ link_spec.addrt.bda = *bd_addr;
+ // Todo: fill with params received
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ link_spec.transport = BT_TRANSPORT_AUTO;
- p_dev = btif_hh_find_connected_dev_by_bda(*bd_addr);
+ p_dev = btif_hh_find_connected_dev_by_bda(link_spec);
if (p_dev == NULL) {
LOG(ERROR) << " Error, device" << ADDRESS_TO_LOGGABLE_STR(*bd_addr) << " not opened";
return BT_STATUS_FAIL;
@@ -1675,6 +1742,7 @@
bthh_report_type_t reportType, char* report) {
CHECK_BTHH_INIT();
btif_hh_device_t* p_dev;
+ tAclLinkSpec link_spec;
VLOG(1) << __func__ << " BTHH: reportType=" << reportType
<< " addr=" << ADDRESS_TO_LOGGABLE_STR(*bd_addr);
@@ -1683,8 +1751,12 @@
LOG_ERROR("%s: Error, HH status = %d", __func__, btif_hh_cb.status);
return BT_STATUS_FAIL;
}
+ link_spec.addrt.bda = *bd_addr;
+ // Todo: fill with params received
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ link_spec.transport = BT_TRANSPORT_AUTO;
- p_dev = btif_hh_find_connected_dev_by_bda(*bd_addr);
+ p_dev = btif_hh_find_connected_dev_by_bda(link_spec);
if (p_dev == NULL) {
LOG(ERROR) << " Error, device" << ADDRESS_TO_LOGGABLE_STR(*bd_addr) << " not opened";
return BT_STATUS_FAIL;
@@ -1730,6 +1802,7 @@
static bt_status_t send_data(RawAddress* bd_addr, char* data) {
CHECK_BTHH_INIT();
btif_hh_device_t* p_dev;
+ tAclLinkSpec link_spec;
VLOG(1) << __func__ << " addr=" << ADDRESS_TO_LOGGABLE_STR(*bd_addr);
@@ -1737,8 +1810,12 @@
LOG_ERROR("%s: Error, HH status = %d", __func__, btif_hh_cb.status);
return BT_STATUS_FAIL;
}
+ link_spec.addrt.bda = *bd_addr;
+ // Todo: fill with params received
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ link_spec.transport = BT_TRANSPORT_AUTO;
- p_dev = btif_hh_find_connected_dev_by_bda(*bd_addr);
+ p_dev = btif_hh_find_connected_dev_by_bda(link_spec);
if (p_dev == NULL) {
LOG(ERROR) << " Error, device"
<< ADDRESS_TO_LOGGABLE_STR(*bd_addr) << " not opened";
@@ -1763,7 +1840,7 @@
return BT_STATUS_FAIL;
}
p_buf->layer_specific = BTA_HH_RPTT_OUTPUT;
- BTA_HhSendData(p_dev->dev_handle, *bd_addr, p_buf);
+ BTA_HhSendData(p_dev->dev_handle, link_spec, p_buf);
osi_free(hexbuf);
return BT_STATUS_SUCCESS;
}
@@ -1885,9 +1962,10 @@
LOG_DUMPSYS(fd, "status:%s", btif_hh_status_text(btif_hh_cb.status).c_str());
for (unsigned i = 0; i < BTIF_HH_MAX_HID; i++) {
const btif_hh_device_t* p_dev = &btif_hh_cb.devices[i];
- if (p_dev->bd_addr != RawAddress::kEmpty) {
+ if (p_dev->link_spec.addrt.bda != RawAddress::kEmpty) {
LOG_DUMPSYS(fd, " %u: addr:%s fd:%d state:%s ready:%s thread_id:%d", i,
- ADDRESS_TO_LOGGABLE_CSTR(p_dev->bd_addr), p_dev->fd,
+ ADDRESS_TO_LOGGABLE_CSTR(p_dev->link_spec.addrt.bda),
+ p_dev->fd,
bthh_connection_state_text(p_dev->dev_status).c_str(),
(p_dev->ready_for_data) ? ("T") : ("F"),
static_cast<int>(p_dev->hh_poll_thread_id));
@@ -1895,8 +1973,9 @@
}
for (unsigned i = 0; i < BTIF_HH_MAX_ADDED_DEV; i++) {
const btif_hh_added_device_t* p_dev = &btif_hh_cb.added_devices[i];
- if (p_dev->bd_addr != RawAddress::kEmpty) {
- LOG_DUMPSYS(fd, " %u: addr:%s", i, ADDRESS_TO_LOGGABLE_CSTR(p_dev->bd_addr));
+ if (p_dev->link_spec.addrt.bda != RawAddress::kEmpty) {
+ LOG_DUMPSYS(fd, " %u: addr:%s", i,
+ ADDRESS_TO_LOGGABLE_CSTR(p_dev->link_spec.addrt.bda));
}
}
}
diff --git a/system/btif/src/btif_le_audio.cc b/system/btif/src/btif_le_audio.cc
index 90931d2..4013860 100644
--- a/system/btif/src/btif_le_audio.cc
+++ b/system/btif/src/btif_le_audio.cc
@@ -32,6 +32,7 @@
using bluetooth::le_audio::ConnectionState;
using bluetooth::le_audio::GroupNodeStatus;
using bluetooth::le_audio::GroupStatus;
+using bluetooth::le_audio::GroupStreamStatus;
using bluetooth::le_audio::LeAudioClientCallbacks;
using bluetooth::le_audio::LeAudioClientInterface;
using bluetooth::le_audio::UnicastMonitorModeStatus;
@@ -140,6 +141,13 @@
Unretained(callbacks), direction, status));
}
+ void OnGroupStreamStatus(int group_id,
+ GroupStreamStatus group_stream_status) override {
+ do_in_jni_thread(
+ FROM_HERE, Bind(&LeAudioClientCallbacks::OnGroupStreamStatus,
+ Unretained(callbacks), group_id, group_stream_status));
+ }
+
void Initialize(LeAudioClientCallbacks* callbacks,
const std::vector<btle_audio_codec_config_t>&
offloading_preference) override {
diff --git a/system/btif/src/btif_profile_storage.cc b/system/btif/src/btif_profile_storage.cc
index c44a2ea..3f6d172 100644
--- a/system/btif/src/btif_profile_storage.cc
+++ b/system/btif/src/btif_profile_storage.cc
@@ -40,9 +40,9 @@
#include "btif_config.h"
#include "btif_hh.h"
#include "btif_storage.h"
-#include "gd/storage/config_keys.h"
#include "stack/include/bt_uuid16.h"
#include "stack/include/main_thread.h"
+#include "storage/config_keys.h"
#include "types/bluetooth/uuid.h"
#include "types/raw_address.h"
@@ -127,6 +127,7 @@
bt_status_t btif_storage_load_bonded_hid_info(void) {
for (const auto& bd_addr : btif_config_get_paired_devices()) {
auto name = bd_addr.ToString();
+ tAclLinkSpec link_spec;
LOG_VERBOSE("Remote device:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
@@ -179,8 +180,11 @@
}
// add extracted information to BTA HH
- if (btif_hh_add_added_dev(bd_addr, attr_mask)) {
- BTA_HhAddDev(bd_addr, attr_mask, sub_class, app_id, dscp_info);
+ link_spec.addrt.bda = bd_addr;
+ link_spec.addrt.type = BLE_ADDR_PUBLIC;
+ link_spec.transport = BT_TRANSPORT_AUTO;
+ if (btif_hh_add_added_dev(link_spec, attr_mask)) {
+ BTA_HhAddDev(link_spec, attr_mask, sub_class, app_id, dscp_info);
}
}
@@ -959,21 +963,6 @@
}
}
-void btif_storage_set_csis_autoconnect(const RawAddress& addr,
- bool autoconnect) {
- do_in_jni_thread(FROM_HERE, Bind(
- [](const RawAddress& addr, bool autoconnect) {
- std::string bdstr = addr.ToString();
- VLOG(2) << "Storing CSIS device: "
- << ADDRESS_TO_LOGGABLE_CSTR(addr);
- btif_config_set_int(
- bdstr,
- BTIF_STORAGE_KEY_CSIS_AUTOCONNECT,
- autoconnect);
- },
- addr, autoconnect));
-}
-
/** Stores information about the bonded CSIS device */
void btif_storage_update_csis_info(const RawAddress& addr) {
std::vector<uint8_t> set_info;
@@ -998,11 +987,6 @@
LOG_VERBOSE("Loading CSIS device:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
- int value;
- bool autoconnect = false;
- if (btif_config_get_int(name, BTIF_STORAGE_KEY_CSIS_AUTOCONNECT, &value))
- autoconnect = !!value;
-
size_t buffer_size =
btif_config_get_bin_length(name, BTIF_STORAGE_KEY_CSIS_SET_INFO_BIN);
std::vector<uint8_t> in(buffer_size);
@@ -1010,9 +994,9 @@
btif_config_get_bin(name, BTIF_STORAGE_KEY_CSIS_SET_INFO_BIN, in.data(),
&buffer_size);
- if (buffer_size != 0 || autoconnect)
- do_in_main_thread(FROM_HERE, Bind(&CsisClient::AddFromStorage, bd_addr,
- std::move(in), autoconnect));
+ if (buffer_size != 0)
+ do_in_main_thread(
+ FROM_HERE, Bind(&CsisClient::AddFromStorage, bd_addr, std::move(in)));
}
}
diff --git a/system/btif/src/btif_sdp_server.cc b/system/btif/src/btif_sdp_server.cc
index e861aeb..75653a7 100644
--- a/system/btif/src/btif_sdp_server.cc
+++ b/system/btif/src/btif_sdp_server.cc
@@ -40,6 +40,7 @@
#include "bta/sys/bta_sys.h"
#include "btif_common.h"
#include "btif_sock_sdp.h"
+#include "common/init_flags.h"
#include "osi/include/allocator.h"
#include "stack/include/bt_types.h"
#include "stack/include/bt_uuid16.h"
diff --git a/system/btif/src/btif_storage.cc b/system/btif/src/btif_storage.cc
index 7069431..8cfc4e8 100644
--- a/system/btif/src/btif_storage.cc
+++ b/system/btif/src/btif_storage.cc
@@ -46,13 +46,14 @@
#include "btif_config.h"
#include "btif_storage.h"
#include "btif_util.h"
+#include "common/init_flags.h"
#include "core_callbacks.h"
#include "device/include/controller.h"
-#include "gd/storage/config_keys.h"
#include "internal_include/bt_target.h"
#include "osi/include/allocator.h"
#include "stack/include/bt_octets.h"
#include "stack/include/bt_uuid16.h"
+#include "storage/config_keys.h"
#include "types/bluetooth/uuid.h"
#include "types/raw_address.h"
diff --git a/system/btif/test/btif_config_cache_test.cc b/system/btif/test/btif_config_cache_test.cc
index 46a4aa5..d1a44dc 100644
--- a/system/btif/test/btif_config_cache_test.cc
+++ b/system/btif/test/btif_config_cache_test.cc
@@ -21,8 +21,8 @@
#include <filesystem>
-#include "gd/storage/config_keys.h"
#include "stack/include/bt_octets.h"
+#include "storage/config_keys.h"
namespace {
diff --git a/system/btif/test/btif_core_test.cc b/system/btif/test/btif_core_test.cc
index c3ba67d..4414b06 100644
--- a/system/btif/test/btif_core_test.cc
+++ b/system/btif/test/btif_core_test.cc
@@ -753,3 +753,21 @@
ASSERT_EQ(7, btif_dm_get_connection_state(kRawAddress));
test::mock::stack_btm_sec::BTM_IsEncrypted = {};
}
+
+TEST_F(BtifCoreWithControllerTest, btif_dm_get_connection_state_sync) {
+ bta_dm_acl_up(kRawAddress, BT_TRANSPORT_AUTO, 0x123);
+
+ test::mock::stack_btm_sec::BTM_IsEncrypted.body =
+ [](const RawAddress& /* bd_addr */, tBT_TRANSPORT transport) {
+ switch (transport) {
+ case BT_TRANSPORT_BR_EDR:
+ return true;
+ case BT_TRANSPORT_LE:
+ return true;
+ }
+ return false;
+ };
+ ASSERT_EQ(7, btif_dm_get_connection_state_sync(kRawAddress));
+
+ test::mock::stack_btm_sec::BTM_IsEncrypted = {};
+}
diff --git a/system/btif/test/btif_dm_test.cc b/system/btif/test/btif_dm_test.cc
index 852c0aa..d1d6b07 100644
--- a/system/btif/test/btif_dm_test.cc
+++ b/system/btif/test/btif_dm_test.cc
@@ -24,8 +24,8 @@
#include "bta/include/bta_api_data_types.h"
#include "btif/include/mock_core_callbacks.h"
-#include "gd/module.h"
#include "main/shim/stack.h"
+#include "module.h"
#include "stack/include/btm_ble_api_types.h"
#include "storage/storage_module.h"
diff --git a/system/btif/test/btif_hh_test.cc b/system/btif/test/btif_hh_test.cc
index f5da8d8..a7088b6 100644
--- a/system/btif/test/btif_hh_test.cc
+++ b/system/btif/test/btif_hh_test.cc
@@ -47,8 +47,8 @@
const tBTA_AG_RES_DATA tBTA_AG_RES_DATA::kEmpty = {};
const bthh_interface_t* btif_hh_get_interface();
-bt_status_t btif_hh_connect(const RawAddress* bd_addr);
-bt_status_t btif_hh_virtual_unplug(const RawAddress* bd_addr);
+bt_status_t btif_hh_connect(const tAclLinkSpec* link_spec);
+bt_status_t btif_hh_virtual_unplug(const tAclLinkSpec* link_spec);
namespace bluetooth {
namespace legacy {
@@ -76,7 +76,11 @@
const RawAddress kDeviceAddress({0x11, 0x22, 0x33, 0x44, 0x55, 0x66});
const RawAddress kDeviceAddressConnecting({0x66, 0x55, 0x44, 0x33, 0x22, 0x11});
const uint16_t kHhHandle = 123;
-
+const tBLE_ADDR_TYPE kDeviceAddrType = BLE_ADDR_PUBLIC;
+const tBT_TRANSPORT kDeviceTransport = BT_TRANSPORT_AUTO;
+const tAclLinkSpec kDeviceConnecting = {.addrt.type = kDeviceAddrType,
+ .addrt.bda = kDeviceAddressConnecting,
+ .transport = kDeviceTransport};
// Callback parameters grouped into a structure
struct get_report_cb_t {
RawAddress raw_address;
@@ -195,7 +199,9 @@
BtifHhAdapterReady::SetUp();
// Short circuit a connected device
- btif_hh_cb.devices[0].bd_addr = kDeviceAddress;
+ btif_hh_cb.devices[0].link_spec.addrt.bda = kDeviceAddress;
+ btif_hh_cb.devices[0].link_spec.addrt.type = kDeviceAddrType;
+ btif_hh_cb.devices[0].link_spec.transport = kDeviceTransport;
btif_hh_cb.devices[0].dev_status = BTHH_CONN_STATE_CONNECTED;
btif_hh_cb.devices[0].dev_handle = kHhHandle;
}
@@ -279,7 +285,7 @@
auto future = g_bthh_connection_state_promise.get_future();
/* Make device in connecting state */
- ASSERT_EQ(btif_hh_connect(&kDeviceAddressConnecting), BT_STATUS_SUCCESS);
+ ASSERT_EQ(btif_hh_connect(&kDeviceConnecting), BT_STATUS_SUCCESS);
ASSERT_EQ(std::future_status::ready, future.wait_for(2s));
@@ -291,7 +297,7 @@
g_bthh_connection_state_promise = std::promise<connection_state_cb_t>();
future = g_bthh_connection_state_promise.get_future();
- btif_hh_virtual_unplug(&kDeviceAddressConnecting);
+ btif_hh_virtual_unplug(&kDeviceConnecting);
ASSERT_EQ(std::future_status::ready, future.wait_for(2s));
diff --git a/system/common/BUILD.gn b/system/common/BUILD.gn
index f5afaf2..58c3a9d 100644
--- a/system/common/BUILD.gn
+++ b/system/common/BUILD.gn
@@ -37,7 +37,10 @@
"//bt/system/gd/rust/shim:init_flags_bridge_header",
]
- configs += [ "//bt/system:target_defaults" ]
+ configs += [
+ "//bt/system:target_defaults",
+ "//bt/system/log:log_defaults",
+ ]
}
if (use.test) {
diff --git a/system/common/base_bind_unittest.cc b/system/common/base_bind_unittest.cc
index a5dc157..7c77f97 100644
--- a/system/common/base_bind_unittest.cc
+++ b/system/common/base_bind_unittest.cc
@@ -24,7 +24,7 @@
#include <memory>
#include <mutex>
-#include "osi/include/log.h"
+#include "os/log.h"
class BaseBindThreadTest : public ::testing::Test {
public:
diff --git a/system/common/stop_watch_legacy.cc b/system/common/stop_watch_legacy.cc
index f7d8ba9..6b783cb 100644
--- a/system/common/stop_watch_legacy.cc
+++ b/system/common/stop_watch_legacy.cc
@@ -18,13 +18,15 @@
#include "common/stop_watch_legacy.h"
+#include <base/logging.h>
+
#include <iomanip>
#include <mutex>
#include <sstream>
#include <utility>
-#include <base/logging.h>
-#include "osi/include/log.h"
+#include "common/init_flags.h"
+#include "os/log.h"
namespace bluetooth {
namespace common {
diff --git a/system/conf/interop_database.conf b/system/conf/interop_database.conf
index 84853bc0..ecc878e 100644
--- a/system/conf/interop_database.conf
+++ b/system/conf/interop_database.conf
@@ -856,3 +856,4 @@
# SMP key exchange completed.
[INTEROP_SUSPEND_ATT_TRAFFIC_DURING_PAIRING]
ORN = Name_Based
+EPG = Name_Based
diff --git a/system/device/BUILD.gn b/system/device/BUILD.gn
index 554ef3c..1d8c938 100644
--- a/system/device/BUILD.gn
+++ b/system/device/BUILD.gn
@@ -30,6 +30,7 @@
configs += [
"//bt/system:target_defaults",
+ "//bt/system/log:log_defaults",
]
deps = [
diff --git a/system/device/src/interop.cc b/system/device/src/interop.cc
index 833587f..6058a48 100644
--- a/system/device/src/interop.cc
+++ b/system/device/src/interop.cc
@@ -42,11 +42,11 @@
#include "check.h"
#include "device/include/interop_config.h"
#include "device/include/interop_database.h"
+#include "os/log.h"
#include "osi/include/allocator.h"
#include "osi/include/compat.h"
#include "osi/include/config.h"
#include "osi/include/list.h"
-#include "osi/include/log.h"
#include "osi/include/osi.h"
#include "types/raw_address.h"
diff --git a/system/gd/Android.bp b/system/gd/Android.bp
index e3ec8eb..d8ba613 100644
--- a/system/gd/Android.bp
+++ b/system/gd/Android.bp
@@ -181,6 +181,7 @@
"libbt-platform-protos-lite",
"libbt_shim_bridge",
"libbt_shim_ffi",
+ "libcom.android.sysprop.bluetooth.wrapped",
"libosi",
"server_configurable_flags",
],
@@ -318,10 +319,12 @@
"libbt_shim_bridge",
"libbt_shim_ffi",
"libchrome",
+ "libcom.android.sysprop.bluetooth.wrapped",
"libflatbuffers-cpp",
"libosi",
],
shared_libs: [
+ "libPlatformProperties",
"libcrypto",
"libgrpc++",
"libgrpc_wrap",
@@ -449,12 +452,14 @@
"libbt_shim_ffi",
"libc++fs",
"libchrome",
+ "libcom.android.sysprop.bluetooth.wrapped",
"libflagtest",
"libflatbuffers-cpp",
"libgmock",
"libosi",
],
shared_libs: [
+ "libPlatformProperties",
"libbase",
"libcrypto",
"server_configurable_flags",
@@ -494,6 +499,7 @@
"BluetoothGeneratedDumpsysTestData_h",
],
static_libs: [
+ "libbase",
"libbluetooth-gdx",
"libbluetooth-types",
"libbluetooth_gd",
@@ -507,6 +513,7 @@
"libevent",
"libflatbuffers-cpp",
"libgmock",
+ "liblog",
"libosi",
],
shared_libs: [
@@ -583,6 +590,7 @@
"libbt_shim_bridge",
"libbt_shim_ffi",
"libchrome",
+ "libcom.android.sysprop.bluetooth.wrapped",
"libgmock",
"libgtest",
"libosi",
@@ -592,6 +600,7 @@
"BluetoothGeneratedDumpsysDataSchema_h",
],
shared_libs: [
+ "libPlatformProperties",
"libbase",
"libcrypto",
"libgrpc++",
diff --git a/system/gd/BUILD.gn b/system/gd/BUILD.gn
index c59edb8..8b5a0d0 100644
--- a/system/gd/BUILD.gn
+++ b/system/gd/BUILD.gn
@@ -35,7 +35,10 @@
]
include_dirs = [ "//bt/system/gd" ]
- configs = [ "//bt/system:target_defaults" ]
+ configs = [
+ "//bt/system:target_defaults",
+ "//bt/system/log:log_defaults",
+ ]
}
config("rust_defaults") {
diff --git a/system/gd/dumpsys/bundler/Android.bp b/system/gd/dumpsys/bundler/Android.bp
index 0a5f57d..c3548c7 100644
--- a/system/gd/dumpsys/bundler/Android.bp
+++ b/system/gd/dumpsys/bundler/Android.bp
@@ -29,6 +29,7 @@
genrule {
name: "BluetoothGeneratedBundlerSchema_h_bfbs",
visibility: [
+ "//packages/modules/Bluetooth/system/btif",
"//packages/modules/Bluetooth/system/gd",
"//packages/modules/Bluetooth/system/main",
"//packages/modules/Bluetooth/system/rust",
diff --git a/system/gd/hci/acl_manager.cc b/system/gd/hci/acl_manager.cc
index 9041d5d..78d6d46 100644
--- a/system/gd/hci/acl_manager.cc
+++ b/system/gd/hci/acl_manager.cc
@@ -23,7 +23,6 @@
#include "common/bidi_queue.h"
#include "common/byte_array.h"
#include "dumpsys_data_generated.h"
-#include "gd/storage/config_keys.h"
#include "hci/acl_manager/acl_scheduler.h"
#include "hci/acl_manager/classic_impl.h"
#include "hci/acl_manager/le_acceptlist_callbacks.h"
@@ -35,6 +34,7 @@
#include "hci/remote_name_request.h"
#include "hci_acl_manager_generated.h"
#include "security/security_module.h"
+#include "storage/config_keys.h"
#include "storage/storage_module.h"
namespace bluetooth {
@@ -443,7 +443,7 @@
void AclManager::impl::Dump(
std::promise<flatbuffers::Offset<AclManagerData>> promise, flatbuffers::FlatBufferBuilder* fb_builder) const {
const std::lock_guard<std::mutex> lock(dumpsys_mutex_);
- const auto connect_list = (le_impl_ != nullptr) ? le_impl_->connect_list : std::unordered_set<AddressWithType>();
+ const auto accept_list = (le_impl_ != nullptr) ? le_impl_->accept_list : std::unordered_set<AddressWithType>();
const auto le_connectability_state_text =
(le_impl_ != nullptr) ? connectability_state_machine_text(le_impl_->connectability_state_) : "INDETERMINATE";
const auto le_create_connection_timeout_alarms_count =
@@ -452,17 +452,17 @@
auto title = fb_builder->CreateString("----- Acl Manager Dumpsys -----");
auto le_connectability_state = fb_builder->CreateString(le_connectability_state_text);
- flatbuffers::Offset<flatbuffers::String> strings[connect_list.size()];
+ flatbuffers::Offset<flatbuffers::String> strings[accept_list.size()];
size_t cnt = 0;
- for (const auto& it : connect_list) {
+ for (const auto& it : accept_list) {
strings[cnt++] = fb_builder->CreateString(it.ToString());
}
- auto vecofstrings = fb_builder->CreateVector(strings, connect_list.size());
+ auto vecofstrings = fb_builder->CreateVector(strings, accept_list.size());
AclManagerDataBuilder builder(*fb_builder);
builder.add_title(title);
- builder.add_le_filter_accept_list_count(connect_list.size());
+ builder.add_le_filter_accept_list_count(accept_list.size());
builder.add_le_filter_accept_list(vecofstrings);
builder.add_le_connectability_state(le_connectability_state);
builder.add_le_create_connection_timeout_alarms_count(le_create_connection_timeout_alarms_count);
diff --git a/system/gd/hci/acl_manager/le_impl.h b/system/gd/hci/acl_manager/le_impl.h
index 321a53f..946c8e6 100644
--- a/system/gd/hci/acl_manager/le_impl.h
+++ b/system/gd/hci/acl_manager/le_impl.h
@@ -154,10 +154,8 @@
SubeventCode code = event_packet.GetSubeventCode();
switch (code) {
case SubeventCode::CONNECTION_COMPLETE:
- on_le_connection_complete(event_packet);
- break;
case SubeventCode::ENHANCED_CONNECTION_COMPLETE:
- on_le_enhanced_connection_complete(event_packet);
+ on_le_connection_complete(event_packet);
break;
case SubeventCode::CONNECTION_UPDATE_COMPLETE:
on_le_connection_update_complete(event_packet);
@@ -330,22 +328,58 @@
}
connecting_le_.clear();
- if (create_connection_timeout_alarms_.find(address_with_type) != create_connection_timeout_alarms_.end()) {
- create_connection_timeout_alarms_.at(address_with_type).Cancel();
- create_connection_timeout_alarms_.erase(address_with_type);
- }
+ direct_connect_remove(address_with_type);
}
void on_le_connection_complete(LeMetaEventView packet) {
- LeConnectionCompleteView connection_complete = LeConnectionCompleteView::Create(packet);
- ASSERT(connection_complete.IsValid());
- auto status = connection_complete.GetStatus();
- auto address = connection_complete.GetPeerAddress();
- auto peer_address_type = connection_complete.GetPeerAddressType();
- auto role = connection_complete.GetRole();
- AddressWithType remote_address(address, peer_address_type);
- AddressWithType local_address = le_address_manager_->GetInitiatorAddress();
- const bool in_filter_accept_list = is_device_in_connect_list(remote_address);
+ ErrorCode status;
+ Address address;
+ AddressType peer_address_type;
+ Role role;
+ AddressWithType remote_address;
+ uint16_t handle, conn_interval, conn_latency, supervision_timeout;
+
+ if (packet.GetSubeventCode() == SubeventCode::CONNECTION_COMPLETE) {
+ LeConnectionCompleteView connection_complete = LeConnectionCompleteView::Create(packet);
+ ASSERT(connection_complete.IsValid());
+ status = connection_complete.GetStatus();
+ address = connection_complete.GetPeerAddress();
+ peer_address_type = connection_complete.GetPeerAddressType();
+ role = connection_complete.GetRole();
+ handle = connection_complete.GetConnectionHandle();
+ conn_interval = connection_complete.GetConnInterval();
+ conn_latency = connection_complete.GetConnLatency();
+ supervision_timeout = connection_complete.GetSupervisionTimeout();
+ remote_address = AddressWithType(address, peer_address_type);
+ } else if (packet.GetSubeventCode() == SubeventCode::ENHANCED_CONNECTION_COMPLETE) {
+ LeEnhancedConnectionCompleteView connection_complete =
+ LeEnhancedConnectionCompleteView::Create(packet);
+ ASSERT(connection_complete.IsValid());
+ status = connection_complete.GetStatus();
+ address = connection_complete.GetPeerAddress();
+ peer_address_type = connection_complete.GetPeerAddressType();
+ role = connection_complete.GetRole();
+ handle = connection_complete.GetConnectionHandle();
+ conn_interval = connection_complete.GetConnInterval();
+ conn_latency = connection_complete.GetConnLatency();
+ supervision_timeout = connection_complete.GetSupervisionTimeout();
+ AddressType remote_address_type;
+ switch (peer_address_type) {
+ case AddressType::PUBLIC_DEVICE_ADDRESS:
+ case AddressType::PUBLIC_IDENTITY_ADDRESS:
+ remote_address_type = AddressType::PUBLIC_DEVICE_ADDRESS;
+ break;
+ case AddressType::RANDOM_DEVICE_ADDRESS:
+ case AddressType::RANDOM_IDENTITY_ADDRESS:
+ remote_address_type = AddressType::RANDOM_DEVICE_ADDRESS;
+ break;
+ }
+ remote_address = AddressWithType(address, remote_address_type);
+ } else {
+ LOG_ALWAYS_FATAL("Bad subevent code:%02x", packet.GetSubeventCode());
+ }
+
+ const bool in_filter_accept_list = is_device_in_accept_list(remote_address);
if (role == hci::Role::CENTRAL) {
connectability_state_ = ConnectabilityState::DISARMED;
@@ -371,9 +405,9 @@
arm_on_resume_ = false;
ready_to_unregister = true;
- remove_device_from_connect_list(remote_address);
+ remove_device_from_accept_list(remote_address);
- if (!connect_list.empty()) {
+ if (!accept_list.empty()) {
AddressWithType empty(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS);
handler_->Post(common::BindOnce(&le_impl::create_le_connection, common::Unretained(this), empty, false, false));
}
@@ -405,23 +439,15 @@
LOG_INFO(
"Received incoming connection of device in filter accept_list, %s",
ADDRESS_TO_LOGGABLE_CSTR(remote_address));
- remove_device_from_connect_list(remote_address);
- if (create_connection_timeout_alarms_.find(remote_address) != create_connection_timeout_alarms_.end()) {
- create_connection_timeout_alarms_.at(remote_address).Cancel();
- create_connection_timeout_alarms_.erase(remote_address);
- }
+ direct_connect_remove(remote_address);
+ remove_device_from_accept_list(remote_address);
}
}
- uint16_t conn_interval = connection_complete.GetConnInterval();
- uint16_t conn_latency = connection_complete.GetConnLatency();
- uint16_t supervision_timeout = connection_complete.GetSupervisionTimeout();
if (!check_connection_parameters(conn_interval, conn_interval, conn_latency, supervision_timeout)) {
LOG_ERROR("Receive connection complete with invalid connection parameters");
return;
}
-
- uint16_t handle = connection_complete.GetConnectionHandle();
auto role_specific_data = initialize_role_specific_data(role);
auto queue = std::make_shared<AclConnection::Queue>(10);
auto queue_down_end = queue->GetDownEnd();
@@ -438,151 +464,20 @@
connection->supervision_timeout_ = supervision_timeout;
connection->in_filter_accept_list_ = in_filter_accept_list;
connection->locally_initiated_ = (role == hci::Role::CENTRAL);
- auto connection_callbacks = connection->GetEventCallbacks(
- [this](uint16_t handle) { this->connections.invalidate(handle); });
- if (std::holds_alternative<DataAsUninitializedPeripheral>(role_specific_data)) {
- // the OnLeConnectSuccess event will be sent after receiving the On Advertising Set Terminated
- // event, since we need it to know what local_address / advertising set the peer connected to.
- // In the meantime, we store it as a pending_connection.
- connections.add(
- handle,
- remote_address,
- std::move(connection),
- queue_down_end,
- handler_,
- connection_callbacks);
- } else {
- connections.add(
- handle, remote_address, nullptr, queue_down_end, handler_, connection_callbacks);
- le_client_handler_->Post(common::BindOnce(
- &LeConnectionCallbacks::OnLeConnectSuccess,
- common::Unretained(le_client_callbacks_),
- remote_address,
- std::move(connection)));
- if (le_acceptlist_callbacks_ != nullptr) {
- le_acceptlist_callbacks_->OnLeConnectSuccess(remote_address);
- }
+
+ if (packet.GetSubeventCode() == SubeventCode::ENHANCED_CONNECTION_COMPLETE) {
+ LeEnhancedConnectionCompleteView connection_complete =
+ LeEnhancedConnectionCompleteView::Create(packet);
+ ASSERT(connection_complete.IsValid());
+
+ connection->local_resolvable_private_address_ =
+ connection_complete.GetLocalResolvablePrivateAddress();
+ connection->peer_resolvable_private_address_ =
+ connection_complete.GetPeerResolvablePrivateAddress();
}
- }
-
- void on_le_enhanced_connection_complete(LeMetaEventView packet) {
- LeEnhancedConnectionCompleteView connection_complete = LeEnhancedConnectionCompleteView::Create(packet);
- ASSERT(connection_complete.IsValid());
- auto status = connection_complete.GetStatus();
- auto address = connection_complete.GetPeerAddress();
- auto peer_address_type = connection_complete.GetPeerAddressType();
- auto peer_resolvable_address = connection_complete.GetPeerResolvablePrivateAddress();
- auto role = connection_complete.GetRole();
-
- AddressType remote_address_type;
- switch (peer_address_type) {
- case AddressType::PUBLIC_DEVICE_ADDRESS:
- case AddressType::PUBLIC_IDENTITY_ADDRESS:
- remote_address_type = AddressType::PUBLIC_DEVICE_ADDRESS;
- break;
- case AddressType::RANDOM_DEVICE_ADDRESS:
- case AddressType::RANDOM_IDENTITY_ADDRESS:
- remote_address_type = AddressType::RANDOM_DEVICE_ADDRESS;
- break;
- }
- AddressWithType remote_address(address, remote_address_type);
- const bool in_filter_accept_list = is_device_in_connect_list(remote_address);
-
-
- if (role == hci::Role::CENTRAL) {
- connectability_state_ = ConnectabilityState::DISARMED;
-
- if (status == ErrorCode::UNKNOWN_CONNECTION && pause_connection) {
- on_le_connection_canceled_on_pause();
- return;
- }
-
- on_common_le_connection_complete(remote_address);
- if (status == ErrorCode::UNKNOWN_CONNECTION) {
- if (remote_address.GetAddress() != Address::kEmpty) {
- LOG_INFO("Controller send non-empty address field:%s",
- ADDRESS_TO_LOGGABLE_CSTR(remote_address.GetAddress()));
- }
- // direct connect canceled due to connection timeout, start background connect
- create_le_connection(remote_address, false, false);
- return;
- }
-
- arm_on_resume_ = false;
- ready_to_unregister = true;
- remove_device_from_connect_list(remote_address);
-
- if (!connect_list.empty()) {
- AddressWithType empty(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS);
- handler_->Post(common::BindOnce(&le_impl::create_le_connection, common::Unretained(this), empty, false, false));
- }
-
- if (le_client_handler_ == nullptr) {
- LOG_ERROR("No callbacks to call");
- return;
- }
-
- if (status != ErrorCode::SUCCESS) {
- report_le_connection_failure(remote_address, status);
- return;
- }
-
- } else {
- LOG_INFO("Received connection complete with Peripheral role");
- if (le_client_handler_ == nullptr) {
- LOG_ERROR("No callbacks to call");
- return;
- }
-
- if (status != ErrorCode::SUCCESS) {
- std::string error_code = ErrorCodeText(status);
- LOG_WARN("Received on_le_enhanced_connection_complete with error code %s", error_code.c_str());
- report_le_connection_failure(remote_address, status);
- return;
- }
-
- if (in_filter_accept_list) {
- LOG_INFO(
- "Received incoming connection of device in filter accept_list, %s",
- ADDRESS_TO_LOGGABLE_CSTR(remote_address));
- remove_device_from_connect_list(remote_address);
- if (create_connection_timeout_alarms_.find(remote_address) != create_connection_timeout_alarms_.end()) {
- create_connection_timeout_alarms_.at(remote_address).Cancel();
- create_connection_timeout_alarms_.erase(remote_address);
- }
- }
- }
-
- auto role_specific_data = initialize_role_specific_data(role);
- uint16_t conn_interval = connection_complete.GetConnInterval();
- uint16_t conn_latency = connection_complete.GetConnLatency();
- uint16_t supervision_timeout = connection_complete.GetSupervisionTimeout();
- if (!check_connection_parameters(conn_interval, conn_interval, conn_latency, supervision_timeout)) {
- LOG_ERROR("Receive enhenced connection complete with invalid connection parameters");
- return;
- }
- uint16_t handle = connection_complete.GetConnectionHandle();
- auto queue = std::make_shared<AclConnection::Queue>(10);
- auto queue_down_end = queue->GetDownEnd();
- round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::LE, handle, queue);
- std::unique_ptr<LeAclConnection> connection(new LeAclConnection(
- std::move(queue),
- le_acl_connection_interface_,
- handle,
- role_specific_data,
- remote_address));
- connection->peer_address_with_type_ = AddressWithType(address, peer_address_type);
- connection->interval_ = conn_interval;
- connection->latency_ = conn_latency;
- connection->supervision_timeout_ = supervision_timeout;
- connection->local_resolvable_private_address_ = connection_complete.GetLocalResolvablePrivateAddress();
- connection->peer_resolvable_private_address_ = connection_complete.GetPeerResolvablePrivateAddress();
- connection->in_filter_accept_list_ = in_filter_accept_list;
- connection->locally_initiated_ = (role == hci::Role::CENTRAL);
auto connection_callbacks = connection->GetEventCallbacks(
[this](uint16_t handle) { this->connections.invalidate(handle); });
-
if (std::holds_alternative<DataAsUninitializedPeripheral>(role_specific_data)) {
// the OnLeConnectSuccess event will be sent after receiving the On Advertising Set Terminated
// event, since we need it to know what local_address / advertising set the peer connected to.
@@ -646,9 +541,9 @@
connections.crash_on_unknown_handle_ = event_also_routes_to_other_receivers;
if (background_connections_.count(remote_address) == 1) {
- LOG_INFO("re-add device to connect list");
+ LOG_INFO("re-add device to accept list");
arm_on_resume_ = true;
- add_device_to_connect_list(remote_address);
+ add_device_to_accept_list(remote_address);
}
}
@@ -768,46 +663,71 @@
}
}
- void add_device_to_connect_list(AddressWithType address_with_type) {
+ void direct_connect_add(AddressWithType address_with_type) {
+ direct_connections_.insert(address_with_type);
+ if (create_connection_timeout_alarms_.find(address_with_type) != create_connection_timeout_alarms_.end()) {
+ return;
+ }
+
+ auto emplace_result = create_connection_timeout_alarms_.emplace(
+ std::piecewise_construct,
+ std::forward_as_tuple(address_with_type.GetAddress(), address_with_type.GetAddressType()),
+ std::forward_as_tuple(handler_));
+ uint32_t connection_timeout =
+ os::GetSystemPropertyUint32(kPropertyDirectConnTimeout, kCreateConnectionTimeoutMs);
+ emplace_result.first->second.Schedule(
+ common::BindOnce(&le_impl::on_create_connection_timeout, common::Unretained(this), address_with_type),
+ std::chrono::milliseconds(connection_timeout));
+ }
+
+ void direct_connect_remove(AddressWithType address_with_type) {
+ auto it = create_connection_timeout_alarms_.find(address_with_type);
+ if (it != create_connection_timeout_alarms_.end()) {
+ it->second.Cancel();
+ create_connection_timeout_alarms_.erase(it);
+ }
+ direct_connections_.erase(address_with_type);
+ }
+
+ void add_device_to_accept_list(AddressWithType address_with_type) {
if (connections.alreadyConnected(address_with_type)) {
LOG_INFO("Device already connected, return");
return;
}
- if (connect_list.find(address_with_type) != connect_list.end()) {
+ if (accept_list.find(address_with_type) != accept_list.end()) {
LOG_WARN(
"Device already exists in acceptlist and cannot be added: %s",
ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
return;
}
- connect_list.insert(address_with_type);
+ accept_list.insert(address_with_type);
register_with_address_manager();
le_address_manager_->AddDeviceToFilterAcceptList(
address_with_type.ToFilterAcceptListAddressType(), address_with_type.GetAddress());
}
- bool is_device_in_connect_list(AddressWithType address_with_type) {
- return (connect_list.find(address_with_type) != connect_list.end());
+ bool is_device_in_accept_list(AddressWithType address_with_type) {
+ return (accept_list.find(address_with_type) != accept_list.end());
}
- void remove_device_from_connect_list(AddressWithType address_with_type) {
- if (connect_list.find(address_with_type) == connect_list.end()) {
+ void remove_device_from_accept_list(AddressWithType address_with_type) {
+ if (accept_list.find(address_with_type) == accept_list.end()) {
LOG_WARN(
"Device not in acceptlist and cannot be removed: %s",
ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
return;
}
- connect_list.erase(address_with_type);
+ accept_list.erase(address_with_type);
connecting_le_.erase(address_with_type);
- direct_connections_.erase(address_with_type);
register_with_address_manager();
le_address_manager_->RemoveDeviceFromFilterAcceptList(
address_with_type.ToFilterAcceptListAddressType(), address_with_type.GetAddress());
}
void clear_filter_accept_list() {
- connect_list.clear();
+ accept_list.clear();
register_with_address_manager();
le_address_manager_->ClearFilterAcceptList();
}
@@ -879,13 +799,13 @@
connectability_state_machine_text(connectability_state_).c_str());
return;
}
- if (connect_list.empty()) {
+ if (accept_list.empty()) {
LOG_INFO("Ignored request to re-arm le connection state machine when filter accept list is empty");
return;
}
AddressWithType empty(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS);
connectability_state_ = ConnectabilityState::ARMING;
- connecting_le_ = connect_list;
+ connecting_le_ = accept_list;
uint16_t le_scan_interval = os::GetSystemPropertyUint32(kPropertyConnScanIntervalSlow, kScanIntervalSlow);
uint16_t le_scan_window = os::GetSystemPropertyUint32(kPropertyConnScanWindowSlow, kScanWindowSlow);
@@ -1014,7 +934,7 @@
}
}
- void create_le_connection(AddressWithType address_with_type, bool add_to_connect_list, bool is_direct) {
+ void create_le_connection(AddressWithType address_with_type, bool add_to_accept_list, bool is_direct) {
if (le_client_callbacks_ == nullptr) {
LOG_ERROR("No callbacks to call");
return;
@@ -1025,27 +945,15 @@
return;
}
- bool already_in_connect_list = connect_list.find(address_with_type) != connect_list.end();
+ bool already_in_accept_list = accept_list.find(address_with_type) != accept_list.end();
// TODO: Configure default LE connection parameters?
- if (add_to_connect_list) {
- if (!already_in_connect_list) {
- add_device_to_connect_list(address_with_type);
+ if (add_to_accept_list) {
+ if (!already_in_accept_list) {
+ add_device_to_accept_list(address_with_type);
}
if (is_direct) {
- direct_connections_.insert(address_with_type);
- if (create_connection_timeout_alarms_.find(address_with_type) == create_connection_timeout_alarms_.end()) {
- create_connection_timeout_alarms_.emplace(
- std::piecewise_construct,
- std::forward_as_tuple(address_with_type.GetAddress(), address_with_type.GetAddressType()),
- std::forward_as_tuple(handler_));
- uint32_t connection_timeout =
- os::GetSystemPropertyUint32(kPropertyDirectConnTimeout, kCreateConnectionTimeoutMs);
- create_connection_timeout_alarms_.at(address_with_type)
- .Schedule(
- common::BindOnce(&le_impl::on_create_connection_timeout, common::Unretained(this), address_with_type),
- std::chrono::milliseconds(connection_timeout));
- }
+ direct_connect_add(address_with_type);
}
}
@@ -1068,7 +976,7 @@
switch (connectability_state_) {
case ConnectabilityState::ARMED:
case ConnectabilityState::ARMING:
- if (already_in_connect_list) {
+ if (already_in_accept_list) {
arm_on_disarm_ = true;
disarm_connectability();
} else {
@@ -1082,7 +990,7 @@
default:
// If we added to filter accept list then the arming of the le state machine
// must wait until the filter accept list command as completed
- if (add_to_connect_list) {
+ if (add_to_accept_list) {
arm_on_resume_ = true;
LOG_DEBUG("Deferred until filter accept list has completed");
} else {
@@ -1095,32 +1003,24 @@
void on_create_connection_timeout(AddressWithType address_with_type) {
LOG_INFO("on_create_connection_timeout, address: %s",
ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
- if (create_connection_timeout_alarms_.find(address_with_type) != create_connection_timeout_alarms_.end()) {
- create_connection_timeout_alarms_.at(address_with_type).Cancel();
- create_connection_timeout_alarms_.erase(address_with_type);
+ direct_connect_remove(address_with_type);
- if (background_connections_.find(address_with_type) != background_connections_.end()) {
- direct_connections_.erase(address_with_type);
- disarm_connectability();
- } else {
- cancel_connect(address_with_type);
- }
- le_client_handler_->Post(common::BindOnce(
- &LeConnectionCallbacks::OnLeConnectFail,
- common::Unretained(le_client_callbacks_),
- address_with_type,
- ErrorCode::CONNECTION_ACCEPT_TIMEOUT));
+ if (background_connections_.find(address_with_type) != background_connections_.end()) {
+ disarm_connectability();
+ } else {
+ remove_device_from_accept_list(address_with_type);
}
+ le_client_handler_->Post(common::BindOnce(
+ &LeConnectionCallbacks::OnLeConnectFail,
+ common::Unretained(le_client_callbacks_),
+ address_with_type,
+ ErrorCode::CONNECTION_ACCEPT_TIMEOUT));
}
void cancel_connect(AddressWithType address_with_type) {
- // Remove any alarms for this peer, if any
- if (create_connection_timeout_alarms_.find(address_with_type) != create_connection_timeout_alarms_.end()) {
- create_connection_timeout_alarms_.at(address_with_type).Cancel();
- create_connection_timeout_alarms_.erase(address_with_type);
- }
+ direct_connect_remove(address_with_type);
// the connection will be canceled by LeAddressManager.OnPause()
- remove_device_from_connect_list(address_with_type);
+ remove_device_from_accept_list(address_with_type);
}
void set_le_suggested_default_data_parameters(uint16_t length, uint16_t time) {
@@ -1315,9 +1215,10 @@
bool arm_on_resume_{};
bool arm_on_disarm_{};
std::unordered_set<AddressWithType> direct_connections_{};
- // Set of devices that will not be removed from connect list after direct connect timeout
+ // Set of devices that will not be removed from accept list after direct connect timeout
std::unordered_set<AddressWithType> background_connections_;
- std::unordered_set<AddressWithType> connect_list;
+ /* This is content of controller "Filter Accept List"*/
+ std::unordered_set<AddressWithType> accept_list;
AddressWithType connection_peer_address_with_type_; // Direct peer address UNSUPPORTEDD
bool address_manager_registered = false;
bool ready_to_unregister = false;
diff --git a/system/gd/hci/acl_manager/le_impl_test.cc b/system/gd/hci/acl_manager/le_impl_test.cc
index d67f9b6..1ea0121 100644
--- a/system/gd/hci/acl_manager/le_impl_test.cc
+++ b/system/gd/hci/acl_manager/le_impl_test.cc
@@ -461,42 +461,42 @@
std::unique_ptr<LeAclConnection> connection_;
};
-TEST_F(LeImplTest, add_device_to_connect_list) {
- le_impl_->add_device_to_connect_list({{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS});
- ASSERT_EQ(1UL, le_impl_->connect_list.size());
+TEST_F(LeImplTest, add_device_to_accept_list) {
+ le_impl_->add_device_to_accept_list({{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS});
+ ASSERT_EQ(1UL, le_impl_->accept_list.size());
- le_impl_->add_device_to_connect_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
- ASSERT_EQ(2UL, le_impl_->connect_list.size());
+ le_impl_->add_device_to_accept_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
+ ASSERT_EQ(2UL, le_impl_->accept_list.size());
- le_impl_->add_device_to_connect_list({{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS});
- ASSERT_EQ(2UL, le_impl_->connect_list.size());
+ le_impl_->add_device_to_accept_list({{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS});
+ ASSERT_EQ(2UL, le_impl_->accept_list.size());
- le_impl_->add_device_to_connect_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
- ASSERT_EQ(2UL, le_impl_->connect_list.size());
+ le_impl_->add_device_to_accept_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
+ ASSERT_EQ(2UL, le_impl_->accept_list.size());
}
-TEST_F(LeImplTest, remove_device_from_connect_list) {
- le_impl_->add_device_to_connect_list({{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS});
- le_impl_->add_device_to_connect_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
- le_impl_->add_device_to_connect_list({{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS});
- le_impl_->add_device_to_connect_list({{0x31, 0x32, 0x33, 0x34, 0x35, 0x36}, AddressType::PUBLIC_DEVICE_ADDRESS});
- ASSERT_EQ(4UL, le_impl_->connect_list.size());
+TEST_F(LeImplTest, remove_device_from_accept_list) {
+ le_impl_->add_device_to_accept_list({{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS});
+ le_impl_->add_device_to_accept_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
+ le_impl_->add_device_to_accept_list({{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS});
+ le_impl_->add_device_to_accept_list({{0x31, 0x32, 0x33, 0x34, 0x35, 0x36}, AddressType::PUBLIC_DEVICE_ADDRESS});
+ ASSERT_EQ(4UL, le_impl_->accept_list.size());
- le_impl_->remove_device_from_connect_list({{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS});
- ASSERT_EQ(3UL, le_impl_->connect_list.size());
+ le_impl_->remove_device_from_accept_list({{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS});
+ ASSERT_EQ(3UL, le_impl_->accept_list.size());
- le_impl_->remove_device_from_connect_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
- ASSERT_EQ(2UL, le_impl_->connect_list.size());
+ le_impl_->remove_device_from_accept_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
+ ASSERT_EQ(2UL, le_impl_->accept_list.size());
- le_impl_->remove_device_from_connect_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
- ASSERT_EQ(2UL, le_impl_->connect_list.size());
+ le_impl_->remove_device_from_accept_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
+ ASSERT_EQ(2UL, le_impl_->accept_list.size());
- le_impl_->remove_device_from_connect_list({Address::kEmpty, AddressType::PUBLIC_DEVICE_ADDRESS});
- ASSERT_EQ(2UL, le_impl_->connect_list.size());
+ le_impl_->remove_device_from_accept_list({Address::kEmpty, AddressType::PUBLIC_DEVICE_ADDRESS});
+ ASSERT_EQ(2UL, le_impl_->accept_list.size());
- le_impl_->remove_device_from_connect_list({{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS});
- le_impl_->remove_device_from_connect_list({{0x31, 0x32, 0x33, 0x34, 0x35, 0x36}, AddressType::PUBLIC_DEVICE_ADDRESS});
- ASSERT_EQ(0UL, le_impl_->connect_list.size());
+ le_impl_->remove_device_from_accept_list({{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS});
+ le_impl_->remove_device_from_accept_list({{0x31, 0x32, 0x33, 0x34, 0x35, 0x36}, AddressType::PUBLIC_DEVICE_ADDRESS});
+ ASSERT_EQ(0UL, le_impl_->accept_list.size());
}
TEST_F(LeImplTest, connection_complete_with_periperal_role) {
diff --git a/system/gd/hci/acl_manager_test.cc b/system/gd/hci/acl_manager_test.cc
index 04c6b5a..45b43c0 100644
--- a/system/gd/hci/acl_manager_test.cc
+++ b/system/gd/hci/acl_manager_test.cc
@@ -177,7 +177,7 @@
os::Handler* client_handler_ = nullptr;
Address remote;
AddressWithType my_initiating_address;
- const bool use_connect_list_ = true; // gd currently only supports connect list
+ const bool use_accept_list_ = true; // gd currently only supports connect list
std::future<void> GetConnectionFuture() {
ASSERT_LOG(connection_promise_ == nullptr, "Promises promises ... Only one at a time");
@@ -364,7 +364,7 @@
LeConnectionManagementCommandView::Create(AclCommandView::Create(packet));
auto command_view = LeCreateConnectionView::Create(le_connection_management_command_view);
ASSERT_TRUE(command_view.IsValid());
- if (use_connect_list_) {
+ if (use_accept_list_) {
ASSERT_EQ(command_view.GetPeerAddress(), empty_address_with_type.GetAddress());
ASSERT_EQ(command_view.GetPeerAddressType(), empty_address_with_type.GetAddressType());
} else {
@@ -455,7 +455,7 @@
LeConnectionManagementCommandView::Create(AclCommandView::Create(packet));
auto command_view = LeCreateConnectionView::Create(le_connection_management_command_view);
ASSERT_TRUE(command_view.IsValid());
- if (use_connect_list_) {
+ if (use_accept_list_) {
ASSERT_EQ(command_view.GetPeerAddress(), hci::Address::kEmpty);
} else {
ASSERT_EQ(command_view.GetPeerAddress(), remote);
@@ -1289,7 +1289,7 @@
LeConnectionManagementCommandView::Create(AclCommandView::Create(packet));
auto command_view = LeCreateConnectionView::Create(le_connection_management_command_view);
ASSERT_TRUE(command_view.IsValid());
- if (use_connect_list_) {
+ if (use_accept_list_) {
ASSERT_EQ(command_view.GetPeerAddress(), hci::Address::kEmpty);
} else {
ASSERT_EQ(command_view.GetPeerAddress(), remote);
@@ -1330,7 +1330,7 @@
LeConnectionManagementCommandView::Create(AclCommandView::Create(packet));
auto command_view = LeCreateConnectionView::Create(le_connection_management_command_view);
ASSERT_TRUE(command_view.IsValid());
- if (use_connect_list_) {
+ if (use_accept_list_) {
ASSERT_EQ(command_view.GetPeerAddress(), hci::Address::kEmpty);
} else {
ASSERT_EQ(command_view.GetPeerAddress(), remote);
diff --git a/system/gd/hci/acl_manager_unittest.cc b/system/gd/hci/acl_manager_unittest.cc
index b54729f..d953128 100644
--- a/system/gd/hci/acl_manager_unittest.cc
+++ b/system/gd/hci/acl_manager_unittest.cc
@@ -218,7 +218,7 @@
}
AddressWithType local_address_with_type_;
- const bool use_connect_list_ = true; // gd currently only supports connect list
+ const bool use_accept_list_ = true; // gd currently only supports connect list
void SendAclData(uint16_t handle, AclConnection::QueueUpEnd* queue_end) {
std::promise<void> promise;
@@ -412,7 +412,7 @@
LeConnectionManagementCommandView::Create(AclCommandView::Create(packet));
auto command_view = LeCreateConnectionView::Create(le_connection_management_command_view);
ASSERT_TRUE(command_view.IsValid());
- if (use_connect_list_) {
+ if (use_accept_list_) {
ASSERT_EQ(command_view.GetPeerAddress(), empty_address_with_type.GetAddress());
ASSERT_EQ(command_view.GetPeerAddressType(), empty_address_with_type.GetAddressType());
} else {
diff --git a/system/gd/hci/controller.cc b/system/gd/hci/controller.cc
index 340a832..a6c16a9 100644
--- a/system/gd/hci/controller.cc
+++ b/system/gd/hci/controller.cc
@@ -16,6 +16,8 @@
#include "hci/controller.h"
+#include <android_bluetooth_flags.h>
+
#include <future>
#include <memory>
#include <string>
@@ -107,7 +109,7 @@
hci_->EnqueueCommand(
LeReadFilterAcceptListSizeBuilder::Create(),
- handler->BindOnceOn(this, &Controller::impl::le_read_connect_list_size_handler));
+ handler->BindOnceOn(this, &Controller::impl::le_read_accept_list_size_handler));
if (is_supported(OpCode::LE_READ_RESOLVING_LIST_SIZE) && module_.SupportsBlePrivacy()) {
hci_->EnqueueCommand(
@@ -484,12 +486,12 @@
le_supported_states_ = complete_view.GetLeStates();
}
- void le_read_connect_list_size_handler(CommandCompleteView view) {
+ void le_read_accept_list_size_handler(CommandCompleteView view) {
auto complete_view = LeReadFilterAcceptListSizeCompleteView::Create(view);
ASSERT(complete_view.IsValid());
ErrorCode status = complete_view.GetStatus();
ASSERT_LOG(status == ErrorCode::SUCCESS, "Status 0x%02hhx, %s", status, ErrorCodeText(status).c_str());
- le_connect_list_size_ = complete_view.GetFilterAcceptListSize();
+ le_accept_list_size_ = complete_view.GetFilterAcceptListSize();
}
void le_read_resolving_list_size_handler(CommandCompleteView view) {
@@ -560,6 +562,7 @@
vendor_capabilities_.le_address_generation_offloading_support_ = 0x00;
vendor_capabilities_.a2dp_source_offload_capability_mask_ = 0x00;
vendor_capabilities_.bluetooth_quality_report_support_ = 0x00;
+ vendor_capabilities_.a2dp_offload_v2_support_ = 0x00;
if (!complete_view.IsValid()) {
vendor_promise.set_value();
@@ -636,16 +639,38 @@
}
vendor_capabilities_.dynamic_audio_buffer_support_ = v103.GetDynamicAudioBufferSupport();
- if (vendor_capabilities_.dynamic_audio_buffer_support_ == 0) {
+ if (IS_FLAG_ENABLED(a2dp_offload_codec_extensibility)) {
+ // v1.04
+ auto v104 = LeGetVendorCapabilitiesComplete104View::Create(v103);
+ if (!v104.IsValid()) {
+ LOG_INFO("invalid data for hci requirements v1.04");
+ } else {
+ vendor_capabilities_.a2dp_offload_v2_support_ = v104.GetA2dpOffloadV2Support();
+ }
+
+ if (vendor_capabilities_.dynamic_audio_buffer_support_) {
+ hci_->EnqueueCommand(
+ DabGetAudioBufferTimeCapabilityBuilder::Create(),
+ module_.GetHandler()->BindOnceOn(
+ this,
+ &Controller::impl::le_get_dynamic_audio_buffer_support_handler,
+ std::move(vendor_promise)));
+ return;
+ }
+
vendor_promise.set_value();
- return;
+ } else {
+ if (vendor_capabilities_.dynamic_audio_buffer_support_ == 0) {
+ vendor_promise.set_value();
+ return;
+ }
+ hci_->EnqueueCommand(
+ DabGetAudioBufferTimeCapabilityBuilder::Create(),
+ module_.GetHandler()->BindOnceOn(
+ this,
+ &Controller::impl::le_get_dynamic_audio_buffer_support_handler,
+ std::move(vendor_promise)));
}
- hci_->EnqueueCommand(
- DabGetAudioBufferTimeCapabilityBuilder::Create(),
- module_.GetHandler()->BindOnceOn(
- this,
- &Controller::impl::le_get_dynamic_audio_buffer_support_handler,
- std::move(vendor_promise)));
}
void le_get_dynamic_audio_buffer_support_handler(
@@ -1186,7 +1211,7 @@
LeBufferSize iso_buffer_size_{};
uint64_t le_local_supported_features_{};
uint64_t le_supported_states_{};
- uint8_t le_connect_list_size_{};
+ uint8_t le_accept_list_size_{};
uint8_t le_resolving_list_size_{};
LeMaximumDataLength le_maximum_data_length_{};
uint16_t le_maximum_advertising_data_length_{};
@@ -1439,7 +1464,7 @@
}
uint8_t Controller::GetLeFilterAcceptListSize() const {
- return impl_->le_connect_list_size_;
+ return impl_->le_accept_list_size_;
}
uint8_t Controller::GetLeResolvingListSize() const {
@@ -1594,7 +1619,7 @@
builder.add_iso_buffer_size(&iso_buffer_size_data);
builder.add_le_buffer_size(&le_buffer_size_data);
- builder.add_le_connect_list_size(le_connect_list_size_);
+ builder.add_le_accept_list_size(le_accept_list_size_);
builder.add_le_resolving_list_size(le_resolving_list_size_);
builder.add_le_maximum_data_length(&le_maximum_data_length_data);
diff --git a/system/gd/hci/controller_interface.h b/system/gd/hci/controller_interface.h
index fbd48ce..d0fe206 100644
--- a/system/gd/hci/controller_interface.h
+++ b/system/gd/hci/controller_interface.h
@@ -200,6 +200,7 @@
uint32_t a2dp_source_offload_capability_mask_;
uint8_t bluetooth_quality_report_support_;
uint32_t dynamic_audio_buffer_support_;
+ uint8_t a2dp_offload_v2_support_;
};
virtual uint32_t GetDabSupportedCodecs() const = 0;
diff --git a/system/gd/hci/controller_test.cc b/system/gd/hci/controller_test.cc
index e1e43a0..669da6f 100644
--- a/system/gd/hci/controller_test.cc
+++ b/system/gd/hci/controller_test.cc
@@ -16,6 +16,7 @@
#include "hci/controller.h"
+#include <android_bluetooth_flags.h>
#include <gtest/gtest.h>
#include <unistd.h>
@@ -359,6 +360,36 @@
}
};
+class Controller104Test : public ControllerTest {
+ protected:
+ void SetUp() override {
+ feature_spec_version_ = 0x100 + 0x04;
+ BaseVendorCapabilities base_vendor_capabilities;
+ base_vendor_capabilities.max_advt_instances_ = 0x10;
+ base_vendor_capabilities.offloaded_resolution_of_private_address_ = 0x01;
+ base_vendor_capabilities.total_scan_results_storage_ = 0x2800;
+ base_vendor_capabilities.max_irk_list_sz_ = 0x20;
+ base_vendor_capabilities.filtering_support_ = 0x01;
+ base_vendor_capabilities.max_filter_ = 0x10;
+ base_vendor_capabilities.activity_energy_info_support_ = 0x01;
+ vendor_capabilities_ = LeGetVendorCapabilitiesComplete104Builder::Create(
+ 1,
+ ErrorCode::SUCCESS,
+ base_vendor_capabilities,
+ feature_spec_version_,
+ 0x102,
+ /*extended_scan_support=*/1,
+ /*debug_logging_supported=*/1,
+ /*le_address_generation_offloading_support=*/0,
+ /*a2dp_source_offload_capability_mask=*/0x4,
+ /*bluetooth_quality_report_support=*/1,
+ kDynamicAudioBufferSupport,
+ /*a2dp_offload_v2_support=*/1,
+ std::make_unique<RawBuilder>());
+ ControllerTest::SetUp();
+ }
+};
+
TEST_F(ControllerTest, startup_teardown) {}
TEST_F(ControllerTest, read_controller_info) {
@@ -504,6 +535,7 @@
TEST_F(Controller103Test, feature_spec_version_103_dab_test) {
ASSERT_EQ(controller_->GetVendorCapabilities().version_supported_, 0x100 + 3);
+ ASSERT_FALSE(controller_->GetVendorCapabilities().a2dp_offload_v2_support_);
ASSERT_TRUE(controller_->IsSupported(OpCode::LE_MULTI_ADVT));
ASSERT_TRUE(controller_->IsSupported(OpCode::CONTROLLER_DEBUG_INFO));
ASSERT_TRUE(controller_->IsSupported(OpCode::CONTROLLER_A2DP_OPCODE));
@@ -526,6 +558,29 @@
ASSERT_EQ(123, test_hci_layer_->dynamic_audio_buffer_time);
}
+TEST_F(Controller104Test, feature_spec_version_104_test) {
+ ASSERT_EQ(controller_->GetVendorCapabilities().version_supported_, 0x100 + 4);
+ if (IS_FLAG_ENABLED(a2dp_offload_codec_extensibility)) {
+ ASSERT_TRUE(controller_->GetVendorCapabilities().a2dp_offload_v2_support_);
+ } else {
+ ASSERT_FALSE(controller_->GetVendorCapabilities().a2dp_offload_v2_support_);
+ }
+ ASSERT_TRUE(controller_->IsSupported(OpCode::LE_MULTI_ADVT));
+ ASSERT_TRUE(controller_->IsSupported(OpCode::CONTROLLER_DEBUG_INFO));
+ ASSERT_TRUE(controller_->IsSupported(OpCode::CONTROLLER_A2DP_OPCODE));
+ ASSERT_TRUE(controller_->IsSupported(OpCode::DYNAMIC_AUDIO_BUFFER));
+ ASSERT_EQ(controller_->GetDabSupportedCodecs(), kDynamicAudioBufferSupport);
+ for (size_t bit = 0; bit < 32; bit++) {
+ if (kDynamicAudioBufferSupport & (1u << bit)) {
+ ASSERT_GT(controller_->GetDabCodecCapabilities()[bit].maximum_time_ms_, 0) << " bit " << bit;
+ } else {
+ ASSERT_EQ(controller_->GetDabCodecCapabilities()[bit].maximum_time_ms_, 0);
+ ASSERT_EQ(controller_->GetDabCodecCapabilities()[bit].minimum_time_ms_, 0);
+ ASSERT_EQ(controller_->GetDabCodecCapabilities()[bit].default_time_ms_, 0);
+ }
+ }
+}
+
std::promise<void> credits1_set;
std::promise<void> credits2_set;
diff --git a/system/gd/hci/distance_measurement_manager.cc b/system/gd/hci/distance_measurement_manager.cc
index f8a26c5..dac1d9a 100644
--- a/system/gd/hci/distance_measurement_manager.cc
+++ b/system/gd/hci/distance_measurement_manager.cc
@@ -110,8 +110,8 @@
hci_layer_->RegisterLeEventHandler(
hci::SubeventCode::TRANSMIT_POWER_REPORTING,
handler_->BindOn(this, &impl::on_transmit_power_reporting));
- if (!IS_FLAG_ENABLED(channel_sounding)) {
- LOG_INFO("IS_FLAG_ENABLED channel_sounding: false");
+ if (!IS_FLAG_ENABLED(channel_sounding_in_stack)) {
+ LOG_INFO("IS_FLAG_ENABLED channel_sounding_in_stack: false");
return;
}
distance_measurement_interface_ = hci_layer_->GetDistanceMeasurementInterface(
@@ -172,7 +172,7 @@
"connection_handle: %d, address: %s",
connection_handle,
ADDRESS_TO_LOGGABLE_CSTR(cs_remote_address));
- if (!IS_FLAG_ENABLED(channel_sounding)) {
+ if (!IS_FLAG_ENABLED(channel_sounding_in_stack)) {
LOG_ERROR("Channel Sounding is not enabled");
distance_measurement_callbacks_->OnDistanceMeasurementStartFail(
cs_remote_address, REASON_INTERNAL_ERROR, METHOD_CS);
diff --git a/system/gd/hci/hci_controller.fbs b/system/gd/hci/hci_controller.fbs
index ce142b6..b554709 100644
--- a/system/gd/hci/hci_controller.fbs
+++ b/system/gd/hci/hci_controller.fbs
@@ -52,7 +52,7 @@
sco_buffer_size : BufferSizeData (privacy:"Any");
iso_buffer_size : BufferSizeData (privacy:"Any");
le_buffer_size : BufferSizeData (privacy:"Any");
- le_connect_list_size : uint64 (privacy:"Any");
+ le_accept_list_size : uint64 (privacy:"Any");
le_resolving_list_size : uint64 (privacy:"Any");
le_maximum_data_length : LeMaximumDataLengthData (privacy:"Any");
le_maximum_advertising_data_length : ushort (privacy:"Any");
diff --git a/system/gd/hci/hci_metrics_logging.cc b/system/gd/hci/hci_metrics_logging.cc
index 8ea24d1..f72ec31 100644
--- a/system/gd/hci/hci_metrics_logging.cc
+++ b/system/gd/hci/hci_metrics_logging.cc
@@ -201,19 +201,19 @@
break;
}
case OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST: {
- auto le_add_device_to_connect_list_view = LeAddDeviceToFilterAcceptListView::Create(
+ auto le_add_device_to_accept_list_view = LeAddDeviceToFilterAcceptListView::Create(
LeConnectionManagementCommandView::Create(std::move(connection_management_command_view)));
- ASSERT(le_add_device_to_connect_list_view.IsValid());
- address = le_add_device_to_connect_list_view.GetAddress();
+ ASSERT(le_add_device_to_accept_list_view.IsValid());
+ address = le_add_device_to_accept_list_view.GetAddress();
direction = android::bluetooth::DIRECTION_INCOMING;
link_type = android::bluetooth::LINK_TYPE_ACL;
break;
}
case OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST: {
- auto le_remove_device_from_connect_list_view = LeRemoveDeviceFromFilterAcceptListView::Create(
+ auto le_remove_device_from_accept_list_view = LeRemoveDeviceFromFilterAcceptListView::Create(
LeConnectionManagementCommandView::Create(std::move(connection_management_command_view)));
- ASSERT(le_remove_device_from_connect_list_view.IsValid());
- address = le_remove_device_from_connect_list_view.GetAddress();
+ ASSERT(le_remove_device_from_accept_list_view.IsValid());
+ address = le_remove_device_from_accept_list_view.GetAddress();
direction = android::bluetooth::DIRECTION_INCOMING;
link_type = android::bluetooth::LINK_TYPE_ACL;
break;
@@ -381,19 +381,19 @@
break;
}
case OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST: {
- auto le_add_device_to_connect_list_view = LeAddDeviceToFilterAcceptListView::Create(
+ auto le_add_device_to_accept_list_view = LeAddDeviceToFilterAcceptListView::Create(
LeConnectionManagementCommandView::Create(std::move(connection_management_command_view)));
- ASSERT(le_add_device_to_connect_list_view.IsValid());
- address = le_add_device_to_connect_list_view.GetAddress();
+ ASSERT(le_add_device_to_accept_list_view.IsValid());
+ address = le_add_device_to_accept_list_view.GetAddress();
direction = android::bluetooth::DIRECTION_INCOMING;
link_type = android::bluetooth::LINK_TYPE_ACL;
break;
}
case OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST: {
- auto le_remove_device_from_connect_list_view = LeRemoveDeviceFromFilterAcceptListView::Create(
+ auto le_remove_device_from_accept_list_view = LeRemoveDeviceFromFilterAcceptListView::Create(
LeConnectionManagementCommandView::Create(std::move(connection_management_command_view)));
- ASSERT(le_remove_device_from_connect_list_view.IsValid());
- address = le_remove_device_from_connect_list_view.GetAddress();
+ ASSERT(le_remove_device_from_accept_list_view.IsValid());
+ address = le_remove_device_from_accept_list_view.GetAddress();
direction = android::bluetooth::DIRECTION_INCOMING;
link_type = android::bluetooth::LINK_TYPE_ACL;
break;
@@ -443,19 +443,19 @@
break;
}
case OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST: {
- auto le_add_device_to_connect_list_view = LeAddDeviceToFilterAcceptListView::Create(
+ auto le_add_device_to_accept_list_view = LeAddDeviceToFilterAcceptListView::Create(
LeConnectionManagementCommandView::Create(std::move(connection_management_command_view)));
- ASSERT(le_add_device_to_connect_list_view.IsValid());
- address = le_add_device_to_connect_list_view.GetAddress();
+ ASSERT(le_add_device_to_accept_list_view.IsValid());
+ address = le_add_device_to_accept_list_view.GetAddress();
direction = android::bluetooth::DIRECTION_INCOMING;
link_type = android::bluetooth::LINK_TYPE_ACL;
break;
}
case OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST: {
- auto le_remove_device_from_connect_list_view = LeRemoveDeviceFromFilterAcceptListView::Create(
+ auto le_remove_device_from_accept_list_view = LeRemoveDeviceFromFilterAcceptListView::Create(
LeConnectionManagementCommandView::Create(std::move(connection_management_command_view)));
- ASSERT(le_remove_device_from_connect_list_view.IsValid());
- address = le_remove_device_from_connect_list_view.GetAddress();
+ ASSERT(le_remove_device_from_accept_list_view.IsValid());
+ address = le_remove_device_from_accept_list_view.GetAddress();
direction = android::bluetooth::DIRECTION_INCOMING;
link_type = android::bluetooth::LINK_TYPE_ACL;
break;
diff --git a/system/gd/hci/le_address_manager.cc b/system/gd/hci/le_address_manager.cc
index 8721adb..6836ac9 100644
--- a/system/gd/hci/le_address_manager.cc
+++ b/system/gd/hci/le_address_manager.cc
@@ -32,12 +32,12 @@
common::Callback<void(std::unique_ptr<CommandBuilder>)> enqueue_command,
os::Handler* handler,
Address public_address,
- uint8_t connect_list_size,
+ uint8_t accept_list_size,
uint8_t resolving_list_size)
: enqueue_command_(enqueue_command),
handler_(handler),
public_address_(public_address),
- connect_list_size_(connect_list_size),
+ accept_list_size_(accept_list_size),
resolving_list_size_(resolving_list_size){};
LeAddressManager::~LeAddressManager() {
@@ -442,7 +442,7 @@
}
uint8_t LeAddressManager::GetFilterAcceptListSize() {
- return connect_list_size_;
+ return accept_list_size_;
}
uint8_t LeAddressManager::GetResolvingListSize() {
@@ -479,9 +479,9 @@
}
void LeAddressManager::AddDeviceToFilterAcceptList(
- FilterAcceptListAddressType connect_list_address_type, bluetooth::hci::Address address) {
- auto packet_builder = hci::LeAddDeviceToFilterAcceptListBuilder::Create(connect_list_address_type, address);
- Command command = {CommandType::ADD_DEVICE_TO_CONNECT_LIST, HCICommand{std::move(packet_builder)}};
+ FilterAcceptListAddressType accept_list_address_type, bluetooth::hci::Address address) {
+ auto packet_builder = hci::LeAddDeviceToFilterAcceptListBuilder::Create(accept_list_address_type, address);
+ Command command = {CommandType::ADD_DEVICE_TO_ACCEPT_LIST, HCICommand{std::move(packet_builder)}};
handler_->BindOnceOn(this, &LeAddressManager::push_command, std::move(command)).Invoke();
}
@@ -524,9 +524,9 @@
}
void LeAddressManager::RemoveDeviceFromFilterAcceptList(
- FilterAcceptListAddressType connect_list_address_type, bluetooth::hci::Address address) {
- auto packet_builder = hci::LeRemoveDeviceFromFilterAcceptListBuilder::Create(connect_list_address_type, address);
- Command command = {CommandType::REMOVE_DEVICE_FROM_CONNECT_LIST, HCICommand{std::move(packet_builder)}};
+ FilterAcceptListAddressType accept_list_address_type, bluetooth::hci::Address address) {
+ auto packet_builder = hci::LeRemoveDeviceFromFilterAcceptListBuilder::Create(accept_list_address_type, address);
+ Command command = {CommandType::REMOVE_DEVICE_FROM_ACCEPT_LIST, HCICommand{std::move(packet_builder)}};
handler_->BindOnceOn(this, &LeAddressManager::push_command, std::move(command)).Invoke();
}
@@ -560,7 +560,7 @@
void LeAddressManager::ClearFilterAcceptList() {
auto packet_builder = hci::LeClearFilterAcceptListBuilder::Create();
- Command command = {CommandType::CLEAR_CONNECT_LIST, HCICommand{std::move(packet_builder)}};
+ Command command = {CommandType::CLEAR_ACCEPT_LIST, HCICommand{std::move(packet_builder)}};
handler_->BindOnceOn(this, &LeAddressManager::push_command, std::move(command)).Invoke();
}
diff --git a/system/gd/hci/le_address_manager.h b/system/gd/hci/le_address_manager.h
index 6f882a6..ae5eef2 100644
--- a/system/gd/hci/le_address_manager.h
+++ b/system/gd/hci/le_address_manager.h
@@ -42,7 +42,7 @@
common::Callback<void(std::unique_ptr<CommandBuilder>)> enqueue_command,
os::Handler* handler,
Address public_address,
- uint8_t connect_list_size,
+ uint8_t accept_list_size,
uint8_t resolving_list_size);
virtual ~LeAddressManager();
@@ -84,13 +84,13 @@
uint8_t GetFilterAcceptListSize();
uint8_t GetResolvingListSize();
- void AddDeviceToFilterAcceptList(FilterAcceptListAddressType connect_list_address_type, Address address);
+ void AddDeviceToFilterAcceptList(FilterAcceptListAddressType accept_list_address_type, Address address);
void AddDeviceToResolvingList(
PeerAddressType peer_identity_address_type,
Address peer_identity_address,
const std::array<uint8_t, 16>& peer_irk,
const std::array<uint8_t, 16>& local_irk);
- void RemoveDeviceFromFilterAcceptList(FilterAcceptListAddressType connect_list_address_type, Address address);
+ void RemoveDeviceFromFilterAcceptList(FilterAcceptListAddressType accept_list_address_type, Address address);
void RemoveDeviceFromResolvingList(PeerAddressType peer_identity_address_type, Address peer_identity_address);
void ClearFilterAcceptList();
void ClearResolvingList();
@@ -117,9 +117,9 @@
enum CommandType {
ROTATE_RANDOM_ADDRESS,
- ADD_DEVICE_TO_CONNECT_LIST,
- REMOVE_DEVICE_FROM_CONNECT_LIST,
- CLEAR_CONNECT_LIST,
+ ADD_DEVICE_TO_ACCEPT_LIST,
+ REMOVE_DEVICE_FROM_ACCEPT_LIST,
+ CLEAR_ACCEPT_LIST,
ADD_DEVICE_TO_RESOLVING_LIST,
REMOVE_DEVICE_FROM_RESOLVING_LIST,
CLEAR_RESOLVING_LIST,
@@ -174,7 +174,7 @@
Address public_address_;
std::unique_ptr<os::Alarm> address_rotation_alarm_;
Octet16 rotation_irk_;
- uint8_t connect_list_size_;
+ uint8_t accept_list_size_;
uint8_t resolving_list_size_;
std::queue<Command> cached_commands_;
bool supports_ble_privacy_{false};
diff --git a/system/gd/hci/le_address_manager_test.cc b/system/gd/hci/le_address_manager_test.cc
index d264a8a..180f919 100644
--- a/system/gd/hci/le_address_manager_test.cc
+++ b/system/gd/hci/le_address_manager_test.cc
@@ -251,7 +251,7 @@
}
};
-TEST_F(LeAddressManagerWithSingleClientTest, add_device_to_connect_list) {
+TEST_F(LeAddressManagerWithSingleClientTest, add_device_to_accept_list) {
Address address;
Address::FromString("01:02:03:04:05:06", address);
le_address_manager_->AddDeviceToFilterAcceptList(FilterAcceptListAddressType::RANDOM, address);
@@ -267,7 +267,7 @@
clients[0].get()->WaitForResume();
}
-TEST_F(LeAddressManagerWithSingleClientTest, remove_device_from_connect_list) {
+TEST_F(LeAddressManagerWithSingleClientTest, remove_device_from_accept_list) {
Address address;
Address::FromString("01:02:03:04:05:06", address);
le_address_manager_->AddDeviceToFilterAcceptList(FilterAcceptListAddressType::RANDOM, address);
diff --git a/system/gd/hci/le_advertising_manager.cc b/system/gd/hci/le_advertising_manager.cc
index 5cbc24a..86a8311 100644
--- a/system/gd/hci/le_advertising_manager.cc
+++ b/system/gd/hci/le_advertising_manager.cc
@@ -223,6 +223,12 @@
return num_instances_;
}
+ size_t GetNumberOfAdvertisingInstancesInUse() const {
+ return std::count_if(advertising_sets_.begin(), advertising_sets_.end(), [](const auto& set) {
+ return set.second.in_use;
+ });
+ }
+
int get_advertiser_reg_id(AdvertiserId advertiser_id) {
return id_map_[advertiser_id];
}
@@ -1487,16 +1493,12 @@
case (AdvertisingApiType::LEGACY): {
le_advertising_interface_->EnqueueCommand(
hci::LeSetAdvertisingEnableBuilder::Create(Enable::ENABLED),
- common::init_flags::
- trigger_advertising_callbacks_on_first_resume_after_pause_is_enabled()
- ? module_handler_->BindOnceOn(
- this,
- &impl::on_set_advertising_enable_complete<
- LeSetAdvertisingEnableCompleteView>,
- true,
- enabled_sets,
- false /* trigger_callbacks */)
- : module_handler_->BindOnce(check_complete<LeSetAdvertisingEnableCompleteView>));
+ module_handler_->BindOnceOn(
+ this,
+ &impl::on_set_advertising_enable_complete<LeSetAdvertisingEnableCompleteView>,
+ true,
+ enabled_sets,
+ false /* trigger_callbacks */));
} break;
case (AdvertisingApiType::ANDROID_HCI): {
for (size_t i = 0; i < enabled_sets_.size(); i++) {
@@ -1504,15 +1506,12 @@
if (id != kInvalidHandle) {
le_advertising_interface_->EnqueueCommand(
hci::LeMultiAdvtSetEnableBuilder::Create(Enable::ENABLED, id),
- common::init_flags::
- trigger_advertising_callbacks_on_first_resume_after_pause_is_enabled()
- ? module_handler_->BindOnceOn(
- this,
- &impl::on_set_advertising_enable_complete<LeMultiAdvtCompleteView>,
- true,
- enabled_sets,
- false /* trigger_callbacks */)
- : module_handler_->BindOnce(check_complete<LeMultiAdvtCompleteView>));
+ module_handler_->BindOnceOn(
+ this,
+ &impl::on_set_advertising_enable_complete<LeMultiAdvtCompleteView>,
+ true,
+ enabled_sets,
+ false /* trigger_callbacks */));
}
}
} break;
@@ -1520,17 +1519,13 @@
if (enabled_sets.size() != 0) {
le_advertising_interface_->EnqueueCommand(
hci::LeSetExtendedAdvertisingEnableBuilder::Create(Enable::ENABLED, enabled_sets),
- common::init_flags::
- trigger_advertising_callbacks_on_first_resume_after_pause_is_enabled()
- ? module_handler_->BindOnceOn(
- this,
- &impl::on_set_extended_advertising_enable_complete<
- LeSetExtendedAdvertisingEnableCompleteView>,
- true,
- enabled_sets,
- false /* trigger_callbacks */)
- : module_handler_->BindOnce(
- check_complete<LeSetExtendedAdvertisingEnableCompleteView>));
+ module_handler_->BindOnceOn(
+ this,
+ &impl::on_set_extended_advertising_enable_complete<
+ LeSetExtendedAdvertisingEnableCompleteView>,
+ true,
+ enabled_sets,
+ false /* trigger_callbacks */));
}
} break;
}
@@ -1852,6 +1847,10 @@
return pimpl_->GetNumberOfAdvertisingInstances();
}
+size_t LeAdvertisingManager::GetNumberOfAdvertisingInstancesInUse() const {
+ return pimpl_->GetNumberOfAdvertisingInstancesInUse();
+}
+
int LeAdvertisingManager::GetAdvertiserRegId(AdvertiserId advertiser_id) {
return pimpl_->get_advertiser_reg_id(advertiser_id);
}
diff --git a/system/gd/hci/le_advertising_manager.h b/system/gd/hci/le_advertising_manager.h
index b4ba824..65d6820 100644
--- a/system/gd/hci/le_advertising_manager.h
+++ b/system/gd/hci/le_advertising_manager.h
@@ -114,6 +114,8 @@
size_t GetNumberOfAdvertisingInstances() const;
+ size_t GetNumberOfAdvertisingInstancesInUse() const;
+
int GetAdvertiserRegId(AdvertiserId advertiser_id);
void ExtendedCreateAdvertiser(
diff --git a/system/gd/hci/le_advertising_manager_test.cc b/system/gd/hci/le_advertising_manager_test.cc
index 2acbaa0..bf2bcbc 100644
--- a/system/gd/hci/le_advertising_manager_test.cc
+++ b/system/gd/hci/le_advertising_manager_test.cc
@@ -103,10 +103,10 @@
common::Callback<void(std::unique_ptr<CommandBuilder>)> enqueue_command,
os::Handler* handler,
Address public_address,
- uint8_t connect_list_size,
+ uint8_t accept_list_size,
uint8_t resolving_list_size)
: LeAddressManager(
- enqueue_command, handler, public_address, connect_list_size, resolving_list_size) {
+ enqueue_command, handler, public_address, accept_list_size, resolving_list_size) {
address_policy_ = AddressPolicy::USE_STATIC_ADDRESS;
minimum_rotation_time_ = 0ms;
maximum_rotation_time_ = 100ms;
@@ -1801,13 +1801,14 @@
test_acl_manager_->SetAddressPolicy(LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS);
// act: start advertising set with RPA
+ AdvertisingConfig config{};
+ config.requested_advertiser_address_type = AdvertiserAddressType::RESOLVABLE_RANDOM;
+ config.channel_map = 1;
+
le_advertising_manager_->ExtendedCreateAdvertiser(
kAdvertiserClientIdJni,
0x00,
- AdvertisingConfig{
- .requested_advertiser_address_type = AdvertiserAddressType::RESOLVABLE_RANDOM,
- .channel_map = 1,
- },
+ config,
scan_callback,
set_terminated_callback,
0,
@@ -1829,13 +1830,14 @@
test_acl_manager_->SetAddressPolicy(LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS);
// start advertising set with NRPA
+ AdvertisingConfig config{};
+ config.requested_advertiser_address_type = AdvertiserAddressType::NONRESOLVABLE_RANDOM;
+ config.channel_map = 1;
+
le_advertising_manager_->ExtendedCreateAdvertiser(
kAdvertiserClientIdJni,
0x00,
- AdvertisingConfig{
- .requested_advertiser_address_type = AdvertiserAddressType::NONRESOLVABLE_RANDOM,
- .channel_map = 1,
- },
+ config,
scan_callback,
set_terminated_callback,
0,
@@ -1866,13 +1868,14 @@
test_acl_manager_->SetAddressPolicy(LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS);
// act: start advertising set with RPA
+ AdvertisingConfig config{};
+ config.requested_advertiser_address_type = AdvertiserAddressType::RESOLVABLE_RANDOM;
+ config.channel_map = 1;
+
le_advertising_manager_->ExtendedCreateAdvertiser(
kAdvertiserClientIdJni,
0x00,
- AdvertisingConfig{
- .requested_advertiser_address_type = AdvertiserAddressType::RESOLVABLE_RANDOM,
- .channel_map = 1,
- },
+ config,
scan_callback,
set_terminated_callback,
0,
@@ -1898,14 +1901,15 @@
test_acl_manager_->SetAddressPolicy(LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS);
// act: start non-connectable advertising set with RPA
+ AdvertisingConfig config{};
+ config.requested_advertiser_address_type = AdvertiserAddressType::RESOLVABLE_RANDOM;
+ config.channel_map = 1;
+ config.connectable = false;
+
le_advertising_manager_->ExtendedCreateAdvertiser(
kAdvertiserClientIdJni,
0x00,
- AdvertisingConfig{
- .requested_advertiser_address_type = AdvertiserAddressType::RESOLVABLE_RANDOM,
- .channel_map = 1,
- .connectable = false,
- },
+ config,
scan_callback,
set_terminated_callback,
0,
@@ -1938,14 +1942,15 @@
test_acl_manager_->SetAddressPolicy(LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS);
// act: start non-connectable advertising set with PUBLIC
+ AdvertisingConfig config{};
+ config.requested_advertiser_address_type = AdvertiserAddressType::PUBLIC;
+ config.channel_map = 1;
+ config.connectable = false;
+
le_advertising_manager_->ExtendedCreateAdvertiser(
kAdvertiserClientIdJni,
0x00,
- AdvertisingConfig{
- .requested_advertiser_address_type = AdvertiserAddressType::PUBLIC,
- .channel_map = 1,
- .connectable = false,
- },
+ config,
scan_callback,
set_terminated_callback,
0,
diff --git a/system/gd/hci/le_periodic_sync_manager.h b/system/gd/hci/le_periodic_sync_manager.h
index 9036597..2c9b06d 100644
--- a/system/gd/hci/le_periodic_sync_manager.h
+++ b/system/gd/hci/le_periodic_sync_manager.h
@@ -15,6 +15,8 @@
*/
#pragma once
+#include <android_bluetooth_flags.h>
+
#include <chrono>
#include <memory>
#include <utility>
@@ -26,6 +28,7 @@
#include "hci/hci_packets.h"
#include "hci/le_scanning_callback.h"
#include "hci/le_scanning_interface.h"
+#include "hci/le_scanning_reassembler.h"
#include "hci/uuid.h"
#include "module.h"
#include "os/alarm.h"
@@ -313,13 +316,23 @@
LOG_ERROR("[PSync]: index not found for handle %u", sync_handle);
return;
}
+
+ auto complete_advertising_data =
+ IS_FLAG_ENABLED(le_periodic_scanning_reassembler)
+ ? scanning_reassembler_.ProcessPeriodicAdvertisingReport(
+ sync_handle, DataStatus(event_view.GetDataStatus()), event_view.GetData())
+ : event_view.GetData();
+ if (!complete_advertising_data.has_value()) {
+ return;
+ }
+
LOG_DEBUG("%s", "[PSync]: invoking callback");
callbacks_->OnPeriodicSyncReport(
sync_handle,
event_view.GetTxPower(),
event_view.GetRssi(),
(uint16_t)event_view.GetDataStatus(),
- event_view.GetData());
+ complete_advertising_data.value());
}
void HandleLePeriodicAdvertisingSyncLost(LePeriodicAdvertisingSyncLostView event_view) {
@@ -532,6 +545,7 @@
std::list<PendingPeriodicSyncRequest> pending_sync_requests_;
std::list<PeriodicSyncStates> periodic_syncs_;
std::list<PeriodicSyncTransferStates> periodic_sync_transfers_;
+ LeScanningReassembler scanning_reassembler_;
bool sync_received_callback_registered_ = false;
int sync_received_callback_id{};
};
diff --git a/system/gd/hci/le_scanning_manager.cc b/system/gd/hci/le_scanning_manager.cc
index 5394276..0e5c2e3 100644
--- a/system/gd/hci/le_scanning_manager.cc
+++ b/system/gd/hci/le_scanning_manager.cc
@@ -457,6 +457,7 @@
// with hardware-filtering features should we ignore waiting for scan response, and make sure
// scan responses are still reported too.
scanning_reassembler_.SetIgnoreScanResponses(
+ le_scan_type_ == LeScanType::PASSIVE ||
filter_policy_ == LeScanningFilterPolicy::FILTER_ACCEPT_LIST_ONLY);
std::optional<LeScanningReassembler::CompleteAdvertisingData> processed_report =
diff --git a/system/gd/hci/le_scanning_manager_test.cc b/system/gd/hci/le_scanning_manager_test.cc
index 1544eab..95dddcc 100644
--- a/system/gd/hci/le_scanning_manager_test.cc
+++ b/system/gd/hci/le_scanning_manager_test.cc
@@ -168,9 +168,9 @@
common::Callback<void(std::unique_ptr<CommandBuilder>)> enqueue_command,
os::Handler* handler,
Address public_address,
- uint8_t connect_list_size,
+ uint8_t accept_list_size,
uint8_t resolving_list_size)
- : LeAddressManager(enqueue_command, handler, public_address, connect_list_size, resolving_list_size) {}
+ : LeAddressManager(enqueue_command, handler, public_address, accept_list_size, resolving_list_size) {}
AddressPolicy Register(LeAddressManagerCallback* callback) override {
client_ = callback;
diff --git a/system/gd/hci/le_scanning_reassembler.cc b/system/gd/hci/le_scanning_reassembler.cc
index 48d55a9..7d825fc 100644
--- a/system/gd/hci/le_scanning_reassembler.cc
+++ b/system/gd/hci/le_scanning_reassembler.cc
@@ -97,6 +97,25 @@
return result;
}
+std::optional<std::vector<uint8_t>> LeScanningReassembler::ProcessPeriodicAdvertisingReport(
+ uint16_t sync_handle, DataStatus data_status, const std::vector<uint8_t>& advertising_data) {
+ // Concatenate the data with existing fragments.
+ std::list<PeriodicAdvertisingFragment>::iterator advertising_fragment =
+ AppendPeriodicFragment(sync_handle, advertising_data);
+
+ // Return and wait for additional fragments if the data is marked as
+ // incomplete.
+ if (data_status == DataStatus::CONTINUING) {
+ return {};
+ }
+
+ // The complete payload has been received; trim the advertising data,
+ // remove the cache entry and return the complete advertising data.
+ std::vector<uint8_t> result = TrimAdvertisingData(advertising_fragment->data);
+ periodic_cache_.erase(advertising_fragment);
+ return result;
+}
+
/// Trim the advertising data by removing empty or overflowing
/// GAP Data entries.
std::vector<uint8_t> LeScanningReassembler::TrimAdvertisingData(
@@ -189,4 +208,34 @@
return cache_.end();
}
+/// Append to the current advertising data of the selected periodic advertiser.
+/// If the advertiser is unknown a new entry is added, optionally by
+/// dropping the oldest advertiser.
+std::list<LeScanningReassembler::PeriodicAdvertisingFragment>::iterator
+LeScanningReassembler::AppendPeriodicFragment(
+ uint16_t sync_handle, const std::vector<uint8_t>& data) {
+ auto it = FindPeriodicFragment(sync_handle);
+ if (it != periodic_cache_.end()) {
+ it->data.insert(it->data.end(), data.cbegin(), data.cend());
+ return it;
+ }
+
+ if (periodic_cache_.size() > kMaximumPeriodicCacheSize) {
+ periodic_cache_.pop_back();
+ }
+
+ periodic_cache_.emplace_front(sync_handle, data);
+ return periodic_cache_.begin();
+}
+
+std::list<LeScanningReassembler::PeriodicAdvertisingFragment>::iterator
+LeScanningReassembler::FindPeriodicFragment(uint16_t sync_handle) {
+ for (auto it = periodic_cache_.begin(); it != periodic_cache_.end(); it++) {
+ if (it->sync_handle == sync_handle) {
+ return it;
+ }
+ }
+ return periodic_cache_.end();
+}
+
} // namespace bluetooth::hci
diff --git a/system/gd/hci/le_scanning_reassembler.h b/system/gd/hci/le_scanning_reassembler.h
index b05d6ca..e5e416e 100644
--- a/system/gd/hci/le_scanning_reassembler.h
+++ b/system/gd/hci/le_scanning_reassembler.h
@@ -58,6 +58,13 @@
uint8_t advertising_sid,
const std::vector<uint8_t>& advertising_data);
+ /// Process an incoming periodic advertising report, extracted from the
+ /// HCI LE Periodic Advertising Report events.
+ /// Returns the completed advertising data if the event was complete,
+ /// or the completion of a fragmented advertising event.
+ std::optional<std::vector<uint8_t>> ProcessPeriodicAdvertisingReport(
+ uint16_t sync_handle, DataStatus status, const std::vector<uint8_t>& advertising_data);
+
/// Configure the scan response filter.
/// If true all scan responses are ignored.
void SetIgnoreScanResponses(bool ignore_scan_responses) {
@@ -105,6 +112,15 @@
: key(key), extended_event_type(extended_event_type), data(data.begin(), data.end()) {}
};
+ /// Packs incomplete periodic advertising data.
+ struct PeriodicAdvertisingFragment {
+ std::optional<uint16_t> sync_handle;
+ std::vector<uint8_t> data;
+
+ PeriodicAdvertisingFragment(uint16_t sync_handle, const std::vector<uint8_t>& data)
+ : sync_handle(sync_handle), data(data.begin(), data.end()) {}
+ };
+
/// Advertising cache for de-fragmenting extended advertising reports,
/// and joining advertising reports with the matching scan response when
/// applicable.
@@ -123,6 +139,15 @@
std::list<AdvertisingFragment>::iterator FindFragment(const AdvertisingKey& key);
+ /// Advertising cache for de-fragmenting periodic advertising reports.
+ static constexpr size_t kMaximumPeriodicCacheSize = 16;
+ std::list<PeriodicAdvertisingFragment> periodic_cache_;
+
+ std::list<PeriodicAdvertisingFragment>::iterator AppendPeriodicFragment(
+ uint16_t sync_handle, const std::vector<uint8_t>& data);
+
+ std::list<PeriodicAdvertisingFragment>::iterator FindPeriodicFragment(uint16_t sync_handle);
+
/// Trim the advertising data by removing empty or overflowing
/// GAP Data entries.
static std::vector<uint8_t> TrimAdvertisingData(const std::vector<uint8_t>& advertising_data);
diff --git a/system/gd/hci/le_scanning_reassembler_test.cc b/system/gd/hci/le_scanning_reassembler_test.cc
index 15382ea..828699f 100644
--- a/system/gd/hci/le_scanning_reassembler_test.cc
+++ b/system/gd/hci/le_scanning_reassembler_test.cc
@@ -42,6 +42,10 @@
// Test addresses.
static const Address kTestAddress = Address({0, 1, 2, 3, 4, 5});
+// Test sync handles.
+static const uint16_t kTestSyncHandle1 = 0x4242;
+static const uint16_t kTestSyncHandle2 = 0x4243;
+
class LeScanningReassemblerTest : public ::testing::Test {
public:
LeScanningReassembler reassembler_;
@@ -383,4 +387,48 @@
std::vector<uint8_t>({0x2, 0x3, 0x3}));
}
+TEST_F(LeScanningReassemblerTest, periodic_advertising) {
+ // Test periodic advertising.
+ ASSERT_FALSE(
+ reassembler_
+ .ProcessPeriodicAdvertisingReport(kTestSyncHandle1, DataStatus::CONTINUING, {0x1, 0x2})
+ .has_value());
+
+ auto processed_report = reassembler_.ProcessPeriodicAdvertisingReport(
+ kTestSyncHandle1, DataStatus::COMPLETE, {0x3, 0x4, 0x5, 0x6});
+ ASSERT_TRUE(processed_report.has_value());
+ ASSERT_EQ(processed_report.value(), std::vector<uint8_t>({0x1, 0x2, 0x3, 0x4, 0x5, 0x6}));
+
+ // Test periodic advertising with the same handle
+ // to validate that the context was cleared.
+ processed_report = reassembler_.ProcessPeriodicAdvertisingReport(
+ kTestSyncHandle1, DataStatus::COMPLETE, {0x4, 0xa0, 0xb0, 0xc0, 0xd0});
+ ASSERT_TRUE(processed_report.has_value());
+ ASSERT_EQ(processed_report.value(), std::vector<uint8_t>({0x4, 0xa0, 0xb0, 0xc0, 0xd0}));
+}
+
+TEST_F(LeScanningReassemblerTest, interleaved_periodic_advertising) {
+ // The reassembler must disambiguate advertising events by address,
+ // address type, and SID.
+ ASSERT_FALSE(
+ reassembler_
+ .ProcessPeriodicAdvertisingReport(kTestSyncHandle1, DataStatus::CONTINUING, {0x2, 0x0})
+ .has_value());
+
+ ASSERT_FALSE(
+ reassembler_
+ .ProcessPeriodicAdvertisingReport(kTestSyncHandle2, DataStatus::CONTINUING, {0x2, 0x1})
+ .has_value());
+
+ ASSERT_EQ(
+ reassembler_.ProcessPeriodicAdvertisingReport(kTestSyncHandle1, DataStatus::COMPLETE, {0x0})
+ .value(),
+ std::vector<uint8_t>({0x2, 0x0, 0x0}));
+
+ ASSERT_EQ(
+ reassembler_.ProcessPeriodicAdvertisingReport(kTestSyncHandle2, DataStatus::COMPLETE, {0x1})
+ .value(),
+ std::vector<uint8_t>({0x2, 0x1, 0x1}));
+}
+
} // namespace bluetooth::hci
diff --git a/system/gd/rust/common/src/init_flags.rs b/system/gd/rust/common/src/init_flags.rs
index 6a41c0f..6a07cfe 100644
--- a/system/gd/rust/common/src/init_flags.rs
+++ b/system/gd/rust/common/src/init_flags.rs
@@ -389,7 +389,6 @@
bluetooth_quality_report_callback = true,
set_min_encryption = true,
subrating = true,
- trigger_advertising_callbacks_on_first_resume_after_pause = true,
use_unified_connection_manager,
sdp_return_classic_services_when_le_discovery_fails = true,
use_rsi_from_cached_inqiry_results = false,
diff --git a/system/gd/rust/linux/client/src/bt_gatt.rs b/system/gd/rust/linux/client/src/bt_gatt.rs
index f902163..a8ac8df 100644
--- a/system/gd/rust/linux/client/src/bt_gatt.rs
+++ b/system/gd/rust/linux/client/src/bt_gatt.rs
@@ -50,3 +50,17 @@
self.auth_req
}
}
+
+/// User preference of GATT server operations
+pub(crate) struct GattServerContext {
+ /// Is connection going to be directed?
+ pub(crate) is_connect_direct: bool,
+ /// Transport of connection
+ pub(crate) connect_transport: BtTransport,
+}
+
+impl GattServerContext {
+ pub(crate) fn new() -> Self {
+ GattServerContext { is_connect_direct: false, connect_transport: BtTransport::Le }
+ }
+}
diff --git a/system/gd/rust/linux/client/src/command_handler.rs b/system/gd/rust/linux/client/src/command_handler.rs
index c2ff72d..daa0448 100644
--- a/system/gd/rust/linux/client/src/command_handler.rs
+++ b/system/gd/rust/linux/client/src/command_handler.rs
@@ -9,13 +9,15 @@
use crate::callbacks::{BtGattCallback, BtGattServerCallback};
use crate::ClientContext;
use crate::{console_red, console_yellow, print_error, print_info};
-use bt_topshim::btif::{BtConnectionState, BtDiscMode, BtStatus, BtTransport, INVALID_RSSI};
+use bt_topshim::btif::{BtConnectionState, BtDiscMode, BtStatus, BtTransport, Uuid, INVALID_RSSI};
use bt_topshim::profiles::hid_host::BthhReportType;
use bt_topshim::profiles::sdp::{BtSdpMpsRecord, BtSdpRecord};
use bt_topshim::profiles::{gatt::LePhy, ProfileConnectionState};
use btstack::battery_manager::IBatteryManager;
use btstack::bluetooth::{BluetoothDevice, IBluetooth};
-use btstack::bluetooth_gatt::{GattWriteType, IBluetoothGatt};
+use btstack::bluetooth_gatt::{
+ BluetoothGattService, GattDbElementType, GattWriteType, IBluetoothGatt,
+};
use btstack::bluetooth_media::{IBluetoothMedia, IBluetoothTelephony};
use btstack::bluetooth_qa::IBluetoothQA;
use btstack::socket_manager::{IBluetoothSocketManager, SocketResult};
@@ -28,6 +30,7 @@
const MAX_MENU_CHAR_WIDTH: usize = 72;
const GATT_CLIENT_APP_UUID: &str = "12345678123456781234567812345678";
const GATT_SERVER_APP_UUID: &str = "12345678123456781234567812345679";
+const HEART_RATE_SERVICE_UUID: &str = "0000180D-0000-1000-8000-00805F9B34FB";
enum CommandError {
// Command not handled due to invalid arguments.
@@ -221,6 +224,13 @@
),
String::from("gatt register-notification <address> <handle> <enable|disable>"),
String::from("gatt register-server"),
+ String::from("gatt server-connect <server_id> <client_address>"),
+ String::from("gatt server-disconnect <server_id> <client_address>"),
+ String::from("gatt server-add-heartrate-service <server_id>"),
+ String::from("gatt server-remove-service <server_id> <service_handle>"),
+ String::from("gatt server-clear-all-services <server_id>"),
+ String::from("gatt server-set-direct-connect <true|false>"),
+ String::from("gatt server-set-connect-transport <Bredr|LE|Auto>"),
],
description: String::from("GATT tools"),
function_pointer: CommandHandler::cmd_gatt,
@@ -1315,6 +1325,91 @@
false,
);
}
+ "server-connect" => {
+ let server_id = String::from(get_arg(args, 1)?)
+ .parse::<i32>()
+ .or(Err("Failed to parse server_id"))?;
+ let client_addr = String::from(get_arg(args, 2)?);
+ let is_direct = self.lock_context().gatt_server_context.is_connect_direct;
+ let transport = self.lock_context().gatt_server_context.connect_transport;
+
+ if !self.lock_context().gatt_dbus.as_mut().unwrap().server_connect(
+ server_id,
+ client_addr.clone(),
+ is_direct,
+ transport,
+ ) {
+ return Err("Connection was unsuccessful".into());
+ }
+ }
+ "server-disconnect" => {
+ let server_id = String::from(get_arg(args, 1)?)
+ .parse::<i32>()
+ .or(Err("Failed to parse server_id"))?;
+ let client_addr = String::from(get_arg(args, 2)?);
+
+ if !self
+ .lock_context()
+ .gatt_dbus
+ .as_mut()
+ .unwrap()
+ .server_disconnect(server_id, client_addr.clone())
+ {
+ return Err("Disconnection was unsuccessful".into());
+ }
+ }
+ "server-add-heartrate-service" => {
+ let uuid = Uuid::from(UuidHelper::from_string(HEART_RATE_SERVICE_UUID).unwrap());
+
+ let server_id = String::from(get_arg(args, 1)?)
+ .parse::<i32>()
+ .or(Err("Failed to parse server_id"))?;
+ let service = BluetoothGattService::new(
+ uuid.into(),
+ 0, // libbluetooth assigns this handle once the service is added
+ GattDbElementType::PrimaryService.into(),
+ );
+
+ self.lock_context().gatt_dbus.as_mut().unwrap().add_service(server_id, service);
+ }
+ "server-remove-service" => {
+ let server_id = String::from(get_arg(args, 1)?)
+ .parse::<i32>()
+ .or(Err("Failed to parse server_id"))?;
+ let service_handle = String::from(get_arg(args, 1)?)
+ .parse::<i32>()
+ .or(Err("Failed to parse service handle"))?;
+
+ self.lock_context()
+ .gatt_dbus
+ .as_mut()
+ .unwrap()
+ .remove_service(server_id, service_handle);
+ }
+ "server-clear-all-services" => {
+ let server_id = String::from(get_arg(args, 1)?)
+ .parse::<i32>()
+ .or(Err("Failed to parse server_id"))?;
+ self.lock_context().gatt_dbus.as_mut().unwrap().clear_services(server_id);
+ }
+ "server-set-direct-connect" => {
+ let is_direct = String::from(get_arg(args, 1)?)
+ .parse::<bool>()
+ .or(Err("Failed to parse is_direct"))?;
+
+ self.lock_context().gatt_server_context.is_connect_direct = is_direct;
+ }
+ "server-set-connect-transport" => {
+ let transport = match &get_arg(args, 1)?[..] {
+ "Bredr" => BtTransport::Bredr,
+ "LE" => BtTransport::Le,
+ "Auto" => BtTransport::Auto,
+ _ => {
+ return Err("Failed to parse transport".into());
+ }
+ };
+ self.lock_context().gatt_server_context.connect_transport = transport;
+ }
_ => return Err(CommandError::InvalidArgs),
}
Ok(())
diff --git a/system/gd/rust/linux/client/src/dbus_iface.rs b/system/gd/rust/linux/client/src/dbus_iface.rs
index 96ee587..dabeb6d 100644
--- a/system/gd/rust/linux/client/src/dbus_iface.rs
+++ b/system/gd/rust/linux/client/src/dbus_iface.rs
@@ -22,7 +22,7 @@
use btstack::battery_manager::{Battery, BatterySet, IBatteryManager, IBatteryManagerCallback};
use btstack::bluetooth::{
- BluetoothDevice, IBluetooth, IBluetoothCallback, IBluetoothConnectionCallback,
+ BluetoothDevice, BtAdapterRole, IBluetooth, IBluetoothCallback, IBluetoothConnectionCallback,
IBluetoothQALegacy,
};
use btstack::bluetooth_admin::{IBluetoothAdmin, IBluetoothAdminPolicyCallback, PolicyEffect};
@@ -96,6 +96,7 @@
impl_dbus_arg_enum!(SuspendType);
impl_dbus_arg_from_into!(Uuid, Vec<u8>);
impl_dbus_arg_enum!(BthhReportType);
+impl_dbus_arg_enum!(BtAdapterRole);
impl RefArgToRust for Uuid {
type RustType = Vec<u8>;
@@ -995,6 +996,11 @@
fn is_swb_supported(&self) -> bool {
dbus_generated!()
}
+
+ #[dbus_method("GetSupportedRoles")]
+ fn get_supported_roles(&self) -> Vec<BtAdapterRole> {
+ dbus_generated!()
+ }
}
pub(crate) struct BluetoothQALegacyDBus {
diff --git a/system/gd/rust/linux/client/src/main.rs b/system/gd/rust/linux/client/src/main.rs
index c1847ca..eafaa8a 100644
--- a/system/gd/rust/linux/client/src/main.rs
+++ b/system/gd/rust/linux/client/src/main.rs
@@ -12,7 +12,7 @@
use tokio::time::{sleep, timeout};
use crate::bt_adv::AdvSet;
-use crate::bt_gatt::GattClientContext;
+use crate::bt_gatt::{GattClientContext, GattServerContext};
use crate::callbacks::{
AdminCallback, AdvertisingSetCallback, BatteryManagerCallback, BtCallback,
BtConnectionCallback, BtManagerCallback, BtSocketManagerCallback, MediaCallback, QACallback,
@@ -141,6 +141,9 @@
/// Data of GATT client preference.
gatt_client_context: GattClientContext,
+ /// Data of GATT server preference.
+ gatt_server_context: GattServerContext,
+
/// The schedule when a socket is connected.
socket_test_schedule: Option<SocketSchedule>,
@@ -199,6 +202,7 @@
qa_callback_id: None,
is_restricted,
gatt_client_context: GattClientContext::new(),
+ gatt_server_context: GattServerContext::new(),
socket_test_schedule: None,
mps_sdp_handle: None,
client_commands_with_callbacks,
diff --git a/system/gd/rust/linux/service/src/iface_bluetooth.rs b/system/gd/rust/linux/service/src/iface_bluetooth.rs
index 6ed6ae9..c84e076 100644
--- a/system/gd/rust/linux/service/src/iface_bluetooth.rs
+++ b/system/gd/rust/linux/service/src/iface_bluetooth.rs
@@ -14,8 +14,8 @@
};
use btstack::bluetooth::{
- Bluetooth, BluetoothDevice, IBluetooth, IBluetoothCallback, IBluetoothConnectionCallback,
- IBluetoothQALegacy,
+ Bluetooth, BluetoothDevice, BtAdapterRole, IBluetooth, IBluetoothCallback,
+ IBluetoothConnectionCallback, IBluetoothQALegacy,
};
use btstack::socket_manager::{
BluetoothServerSocket, BluetoothSocket, BluetoothSocketManager, CallbackId,
@@ -162,6 +162,7 @@
impl_dbus_arg_enum!(BtSspVariant);
impl_dbus_arg_enum!(BtTransport);
impl_dbus_arg_enum!(ProfileConnectionState);
+impl_dbus_arg_enum!(BtAdapterRole);
#[allow(dead_code)]
struct BluetoothConnectionCallbackDBus {}
@@ -706,6 +707,11 @@
fn is_swb_supported(&self) -> bool {
dbus_generated!()
}
+
+ #[dbus_method("GetSupportedRoles", DBusLog::Disable)]
+ fn get_supported_roles(&self) -> Vec<BtAdapterRole> {
+ dbus_generated!()
+ }
}
impl_dbus_arg_enum!(SocketType);
diff --git a/system/gd/rust/linux/stack/src/bluetooth.rs b/system/gd/rust/linux/stack/src/bluetooth.rs
index c48710b..2a655c4 100644
--- a/system/gd/rust/linux/stack/src/bluetooth.rs
+++ b/system/gd/rust/linux/stack/src/bluetooth.rs
@@ -8,7 +8,7 @@
ToggleableProfile, Uuid, Uuid128Bit, INVALID_RSSI,
};
use bt_topshim::{
- metrics,
+ controller, metrics,
profiles::gatt::GattStatus,
profiles::hid_host::{
BthhConnectionState, BthhHidInfo, BthhProtocolMode, BthhReportType, BthhStatus,
@@ -25,6 +25,7 @@
use btif_macros::{btif_callback, btif_callbacks_dispatcher};
use log::{debug, warn};
+use num_derive::{FromPrimitive, ToPrimitive};
use num_traits::cast::ToPrimitive;
use num_traits::pow;
use std::collections::{HashMap, HashSet};
@@ -66,6 +67,14 @@
const PID_DIR: &str = "/var/run/bluetooth";
+/// Represents various roles the adapter supports.
+#[derive(Debug, FromPrimitive, ToPrimitive)]
+#[repr(u32)]
+pub enum BtAdapterRole {
+ Central = 0,
+ Peripheral,
+ CentralPeripheral,
+}
/// Defines the adapter API.
pub trait IBluetooth {
/// Adds a callback from a client who wishes to observe adapter events.
@@ -239,6 +248,9 @@
/// Returns whether SWB is supported.
fn is_swb_supported(&self) -> bool;
+
+ /// Returns a list of all the roles that are supported.
+ fn get_supported_roles(&self) -> Vec<BtAdapterRole>;
}
/// Adapter API for Bluetooth qualification and verification.
@@ -522,6 +534,7 @@
discoverable_timeout: Option<JoinHandle<()>>,
cancelling_devices: HashSet<RawAddress>,
active_pairing_address: Option<RawAddress>,
+ le_supported_states: u64,
/// Used to notify signal handler that we have turned off the stack.
sig_notifier: Arc<SigData>,
@@ -579,6 +592,7 @@
discoverable_timeout: None,
cancelling_devices: HashSet::new(),
active_pairing_address: None,
+ le_supported_states: 0u64,
sig_notifier,
uhid_wakeup_source: UHid::new(),
}
@@ -1312,6 +1326,7 @@
// Also need to manually request some properties
self.intf.lock().unwrap().get_adapter_property(BtPropertyType::ClassOfDevice);
+ self.le_supported_states = controller::Controller::new().get_ble_supported_states();
// Initialize the BLE scanner for discovery.
let callback_id = self.bluetooth_gatt.lock().unwrap().register_scanner_callback(
@@ -2765,6 +2780,23 @@
fn is_swb_supported(&self) -> bool {
self.intf.lock().unwrap().get_swb_supported()
}
+
+ fn get_supported_roles(&self) -> Vec<BtAdapterRole> {
+ let mut roles: Vec<BtAdapterRole> = vec![];
+
+ // See Core 5.3, Vol 4, Part E, 7.8.27 for detailed state information
+ if self.le_supported_states >> 35 & 1 == 1u64 {
+ roles.push(BtAdapterRole::Central);
+ }
+ if self.le_supported_states >> 38 & 1 == 1u64 {
+ roles.push(BtAdapterRole::Peripheral);
+ }
+ if self.le_supported_states >> 28 & 1 == 1u64 {
+ roles.push(BtAdapterRole::CentralPeripheral);
+ }
+
+ roles
+ }
}
impl BtifSdpCallbacks for Bluetooth {
diff --git a/system/gd/rust/linux/stack/src/bluetooth_gatt.rs b/system/gd/rust/linux/stack/src/bluetooth_gatt.rs
index c5d59d0..c296423 100644
--- a/system/gd/rust/linux/stack/src/bluetooth_gatt.rs
+++ b/system/gd/rust/linux/stack/src/bluetooth_gatt.rs
@@ -782,11 +782,7 @@
}
impl BluetoothGattService {
- pub(crate) fn new(
- uuid: Uuid128Bit,
- instance_id: i32,
- service_type: i32,
- ) -> BluetoothGattService {
+ pub fn new(uuid: Uuid128Bit, instance_id: i32, service_type: i32) -> BluetoothGattService {
BluetoothGattService {
uuid,
instance_id,
@@ -1133,7 +1129,7 @@
#[derive(Debug, FromPrimitive, ToPrimitive)]
#[repr(u8)]
/// GATT write type.
-pub(crate) enum GattDbElementType {
+pub enum GattDbElementType {
PrimaryService = 0,
SecondaryService = 1,
IncludedService = 2,
@@ -1163,7 +1159,7 @@
}
}
-#[derive(Debug, FromPrimitive, ToPrimitive, Clone)]
+#[derive(Debug, FromPrimitive, ToPrimitive, Clone, PartialEq)]
#[repr(u32)]
/// Scan type configuration.
pub enum ScanType {
@@ -1173,7 +1169,7 @@
impl Default for ScanType {
fn default() -> Self {
- ScanType::Active
+ ScanType::Passive
}
}
@@ -1189,20 +1185,26 @@
}
impl ScanSettings {
- fn extract_scan_parameters(self) -> Option<(u16, u16)> {
- let interval = u16::try_from(self.interval);
- if interval.is_err() {
- println!("Invalid scan interval {}", self.interval);
- return None;
- }
-
- let window = u16::try_from(self.window);
- if window.is_err() {
- println!("Invalid scan window {}", self.window);
- return None;
- }
-
- return Some((interval.unwrap(), window.unwrap()));
+ fn extract_scan_parameters(&self) -> Option<(u8, u16, u16)> {
+ let scan_type = match self.scan_type {
+ ScanType::Passive => 0x00,
+ ScanType::Active => 0x01,
+ };
+ let interval = match u16::try_from(self.interval) {
+ Ok(i) => i,
+ Err(e) => {
+ println!("Invalid scan interval {}: {}", self.interval, e);
+ return None;
+ }
+ };
+ let window = match u16::try_from(self.window) {
+ Ok(w) => w,
+ Err(e) => {
+ println!("Invalid scan window {}: {}", self.window, e);
+ return None;
+ }
+ };
+ return Some((scan_type, interval, window));
}
}
@@ -1344,31 +1346,52 @@
.await
}
- /// Updates the topshim's scan state depending on the states of registered scanners. Scan is
- /// enabled if there is at least 1 active registered scanner.
+ /// Updates the scan state depending on the states of registered scanners:
+ /// 1. Scan is started if there is at least 1 enabled scanner.
+ /// 2. Always toggle the scan off and on so that we reset the scan parameters based on whether
+ /// we have enabled scanners using hardware filtering.
+ /// TODO(b/266752123): We can do more bookkeeping to optimize when we really need to
+ /// toggle. Also improve toggling API into 1 operation that guarantees correct ordering.
+ /// 3. If there is an enabled ScanType::Active scanner, prefer its scan settings. Otherwise,
+ /// adopt the settings from any of the enabled scanners. We shouldn't just use the settings
+ /// from |scanner_id| because it may refer to a disabled scan.
///
/// Note: this does not need to be async, but declared as async for consistency in this struct.
/// May be converted into real async in the future if btif supports it.
- async fn update_scan(&mut self, scanner_id: u8, scan_settings: Option<ScanSettings>) {
- if self.scanners.lock().unwrap().values().find(|scanner| scanner.is_active).is_some() {
- // Toggle the scan off and on so that we reset the scan parameters based on whether
- // we have active scanners using hardware filtering.
- // TODO(b/266752123): We can do more bookkeeping to optimize when we really need to
- // toggle. Also improve toggling API into 1 operation that guarantees correct ordering.
- self.gatt.as_ref().unwrap().lock().unwrap().scanner.stop_scan();
- if let Some(settings) = scan_settings {
- if let Some((scan_interval, scan_window)) = settings.extract_scan_parameters() {
- self.gatt.as_ref().unwrap().lock().unwrap().scanner.set_scan_parameters(
- scanner_id,
- scan_interval,
- scan_window,
- );
+ async fn update_scan(&mut self, scanner_id: u8) {
+ let mut has_enabled_scan = false;
+ let mut enabled_scan_param = None;
+ let mut enabled_active_scan_param = None;
+ for scanner in self.scanners.lock().unwrap().values() {
+ if !scanner.is_enabled {
+ continue;
+ }
+ has_enabled_scan = true;
+ if let Some(ss) = &scanner.scan_settings {
+ enabled_scan_param = ss.extract_scan_parameters();
+ if ss.scan_type == ScanType::Active {
+ enabled_active_scan_param = ss.extract_scan_parameters();
+ break;
}
}
- self.gatt.as_ref().unwrap().lock().unwrap().scanner.start_scan();
- } else {
- self.gatt.as_ref().unwrap().lock().unwrap().scanner.stop_scan();
}
+
+ self.gatt.as_ref().unwrap().lock().unwrap().scanner.stop_scan();
+ if !has_enabled_scan {
+ return;
+ }
+
+ if let Some((scan_type, scan_interval, scan_window)) =
+ enabled_active_scan_param.or(enabled_scan_param)
+ {
+ self.gatt.as_ref().unwrap().lock().unwrap().scanner.set_scan_parameters(
+ scanner_id,
+ scan_type,
+ scan_interval,
+ scan_window,
+ );
+ }
+ self.gatt.as_ref().unwrap().lock().unwrap().scanner.start_scan();
}
}
@@ -1593,7 +1616,7 @@
.unwrap()
.iter()
.filter_map(|(_uuid, scanner)| {
- if let (true, Some(scanner_id)) = (scanner.is_active, scanner.scanner_id) {
+ if let (true, Some(scanner_id)) = (scanner.is_enabled, scanner.scanner_id) {
Some(scanner_id)
} else {
None
@@ -1663,7 +1686,7 @@
if let Some(scanner) = Self::find_scanner_by_id(&mut scanners_lock, scanner_id) {
if scanner.is_suspended {
scanner.is_suspended = false;
- scanner.is_active = true;
+ scanner.is_enabled = true;
// When a scanner resumes from a suspended state, the
// scanner.filter has already had the filter data.
scanner.filter.clone()
@@ -1723,14 +1746,14 @@
log::debug!("Added adv monitor handle = {}", monitor_handle);
}
- let has_active_unfiltered_scanner = scanners
+ let has_enabled_unfiltered_scanner = scanners
.lock()
.unwrap()
.iter()
- .any(|(_uuid, scanner)| scanner.is_active && scanner.filter.is_none());
+ .any(|(_uuid, scanner)| scanner.is_enabled && scanner.filter.is_none());
if !gatt_async
- .msft_adv_monitor_enable(!has_active_unfiltered_scanner)
+ .msft_adv_monitor_enable(!has_enabled_unfiltered_scanner)
.await
.map_or(false, |status| status == 0)
{
@@ -1742,10 +1765,7 @@
}
}
- let scan_settings = Self::find_scanner_by_id(&mut scanners.lock().unwrap(), scanner_id)
- .map_or(None, |s| s.scan_settings.clone());
-
- gatt_async.update_scan(scanner_id, scan_settings).await;
+ gatt_async.update_scan(scanner_id).await;
});
BtStatus::Success
@@ -1909,8 +1929,8 @@
callback_id: u32,
// If the scanner is registered successfully, this contains the scanner id, otherwise None.
scanner_id: Option<u8>,
- // If one of scanners is active, we scan.
- is_active: bool,
+ // If one of scanners is enabled, we scan.
+ is_enabled: bool,
// Scan filter.
filter: Option<ScanFilter>,
// Adv monitor handle, if exists.
@@ -1926,7 +1946,7 @@
Self {
callback_id,
scanner_id: None,
- is_active: false,
+ is_enabled: false,
filter: None,
monitor_handle: None,
is_suspended: false,
@@ -2033,7 +2053,7 @@
let settings = settings.unwrap_or_else(|| ScanSettings {
interval: sysprop::get_i32(sysprop::PropertyI32::LeInquiryScanInterval),
window: sysprop::get_i32(sysprop::PropertyI32::LeInquiryScanWindow),
- scan_type: ScanType::Active,
+ scan_type: ScanType::default(),
});
// Multiplexing scanners happens at this layer. The implementations of start_scan
@@ -2043,7 +2063,7 @@
let mut scanners_lock = self.scanners.lock().unwrap();
if let Some(scanner) = Self::find_scanner_by_id(&mut scanners_lock, scanner_id) {
- scanner.is_active = true;
+ scanner.is_enabled = true;
scanner.filter = filter.clone();
scanner.scan_settings = Some(settings);
} else {
@@ -2070,7 +2090,7 @@
let mut scanners_lock = self.scanners.lock().unwrap();
if let Some(scanner) = Self::find_scanner_by_id(&mut scanners_lock, scanner_id) {
- scanner.is_active = false;
+ scanner.is_enabled = false;
scanner.monitor_handle
} else {
log::warn!("Scanner {} not found", scanner_id);
@@ -2095,14 +2115,14 @@
let _res = gatt_async.msft_adv_monitor_remove(handle).await;
}
- let has_active_unfiltered_scanner = scanners
+ let has_enabled_unfiltered_scanner = scanners
.lock()
.unwrap()
.iter()
- .any(|(_uuid, scanner)| scanner.is_active && scanner.filter.is_none());
+ .any(|(_uuid, scanner)| scanner.is_enabled && scanner.filter.is_none());
if !gatt_async
- .msft_adv_monitor_enable(!has_active_unfiltered_scanner)
+ .msft_adv_monitor_enable(!has_enabled_unfiltered_scanner)
.await
.map_or(false, |status| status == 0)
{
@@ -2110,10 +2130,7 @@
}
}
- let scan_settings = Self::find_scanner_by_id(&mut scanners.lock().unwrap(), scanner_id)
- .map_or(None, |s| s.scan_settings.clone());
-
- gatt_async.update_scan(scanner_id, scan_settings).await;
+ gatt_async.update_scan(scanner_id).await;
});
BtStatus::Success
diff --git a/system/gd/rust/shim/src/init_flags.rs b/system/gd/rust/shim/src/init_flags.rs
index d2275cf..b7cec37 100644
--- a/system/gd/rust/shim/src/init_flags.rs
+++ b/system/gd/rust/shim/src/init_flags.rs
@@ -45,7 +45,6 @@
fn bluetooth_quality_report_callback_is_enabled() -> bool;
fn set_min_encryption_is_enabled() -> bool;
fn subrating_is_enabled() -> bool;
- fn trigger_advertising_callbacks_on_first_resume_after_pause_is_enabled() -> bool;
fn use_unified_connection_manager_is_enabled() -> bool;
fn sdp_return_classic_services_when_le_discovery_fails_is_enabled() -> bool;
fn use_rsi_from_cached_inqiry_results_is_enabled() -> bool;
diff --git a/system/gd/rust/topshim/BUILD.gn b/system/gd/rust/topshim/BUILD.gn
index cde636e..f9c5aea 100644
--- a/system/gd/rust/topshim/BUILD.gn
+++ b/system/gd/rust/topshim/BUILD.gn
@@ -48,7 +48,10 @@
":btif_bridge_header",
"//bt/system/pdl:BluetoothGeneratedPackets_h",
]
- configs = [ "//bt/system/gd:gd_defaults" ]
+ configs = [
+ "//bt/system/gd:gd_defaults",
+ "//bt/system/log:log_defaults",
+ ]
}
source_set("btif_cxx_bridge_code") {
@@ -69,7 +72,10 @@
"//bt/system/gd/metrics:BluetoothMetricsSources",
"//bt/system/pdl:BluetoothGeneratedPackets_h",
]
- configs += [ "//bt/system/gd:gd_defaults" ]
+ configs += [
+ "//bt/system/gd:gd_defaults",
+ "//bt/system/log:log_defaults",
+ ]
}
cxxbridge_libheader("cxxlibheader") {
diff --git a/system/gd/rust/topshim/build.rs b/system/gd/rust/topshim/build.rs
index c7cacdf..ad646e0 100644
--- a/system/gd/rust/topshim/build.rs
+++ b/system/gd/rust/topshim/build.rs
@@ -21,6 +21,7 @@
"/system/btcore",
"/system/include",
"/system/include/hardware",
+ "/system/log/include",
"/system/types",
];
diff --git a/system/gd/rust/topshim/controller/controller_shim.cc b/system/gd/rust/topshim/controller/controller_shim.cc
index a9594c3..3ee9086 100644
--- a/system/gd/rust/topshim/controller/controller_shim.cc
+++ b/system/gd/rust/topshim/controller/controller_shim.cc
@@ -43,6 +43,13 @@
return *controller_->get_address();
}
+uint64_t ControllerIntf::get_ble_supported_states() const {
+ if (!controller_) std::abort();
+ uint64_t states;
+ memcpy(&states, controller_->get_ble_supported_states(), sizeof(uint64_t));
+ return states;
+}
+
} // namespace rust
} // namespace topshim
} // namespace bluetooth
diff --git a/system/gd/rust/topshim/controller/controller_shim.h b/system/gd/rust/topshim/controller/controller_shim.h
index 35fcf24..275824a 100644
--- a/system/gd/rust/topshim/controller/controller_shim.h
+++ b/system/gd/rust/topshim/controller/controller_shim.h
@@ -32,6 +32,7 @@
~ControllerIntf();
RawAddress read_local_addr() const;
+ uint64_t get_ble_supported_states() const;
private:
const controller_t* controller_;
diff --git a/system/gd/rust/topshim/facade/Android.bp b/system/gd/rust/topshim/facade/Android.bp
index 3e197f0..656de8a 100644
--- a/system/gd/rust/topshim/facade/Android.bp
+++ b/system/gd/rust/topshim/facade/Android.bp
@@ -71,6 +71,7 @@
"libbtif-core",
"libc++fs",
"libchrome",
+ "libcom.android.sysprop.bluetooth.wrapped",
"libevent",
"libflatbuffers-cpp",
"libg722codec",
@@ -80,6 +81,7 @@
"libudrv-uipc",
],
shared_libs: [
+ "libPlatformProperties",
"libcrypto",
"libcutils",
"libgrpc++",
diff --git a/system/gd/rust/topshim/facade/src/gatt_service.rs b/system/gd/rust/topshim/facade/src/gatt_service.rs
index 081fb98..73a5bc2 100644
--- a/system/gd/rust/topshim/facade/src/gatt_service.rs
+++ b/system/gd/rust/topshim/facade/src/gatt_service.rs
@@ -364,7 +364,7 @@
fn set_scan_parameters(&mut self, ctx: RpcContext<'_>, _req: Empty, sink: UnarySink<Empty>) {
let scanner = &mut self.gatt.lock().unwrap().scanner;
- scanner.set_scan_parameters(0, 0, 0);
+ scanner.set_scan_parameters(0, 0, 0, 0);
ctx.spawn(async move {
sink.success(Empty::default()).await.unwrap();
})
diff --git a/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.cc b/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.cc
index 72b9bfc..e8f5019 100644
--- a/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.cc
+++ b/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.cc
@@ -272,9 +272,11 @@
enable, base::Bind(&BleScannerIntf::OnMsftAdvMonitorEnableCallback, base::Unretained(this), call_id));
}
-void BleScannerIntf::SetScanParameters(uint8_t scanner_id, uint16_t scan_interval, uint16_t scan_window) {
+void BleScannerIntf::SetScanParameters(
+ uint8_t scanner_id, uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window) {
scanner_intf_->SetScanParameters(
scanner_id,
+ scan_type,
scan_interval,
scan_window,
base::Bind(&BleScannerIntf::OnStatusCallback, base::Unretained(this), scanner_id));
diff --git a/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.h b/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.h
index 7011ae3..75bb38f 100644
--- a/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.h
+++ b/system/gd/rust/topshim/gatt/gatt_ble_scanner_shim.h
@@ -117,7 +117,8 @@
// Sets the LE scan interval and window in units of N * 0.625 msec. The result
// of this action is returned via |OnStatusCallback|.
- void SetScanParameters(uint8_t scanner_id, uint16_t scan_interval, uint16_t scan_window);
+ void SetScanParameters(
+ uint8_t scanner_id, uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window);
// Configure the batchscan storage and get a response via |OnStatusCallback|.
void BatchscanConfigStorage(
diff --git a/system/gd/rust/topshim/src/controller.rs b/system/gd/rust/topshim/src/controller.rs
index 36df8a2..3247935 100644
--- a/system/gd/rust/topshim/src/controller.rs
+++ b/system/gd/rust/topshim/src/controller.rs
@@ -12,6 +12,7 @@
fn GetControllerInterface() -> UniquePtr<ControllerIntf>;
fn read_local_addr(self: &ControllerIntf) -> RawAddress;
+ fn get_ble_supported_states(self: &ControllerIntf) -> u64;
}
}
@@ -30,4 +31,8 @@
pub fn read_local_addr(&mut self) -> [u8; 6] {
self.internal.read_local_addr().address
}
+
+ pub fn get_ble_supported_states(&mut self) -> u64 {
+ self.internal.get_ble_supported_states()
+ }
}
diff --git a/system/gd/rust/topshim/src/profiles/gatt.rs b/system/gd/rust/topshim/src/profiles/gatt.rs
index 01691a4..d2b0e45 100644
--- a/system/gd/rust/topshim/src/profiles/gatt.rs
+++ b/system/gd/rust/topshim/src/profiles/gatt.rs
@@ -199,6 +199,7 @@
fn SetScanParameters(
self: Pin<&mut BleScannerIntf>,
scanner_id: u8,
+ scan_type: u8,
scan_interval: u16,
scan_window: u16,
);
@@ -1540,8 +1541,14 @@
mutcxxcall!(self, MsftAdvMonitorEnable, call_id, enable);
}
- pub fn set_scan_parameters(&mut self, scanner_id: u8, scan_interval: u16, scan_window: u16) {
- mutcxxcall!(self, SetScanParameters, scanner_id, scan_interval, scan_window);
+ pub fn set_scan_parameters(
+ &mut self,
+ scanner_id: u8,
+ scan_type: u8,
+ scan_interval: u16,
+ scan_window: u16,
+ ) {
+ mutcxxcall!(self, SetScanParameters, scanner_id, scan_type, scan_interval, scan_window);
}
pub fn batchscan_config_storage(
diff --git a/system/gd/security/internal/security_manager_impl.cc b/system/gd/security/internal/security_manager_impl.cc
index 5b05c77..4b6d69f 100644
--- a/system/gd/security/internal/security_manager_impl.cc
+++ b/system/gd/security/internal/security_manager_impl.cc
@@ -17,8 +17,9 @@
*/
#include "security_manager_impl.h"
+#include <android_bluetooth_sysprop.h>
+
#include "common/bind.h"
-#include "gd/storage/config_keys.h"
#include "hci/address_with_type.h"
#include "hci/octets.h"
#include "os/log.h"
@@ -28,6 +29,7 @@
#include "security/pairing_handler_le.h"
#include "security/security_manager_listener.h"
#include "security/ui.h"
+#include "storage/config_keys.h"
namespace bluetooth {
namespace security {
@@ -109,9 +111,12 @@
hci::LeAddressManager::AddressPolicy address_policy = hci::LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS;
hci::AddressWithType address_with_type(hci::Address{}, hci::AddressType::RANDOM_DEVICE_ADDRESS);
- /* 7 minutes minimum, 15 minutes maximum for random address refreshing */
- auto minimum_rotation_time = std::chrono::minutes(7);
- auto maximum_rotation_time = std::chrono::minutes(15);
+ /* Default to 7 minutes minimum, 15 minutes maximum for random address refreshing;
+ * device can override. */
+ auto minimum_rotation_time = std::chrono::minutes(
+ GET_SYSPROP(Ble, random_address_rotation_interval_min, 7));
+ auto maximum_rotation_time = std::chrono::minutes(
+ GET_SYSPROP(Ble, random_address_rotation_interval_max, 15));
acl_manager_->SetPrivacyPolicyForInitiatorAddress(
address_policy, address_with_type, minimum_rotation_time, maximum_rotation_time);
diff --git a/system/gd/storage/config_cache_test.cc b/system/gd/storage/config_cache_test.cc
index 90f1561..d4fde91 100644
--- a/system/gd/storage/config_cache_test.cc
+++ b/system/gd/storage/config_cache_test.cc
@@ -21,8 +21,8 @@
#include <cstdio>
-#include "gd/storage/config_keys.h"
#include "hci/enum_helper.h"
+#include "storage/config_keys.h"
#include "storage/device.h"
namespace testing {
diff --git a/system/gd/storage/legacy_config_file_test.cc b/system/gd/storage/legacy_config_file_test.cc
index 4215b5b..430dbd4 100644
--- a/system/gd/storage/legacy_config_file_test.cc
+++ b/system/gd/storage/legacy_config_file_test.cc
@@ -21,8 +21,8 @@
#include <filesystem>
-#include "gd/storage/config_keys.h"
#include "os/files.h"
+#include "storage/config_keys.h"
#include "storage/device.h"
namespace testing {
diff --git a/system/gd/storage/storage_module.cc b/system/gd/storage/storage_module.cc
index fe2f5e4..febcf95 100644
--- a/system/gd/storage/storage_module.cc
+++ b/system/gd/storage/storage_module.cc
@@ -23,7 +23,6 @@
#include <utility>
#include "common/bind.h"
-#include "gd/storage/config_keys.h"
#include "metrics/counter_metrics.h"
#include "os/alarm.h"
#include "os/files.h"
@@ -31,6 +30,7 @@
#include "os/parameter_provider.h"
#include "os/system_properties.h"
#include "storage/config_cache.h"
+#include "storage/config_keys.h"
#include "storage/legacy_config_file.h"
#include "storage/mutation.h"
diff --git a/system/include/hardware/ble_scanner.h b/system/include/hardware/ble_scanner.h
index af5b710..a899526 100644
--- a/system/include/hardware/ble_scanner.h
+++ b/system/include/hardware/ble_scanner.h
@@ -183,8 +183,9 @@
MsftAdvMonitorEnableCallback cb) = 0;
/** Sets the LE scan interval and window in units of N*0.625 msec */
- virtual void SetScanParameters(int scanner_id, int scan_interval,
- int scan_window, Callback cb) = 0;
+ virtual void SetScanParameters(int scanner_id, uint8_t scan_type,
+ int scan_interval, int scan_window,
+ Callback cb) = 0;
/* Configure the batchscan storage */
virtual void BatchscanConfigStorage(int client_if, int batch_scan_full_max,
diff --git a/system/include/hardware/bluetooth.h b/system/include/hardware/bluetooth.h
index a0679a1..57c5964 100644
--- a/system/include/hardware/bluetooth.h
+++ b/system/include/hardware/bluetooth.h
@@ -131,11 +131,11 @@
case BT_STATUS_UNHANDLED:
return std::string("unhandled");
case BT_STATUS_AUTH_FAILURE:
- return std::string("failure");
+ return std::string("auth_failure");
case BT_STATUS_RMT_DEV_DOWN:
return std::string("remote_device_down");
case BT_STATUS_AUTH_REJECTED:
- return std::string("rejected");
+ return std::string("auth_rejected");
case BT_STATUS_JNI_ENVIRONMENT_ERROR:
return std::string("jni_env_error");
case BT_STATUS_JNI_THREAD_ATTACH_ERROR:
@@ -158,7 +158,7 @@
typedef struct {
uint8_t status;
- uint8_t ctrl_state; /* stack reported state */
+ uint32_t ctrl_state; /* stack reported state */
uint64_t tx_time; /* in ms */
uint64_t rx_time; /* in ms */
uint64_t idle_time; /* in ms */
diff --git a/system/include/hardware/bt_av.h b/system/include/hardware/bt_av.h
index b878d85..15dcdbc 100644
--- a/system/include/hardware/bt_av.h
+++ b/system/include/hardware/bt_av.h
@@ -17,6 +17,7 @@
#ifndef ANDROID_INCLUDE_BT_AV_H
#define ANDROID_INCLUDE_BT_AV_H
+#include <bluetooth/log.h>
#include <hardware/bluetooth.h>
#include <raw_address.h>
@@ -433,4 +434,22 @@
__END_DECLS
+namespace fmt {
+template <>
+struct formatter<btav_a2dp_codec_bits_per_sample_t>
+ : enum_formatter<btav_a2dp_codec_bits_per_sample_t> {};
+template <>
+struct formatter<btav_a2dp_codec_priority_t>
+ : enum_formatter<btav_a2dp_codec_priority_t> {};
+template <>
+struct formatter<btav_a2dp_codec_index_t>
+ : enum_formatter<btav_a2dp_codec_index_t> {};
+template <>
+struct formatter<btav_a2dp_codec_sample_rate_t>
+ : enum_formatter<btav_a2dp_codec_sample_rate_t> {};
+template <>
+struct formatter<btav_a2dp_codec_channel_mode_t>
+ : enum_formatter<btav_a2dp_codec_channel_mode_t> {};
+} // namespace fmt
+
#endif /* ANDROID_INCLUDE_BT_AV_H */
diff --git a/system/include/hardware/bt_common_types.h b/system/include/hardware/bt_common_types.h
index ad3c7de..601b64b 100644
--- a/system/include/hardware/bt_common_types.h
+++ b/system/include/hardware/bt_common_types.h
@@ -128,4 +128,14 @@
std::vector<MsftAdvMonitorPattern> patterns;
};
+#if __has_include(<bluetooth/log.h>)
+#include <bluetooth/log.h>
+
+namespace fmt {
+template <>
+struct formatter<bt_gatt_db_attribute_type_t>
+ : enum_formatter<bt_gatt_db_attribute_type_t> {};
+} // namespace fmt
+#endif // __has_include(<bluetooth/log.h>)
+
#endif /* ANDROID_INCLUDE_BT_COMMON_TYPES_H */
diff --git a/system/include/hardware/bt_hf.h b/system/include/hardware/bt_hf.h
index 671e564..e69e841 100644
--- a/system/include/hardware/bt_hf.h
+++ b/system/include/hardware/bt_hf.h
@@ -16,6 +16,8 @@
#pragma once
+#include <bluetooth/log.h>
+
namespace bluetooth {
namespace headset {
@@ -137,3 +139,13 @@
} // namespace headset
} // namespace bluetooth
+
+namespace fmt {
+template <>
+struct formatter<bluetooth::headset::bthf_connection_state_t>
+ : enum_formatter<bluetooth::headset::bthf_connection_state_t> {};
+
+template <>
+struct formatter<bluetooth::headset::bthf_audio_state_t>
+ : enum_formatter<bluetooth::headset::bthf_audio_state_t> {};
+} // namespace fmt
diff --git a/system/include/hardware/bt_hf_client.h b/system/include/hardware/bt_hf_client.h
index 9e64dbb..83d005b 100644
--- a/system/include/hardware/bt_hf_client.h
+++ b/system/include/hardware/bt_hf_client.h
@@ -14,11 +14,10 @@
* limitations under the License.
*/
-#ifndef ANDROID_INCLUDE_BT_HF_CLIENT_H
-#define ANDROID_INCLUDE_BT_HF_CLIENT_H
-#include <raw_address.h>
+#pragma once
-__BEGIN_DECLS
+#include <bluetooth/log.h>
+#include <raw_address.h>
typedef enum {
BTHF_CLIENT_CONNECTION_STATE_DISCONNECTED = 0,
@@ -398,6 +397,8 @@
bt_status_t (*send_android_at)(const RawAddress* bd_addr, const char* arg);
} bthf_client_interface_t;
-__END_DECLS
-
-#endif /* ANDROID_INCLUDE_BT_HF_CLIENT_H */
+namespace fmt {
+template <>
+struct formatter<bthf_client_connection_state_t>
+ : enum_formatter<bthf_client_connection_state_t> {};
+} // namespace fmt
diff --git a/system/include/hardware/bt_le_audio.h b/system/include/hardware/bt_le_audio.h
index c7d3130..b149fec 100644
--- a/system/include/hardware/bt_le_audio.h
+++ b/system/include/hardware/bt_le_audio.h
@@ -17,6 +17,8 @@
#pragma once
+#include <bluetooth/log.h>
+
#include <array>
#include <map>
#include <optional>
@@ -102,11 +104,18 @@
typedef enum {
LE_AUDIO_SAMPLE_RATE_INDEX_NONE = 0,
LE_AUDIO_SAMPLE_RATE_INDEX_8000HZ = 0x01 << 0,
+ LE_AUDIO_SAMPLE_RATE_INDEX_11025HZ = 0x01 << 1,
LE_AUDIO_SAMPLE_RATE_INDEX_16000HZ = 0x01 << 2,
+ LE_AUDIO_SAMPLE_RATE_INDEX_22050HZ = 0x01 << 3,
LE_AUDIO_SAMPLE_RATE_INDEX_24000HZ = 0x01 << 4,
LE_AUDIO_SAMPLE_RATE_INDEX_32000HZ = 0x01 << 5,
LE_AUDIO_SAMPLE_RATE_INDEX_44100HZ = 0x01 << 6,
- LE_AUDIO_SAMPLE_RATE_INDEX_48000HZ = 0x01 << 7
+ LE_AUDIO_SAMPLE_RATE_INDEX_48000HZ = 0x01 << 7,
+ LE_AUDIO_SAMPLE_RATE_INDEX_88200HZ = 0x01 << 8,
+ LE_AUDIO_SAMPLE_RATE_INDEX_96000HZ = 0x01 << 9,
+ LE_AUDIO_SAMPLE_RATE_INDEX_176400HZ = 0x01 << 10,
+ LE_AUDIO_SAMPLE_RATE_INDEX_192000HZ = 0x01 << 11,
+ LE_AUDIO_SAMPLE_RATE_INDEX_384000HZ = 0x01 << 12
} btle_audio_sample_rate_index_t;
typedef enum {
@@ -162,9 +171,15 @@
case LE_AUDIO_SAMPLE_RATE_INDEX_8000HZ:
sample_rate_str = "8000 hz";
break;
+ case LE_AUDIO_SAMPLE_RATE_INDEX_11025HZ:
+ sample_rate_str = "11025 hz";
+ break;
case LE_AUDIO_SAMPLE_RATE_INDEX_16000HZ:
sample_rate_str = "16000 hz";
break;
+ case LE_AUDIO_SAMPLE_RATE_INDEX_22050HZ:
+ sample_rate_str = "22050 hz";
+ break;
case LE_AUDIO_SAMPLE_RATE_INDEX_24000HZ:
sample_rate_str = "24000 hz";
break;
@@ -177,6 +192,21 @@
case LE_AUDIO_SAMPLE_RATE_INDEX_48000HZ:
sample_rate_str = "48000 hz";
break;
+ case LE_AUDIO_SAMPLE_RATE_INDEX_88200HZ:
+ sample_rate_str = "88200 hz";
+ break;
+ case LE_AUDIO_SAMPLE_RATE_INDEX_96000HZ:
+ sample_rate_str = "96000 hz";
+ break;
+ case LE_AUDIO_SAMPLE_RATE_INDEX_176400HZ:
+ sample_rate_str = "176400 hz";
+ break;
+ case LE_AUDIO_SAMPLE_RATE_INDEX_192000HZ:
+ sample_rate_str = "192000 hz";
+ break;
+ case LE_AUDIO_SAMPLE_RATE_INDEX_384000HZ:
+ sample_rate_str = "384000 hz";
+ break;
default:
sample_rate_str =
"Unknown LE sample rate " + std::to_string(sample_rate);
@@ -305,6 +335,10 @@
virtual void OnUnicastMonitorModeStatus(uint8_t direction,
UnicastMonitorModeStatus status) = 0;
+
+ /* Callback with group stream status update */
+ virtual void OnGroupStreamStatus(int group_id,
+ GroupStreamStatus group_stream_status) = 0;
};
class LeAudioClientInterface {
@@ -501,3 +535,22 @@
} /* namespace le_audio */
} /* namespace bluetooth */
+
+namespace fmt {
+template <>
+struct formatter<bluetooth::le_audio::btle_audio_codec_index_t>
+ : enum_formatter<bluetooth::le_audio::btle_audio_codec_index_t> {};
+template <>
+struct formatter<bluetooth::le_audio::btle_audio_sample_rate_index_t>
+ : enum_formatter<bluetooth::le_audio::btle_audio_sample_rate_index_t> {};
+template <>
+struct formatter<bluetooth::le_audio::btle_audio_bits_per_sample_index_t>
+ : enum_formatter<bluetooth::le_audio::btle_audio_bits_per_sample_index_t> {
+};
+template <>
+struct formatter<bluetooth::le_audio::btle_audio_channel_count_index_t>
+ : enum_formatter<bluetooth::le_audio::btle_audio_channel_count_index_t> {};
+template <>
+struct formatter<bluetooth::le_audio::btle_audio_frame_duration_index_t>
+ : enum_formatter<bluetooth::le_audio::btle_audio_frame_duration_index_t> {};
+} // namespace fmt
diff --git a/system/include/hardware/bt_pan.h b/system/include/hardware/bt_pan.h
index 439edf8..25261ba 100644
--- a/system/include/hardware/bt_pan.h
+++ b/system/include/hardware/bt_pan.h
@@ -14,11 +14,10 @@
* limitations under the License.
*/
-#ifndef ANDROID_INCLUDE_BT_PAN_H
-#define ANDROID_INCLUDE_BT_PAN_H
-#include <raw_address.h>
+#pragma once
-__BEGIN_DECLS
+#include <bluetooth/log.h>
+#include <raw_address.h>
#define BTPAN_ROLE_NONE 0
#define BTPAN_ROLE_PANNAP 1
@@ -90,6 +89,12 @@
} btpan_interface_t;
-__END_DECLS
+namespace fmt {
+template <>
+struct formatter<btpan_connection_state_t>
+ : enum_formatter<btpan_connection_state_t> {};
-#endif /* ANDROID_INCLUDE_BT_PAN_H */
+template <>
+struct formatter<btpan_control_state_t>
+ : enum_formatter<btpan_control_state_t> {};
+} // namespace fmt
diff --git a/system/log/include/bluetooth/log.h b/system/log/include/bluetooth/log.h
index 3ed77aa..6f71ae70 100644
--- a/system/log/include/bluetooth/log.h
+++ b/system/log/include/bluetooth/log.h
@@ -143,4 +143,21 @@
}
};
+/// Default formatter implementation for formatting
+/// values of type T for which a string conversion function
+/// T_to_str is implemented.
+///
+/// Enable this formatter in the code by declaring:
+/// ```
+/// template<>
+/// struct fmt::formatter<T> : string_formatter<T, &T_to_str> {};
+/// ```
+template <typename T, std::string (*F)(const T&), class CharT = char>
+struct string_formatter : fmt::formatter<std::string> {
+ template <class Context>
+ typename Context::iterator format(const T& value, Context& ctx) const {
+ return fmt::formatter<std::string>::format(F(value), ctx);
+ }
+};
+
} // namespace fmt
diff --git a/system/log/src/vlog_android.cc b/system/log/src/vlog_android.cc
index 38930ca..e5ca8f1 100644
--- a/system/log/src/vlog_android.cc
+++ b/system/log/src/vlog_android.cc
@@ -27,8 +27,8 @@
char const* function_name, fmt::string_view fmt,
fmt::format_args vargs) {
// Check if log is enabled.
- if (!__android_log_is_loggable(level, tag, ANDROID_LOG_DEFAULT) &&
- !__android_log_is_loggable(level, "bluetooth", ANDROID_LOG_DEFAULT)) {
+ if (!__android_log_is_loggable(level, tag, ANDROID_LOG_INFO) &&
+ !__android_log_is_loggable(level, "bluetooth", ANDROID_LOG_INFO)) {
return;
}
@@ -48,6 +48,15 @@
.message = buffer.c_str(),
};
__android_log_write_log_message(&message);
+
+ if (level == Level::kFatal) {
+ // Log assertion failures to stderr for the benefit of "adb shell" users
+ // and gtests (http://b/23675822).
+ char const* buf = buffer.c_str();
+ TEMP_FAILURE_RETRY(write(2, buf, strlen(buf)));
+ TEMP_FAILURE_RETRY(write(2, "\n", 1));
+ __android_log_call_aborter(buf);
+ }
}
} // namespace bluetooth::log_internal
diff --git a/system/main/Android.bp b/system/main/Android.bp
index a968cdb..dacedb6 100644
--- a/system/main/Android.bp
+++ b/system/main/Android.bp
@@ -22,6 +22,7 @@
name: "libbte",
defaults: ["fluoride_defaults"],
srcs: [
+ ":BluetoothStackManagerSources",
":LibBluetoothShimSources",
":LibBluetoothSources",
],
@@ -57,6 +58,7 @@
"libbluetooth_log",
"libbt-platform-protos-lite",
"libbt_shim_bridge",
+ "libcom.android.sysprop.bluetooth.wrapped",
],
header_libs: ["libbluetooth_headers"],
cflags: ["-Wno-unused-parameter"],
@@ -124,6 +126,7 @@
defaults: ["fluoride_defaults"],
srcs: [
+ ":BluetoothStackManagerSources",
":LibBluetoothShimSources",
":LibBluetoothSources",
],
@@ -146,6 +149,7 @@
],
whole_static_libs: [
"libbluetooth_gd", // Gabeldorsche
+ "libcom.android.sysprop.bluetooth.wrapped",
],
header_libs: ["libbluetooth_headers"],
static_libs: [
@@ -179,6 +183,7 @@
":TestMockBta",
":TestMockBtif",
":TestMockBtu",
+ ":TestMockJni",
":TestMockLegacyHciCommands",
":TestMockLegacyHciInterface",
":TestMockMainShimEntry",
@@ -203,9 +208,11 @@
"shim/utils.cc",
"test/common_stack_test.cc",
"test/main_shim_dumpsys_test.cc",
+ "test/main_shim_stack_lifecycle_test.cc",
"test/main_shim_test.cc",
],
static_libs: [
+ "libbase",
"libbluetooth-dumpsys",
"libbluetooth-types",
"libbluetooth_crypto_toolbox",
@@ -218,6 +225,7 @@
"libbt_shim_ffi",
"libbtdevice",
"libchrome",
+ "libcom.android.sysprop.bluetooth.wrapped",
"libevent",
"libflatbuffers-cpp",
"libgmock",
@@ -225,6 +233,7 @@
"libosi",
],
shared_libs: [
+ "libPlatformProperties",
"libcrypto",
"server_configurable_flags",
],
diff --git a/system/main/BUILD.gn b/system/main/BUILD.gn
index d2e25f7..08456b7 100644
--- a/system/main/BUILD.gn
+++ b/system/main/BUILD.gn
@@ -85,6 +85,7 @@
"//bt/system/gd:libbluetooth_gd",
"//bt/system/log:libbluetooth_log",
"//bt/system/hci",
+ "//bt/system/main/shim:BluetoothStackManagerSources",
"//bt/system/main/shim:LibBluetoothShimSources",
"//bt/system/osi",
"//bt/system/packet",
@@ -95,6 +96,7 @@
configs += [
"//bt/system:target_defaults",
+ "//bt/system/log:log_defaults",
"//bt/system:external_tinyxml2",
"//bt/system:external_flatbuffers",
]
diff --git a/system/main/bte_init_cpp_logging.cc b/system/main/bte_init_cpp_logging.cc
index 520d14d..367cce1 100644
--- a/system/main/bte_init_cpp_logging.cc
+++ b/system/main/bte_init_cpp_logging.cc
@@ -18,7 +18,7 @@
#include <base/command_line.h>
#include <base/logging.h>
#include <base/strings/stringprintf.h>
-#include <osi/include/log.h>
+#include <os/log.h>
#include "main_int.h"
diff --git a/system/main/shim/Android.bp b/system/main/shim/Android.bp
index ae14e4f..b896720 100644
--- a/system/main/shim/Android.bp
+++ b/system/main/shim/Android.bp
@@ -8,6 +8,14 @@
}
filegroup {
+ name: "BluetoothStackManagerSources",
+ srcs: [
+ "entry.cc",
+ "stack.cc",
+ ],
+}
+
+filegroup {
name: "LibBluetoothShimSources",
srcs: [
"acl.cc",
@@ -19,7 +27,6 @@
"controller.cc",
"distance_measurement_manager.cc",
"dumpsys.cc",
- "entry.cc",
"hci_layer.cc",
"l2c_api.cc",
"le_advertising_manager.cc",
@@ -27,7 +34,6 @@
"metric_id_api.cc",
"metrics_api.cc",
"shim.cc",
- "stack.cc",
"utils.cc",
],
}
diff --git a/system/main/shim/BUILD.gn b/system/main/shim/BUILD.gn
index 6529f1b..33ffeb9 100644
--- a/system/main/shim/BUILD.gn
+++ b/system/main/shim/BUILD.gn
@@ -13,7 +13,42 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
+#
+source_set("BluetoothStackManagerSources") {
+ sources = [
+ "entry.cc",
+ "stack.cc",
+ ]
+ include_dirs = [
+ "//bt/system",
+ "//bt/system/btif/include",
+ "//bt/system/gd",
+ "//bt/system/gd/rust/shim",
+ "//bt/system/stack/include",
+ "//bt/system/types",
+ ]
+
+ deps = [
+ "//bt/system/gd:BluetoothGeneratedDumpsysDataSchema_h",
+ "//bt/system/gd/common:BluetoothCommonSources",
+ "//bt/system/gd/dumpsys/bundler:BluetoothGeneratedBundlerSchema_h_bfbs",
+ "//bt/system/gd/hci:BluetoothHciSources",
+ "//bt/system/gd/os:BluetoothOsSources_linux_generic",
+ "//bt/system/gd/packet:BluetoothPacketSources",
+ "//bt/system/gd/rust/shim:libbluetooth_rust_interop",
+ "//bt/system/gd/rust/topshim:libbluetooth_topshim",
+ "//bt/system/osi",
+ "//bt/system/pdl:BluetoothGeneratedPackets_h",
+ "//bt/system/stack",
+ "//bt/system/types",
+ ]
+
+ configs += [
+ "//bt/system:target_defaults",
+ "//bt/system/log:log_defaults",
+ ]
+}
source_set("LibBluetoothShimSources") {
sources = [
"acl.cc",
@@ -25,7 +60,6 @@
"controller.cc",
"distance_measurement_manager.cc",
"dumpsys.cc",
- "entry.cc",
"hci_layer.cc",
"l2c_api.cc",
"le_advertising_manager.cc",
@@ -33,7 +67,6 @@
"metric_id_api.cc",
"metrics_api.cc",
"shim.cc",
- "stack.cc",
"utils.cc",
]
@@ -61,5 +94,8 @@
"//bt/system/types",
]
- configs += [ "//bt/system:target_defaults" ]
+ configs += [
+ "//bt/system:target_defaults",
+ "//bt/system/log:log_defaults",
+ ]
}
diff --git a/system/main/shim/acl.cc b/system/main/shim/acl.cc
index e34eea7..cd6339b 100644
--- a/system/main/shim/acl.cc
+++ b/system/main/shim/acl.cc
@@ -542,7 +542,7 @@
TRY_POSTING_ON_MAIN(interface_.on_change_connection_link_key_complete);
}
- void OnReadClockOffsetComplete(uint16_t clock_offset) override {
+ void OnReadClockOffsetComplete(uint16_t /* clock_offset */) override {
LOG_INFO("UNIMPLEMENTED");
}
@@ -563,66 +563,73 @@
minimum_remote_timeout, minimum_local_timeout);
}
- void OnQosSetupComplete(hci::ServiceType service_type, uint32_t token_rate,
- uint32_t peak_bandwidth, uint32_t latency,
- uint32_t delay_variation) override {
+ void OnQosSetupComplete(hci::ServiceType /* service_type */,
+ uint32_t /* token_rate */,
+ uint32_t /* peak_bandwidth */, uint32_t /* latency */,
+ uint32_t /* delay_variation */) override {
LOG_INFO("UNIMPLEMENTED");
}
- void OnFlowSpecificationComplete(hci::FlowDirection flow_direction,
- hci::ServiceType service_type,
- uint32_t token_rate,
- uint32_t token_bucket_size,
- uint32_t peak_bandwidth,
- uint32_t access_latency) override {
+ void OnFlowSpecificationComplete(hci::FlowDirection /* flow_direction */,
+ hci::ServiceType /* service_type */,
+ uint32_t /* token_rate */,
+ uint32_t /* token_bucket_size */,
+ uint32_t /* peak_bandwidth */,
+ uint32_t /* access_latency */) override {
LOG_INFO("UNIMPLEMENTED");
}
void OnFlushOccurred() override { LOG_INFO("UNIMPLEMENTED"); }
- void OnRoleDiscoveryComplete(hci::Role current_role) override {
+ void OnRoleDiscoveryComplete(hci::Role /* current_role */) override {
LOG_INFO("UNIMPLEMENTED");
}
void OnReadLinkPolicySettingsComplete(
- uint16_t link_policy_settings) override {
+ uint16_t /* link_policy_settings */) override {
LOG_INFO("UNIMPLEMENTED");
}
- void OnReadAutomaticFlushTimeoutComplete(uint16_t flush_timeout) override {
+ void OnReadAutomaticFlushTimeoutComplete(
+ uint16_t /* flush_timeout */) override {
LOG_INFO("UNIMPLEMENTED");
}
- void OnReadTransmitPowerLevelComplete(uint8_t transmit_power_level) override {
+ void OnReadTransmitPowerLevelComplete(
+ uint8_t /* transmit_power_level */) override {
LOG_INFO("UNIMPLEMENTED");
}
void OnReadLinkSupervisionTimeoutComplete(
- uint16_t link_supervision_timeout) override {
+ uint16_t /* link_supervision_timeout */) override {
LOG_INFO("UNIMPLEMENTED");
}
void OnReadFailedContactCounterComplete(
- uint16_t failed_contact_counter) override {
+ uint16_t /* failed_contact_counter */) override {
LOG_INFO("UNIMPLEMENTED");
}
- void OnReadLinkQualityComplete(uint8_t link_quality) override {
+ void OnReadLinkQualityComplete(uint8_t /* link_quality */) override {
LOG_INFO("UNIMPLEMENTED");
}
void OnReadAfhChannelMapComplete(
- hci::AfhMode afh_mode, std::array<uint8_t, 10> afh_channel_map) override {
+ hci::AfhMode /* afh_mode */,
+ std::array<uint8_t, 10> /* afh_channel_map */) override {
LOG_INFO("UNIMPLEMENTED");
}
- void OnReadRssiComplete(uint8_t rssi) override { LOG_INFO("UNIMPLEMENTED"); }
-
- void OnReadClockComplete(uint32_t clock, uint16_t accuracy) override {
+ void OnReadRssiComplete(uint8_t /* rssi */) override {
LOG_INFO("UNIMPLEMENTED");
}
- void OnCentralLinkKeyComplete(hci::KeyFlag key_flag) override {
+ void OnReadClockComplete(uint32_t /* clock */,
+ uint16_t /* accuracy */) override {
+ LOG_INFO("UNIMPLEMENTED");
+ }
+
+ void OnCentralLinkKeyComplete(hci::KeyFlag /* key_flag */) override {
LOG_INFO("%s UNIMPLEMENTED", __func__);
}
@@ -807,8 +814,8 @@
manufacturer_name, sub_version);
}
- void OnLeReadRemoteFeaturesComplete(hci::ErrorCode hci_status,
- uint64_t features) {
+ void OnLeReadRemoteFeaturesComplete(hci::ErrorCode /* hci_status */,
+ uint64_t /* features */) {
// TODO
}
diff --git a/system/main/shim/acl_api.cc b/system/main/shim/acl_api.cc
index e8d8b4c..6194e4a 100644
--- a/system/main/shim/acl_api.cc
+++ b/system/main/shim/acl_api.cc
@@ -16,8 +16,8 @@
#include "main/shim/acl_api.h"
+#include <android_bluetooth_sysprop.h>
#include <base/location.h>
-
#include <cstdint>
#include <future>
#include <optional>
@@ -79,9 +79,13 @@
: hci::LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS;
hci::AddressWithType empty_address_with_type(
hci::Address{}, hci::AddressType::RANDOM_DEVICE_ADDRESS);
- /* 7 minutes minimum, 15 minutes maximum for random address refreshing */
- auto minimum_rotation_time = std::chrono::minutes(7);
- auto maximum_rotation_time = std::chrono::minutes(15);
+
+ /* Default to 7 minutes minimum, 15 minutes maximum for random address refreshing;
+ * device can override. */
+ auto minimum_rotation_time = std::chrono::minutes(
+ GET_SYSPROP(Ble, random_address_rotation_interval_min, 7));
+ auto maximum_rotation_time = std::chrono::minutes(
+ GET_SYSPROP(Ble, random_address_rotation_interval_max, 15));
Stack::GetInstance()
->GetStackManager()
@@ -177,7 +181,7 @@
void bluetooth::shim::ACL_RemoteNameRequest(const RawAddress& addr,
uint8_t page_scan_rep_mode,
- uint8_t page_scan_mode,
+ uint8_t /* page_scan_mode */,
uint16_t clock_offset) {
bluetooth::shim::GetRemoteNameRequest()->StartRemoteNameRequest(
ToGdAddress(addr),
diff --git a/system/main/shim/ble_scanner_interface_impl.h b/system/main/shim/ble_scanner_interface_impl.h
index 2d2401c..8a95240 100644
--- a/system/main/shim/ble_scanner_interface_impl.h
+++ b/system/main/shim/ble_scanner_interface_impl.h
@@ -74,8 +74,8 @@
MsftAdvMonitorRemoveCallback cb) override;
void MsftAdvMonitorEnable(bool enable,
MsftAdvMonitorEnableCallback cb) override;
- void SetScanParameters(int scanner_id, int scan_interval, int scan_window,
- Callback cb) override;
+ void SetScanParameters(int scanner_id, uint8_t scan_type, int scan_interval,
+ int scan_window, Callback cb) override;
void BatchscanConfigStorage(int client_if, int batch_scan_full_max,
int batch_scan_trunc_max,
int batch_scan_notify_threshold,
diff --git a/system/main/shim/btm.cc b/system/main/shim/btm.cc
index 596ae37..5269832 100644
--- a/system/main/shim/btm.cc
+++ b/system/main/shim/btm.cc
@@ -26,16 +26,16 @@
#include <cstring>
#include <mutex>
+#include "hci/acl_manager.h"
+#include "hci/controller_interface.h"
#include "hci/le_advertising_manager.h"
#include "hci/le_scanning_manager.h"
-#include "main/shim/controller.h"
#include "main/shim/entry.h"
#include "main/shim/helpers.h"
#include "neighbor/connectability.h"
#include "neighbor/discoverability.h"
#include "neighbor/inquiry.h"
#include "neighbor/page.h"
-#include "security/security_module.h"
#include "stack/btm/btm_dev.h"
#include "stack/btm/btm_int_types.h"
#include "types/ble_address_with_type.h"
@@ -86,16 +86,17 @@
}
void Btm::ScanningCallbacks::OnScannerRegistered(
- const bluetooth::hci::Uuid app_uuid, bluetooth::hci::ScannerId scanner_id,
- ScanningStatus status){};
+ const bluetooth::hci::Uuid /* app_uuid */,
+ bluetooth::hci::ScannerId /* scanner_id */, ScanningStatus /* status */){};
void Btm::ScanningCallbacks::OnSetScannerParameterComplete(
- bluetooth::hci::ScannerId scanner_id, ScanningStatus status){};
+ bluetooth::hci::ScannerId /* scanner_id */, ScanningStatus /* status */){};
void Btm::ScanningCallbacks::OnScanResult(
- uint16_t event_type, uint8_t address_type, bluetooth::hci::Address address,
- uint8_t primary_phy, uint8_t secondary_phy, uint8_t advertising_sid,
- int8_t tx_power, int8_t rssi, uint16_t periodic_advertising_interval,
+ uint16_t /* event_type */, uint8_t address_type,
+ bluetooth::hci::Address address, uint8_t primary_phy, uint8_t secondary_phy,
+ uint8_t advertising_sid, int8_t tx_power, int8_t rssi,
+ uint16_t periodic_advertising_interval,
std::vector<uint8_t> advertising_data) {
tBLE_ADDR_TYPE ble_address_type = to_ble_addr_type(address_type);
uint16_t extended_event_type = 0;
@@ -118,34 +119,37 @@
}
void Btm::ScanningCallbacks::OnTrackAdvFoundLost(
- bluetooth::hci::AdvertisingFilterOnFoundOnLostInfo on_found_on_lost_info){};
-void Btm::ScanningCallbacks::OnBatchScanReports(int client_if, int status,
- int report_format,
- int num_records,
- std::vector<uint8_t> data){};
+ bluetooth::hci::
+ AdvertisingFilterOnFoundOnLostInfo /* on_found_on_lost_info */){};
+void Btm::ScanningCallbacks::OnBatchScanReports(
+ int /* client_if */, int /* status */, int /* report_format */,
+ int /* num_records */, std::vector<uint8_t> /* data */){};
-void Btm::ScanningCallbacks::OnBatchScanThresholdCrossed(int client_if){};
+void Btm::ScanningCallbacks::OnBatchScanThresholdCrossed(int /* client_if */){};
void Btm::ScanningCallbacks::OnTimeout(){};
-void Btm::ScanningCallbacks::OnFilterEnable(bluetooth::hci::Enable enable,
- uint8_t status){};
+void Btm::ScanningCallbacks::OnFilterEnable(bluetooth::hci::Enable /* enable */,
+ uint8_t /* status */){};
void Btm::ScanningCallbacks::OnFilterParamSetup(
- uint8_t available_spaces, bluetooth::hci::ApcfAction action,
- uint8_t status){};
+ uint8_t /* available_spaces */, bluetooth::hci::ApcfAction /* action */,
+ uint8_t /* status */){};
void Btm::ScanningCallbacks::OnFilterConfigCallback(
- bluetooth::hci::ApcfFilterType filter_type, uint8_t available_spaces,
- bluetooth::hci::ApcfAction action, uint8_t status){};
+ bluetooth::hci::ApcfFilterType /* filter_type */,
+ uint8_t /* available_spaces */, bluetooth::hci::ApcfAction /* action */,
+ uint8_t /* status */){};
void Btm::ScanningCallbacks::OnPeriodicSyncStarted(
- int reg_id, uint8_t status, uint16_t sync_handle, uint8_t advertising_sid,
- bluetooth::hci::AddressWithType address_with_type, uint8_t phy,
- uint16_t interval) {}
-void Btm::ScanningCallbacks::OnPeriodicSyncReport(uint16_t sync_handle,
- int8_t tx_power, int8_t rssi,
- uint8_t status,
- std::vector<uint8_t> data) {}
-void Btm::ScanningCallbacks::OnPeriodicSyncLost(uint16_t sync_handle) {}
+ int /* reg_id */, uint8_t /* status */, uint16_t /* sync_handle */,
+ uint8_t /* advertising_sid */,
+ bluetooth::hci::AddressWithType /* address_with_type */, uint8_t /* phy */,
+ uint16_t /* interval */) {}
+void Btm::ScanningCallbacks::OnPeriodicSyncReport(
+ uint16_t /* sync_handle */, int8_t /* tx_power */, int8_t /* rssi */,
+ uint8_t /* status */, std::vector<uint8_t> /* data */) {}
+void Btm::ScanningCallbacks::OnPeriodicSyncLost(uint16_t /* sync_handle */) {}
void Btm::ScanningCallbacks::OnPeriodicSyncTransferred(
- int pa_source, uint8_t status, bluetooth::hci::Address address) {}
-void Btm::ScanningCallbacks::OnBigInfoReport(uint16_t sync_handle, bool encrypted) {}
+ int /* pa_source */, uint8_t /* status */,
+ bluetooth::hci::Address /* address */) {}
+void Btm::ScanningCallbacks::OnBigInfoReport(uint16_t /* sync_handle */,
+ bool /* encrypted */) {}
Btm::Btm(os::Handler* handler, neighbor::InquiryModule* inquiry)
: scanning_timer_(handler), observing_timer_(handler) {
@@ -241,7 +245,7 @@
bool Btm::StartPeriodicInquiry(uint8_t mode, uint8_t duration,
uint8_t max_responses, uint16_t max_delay,
uint16_t min_delay,
- tBTM_INQ_RESULTS_CB* p_results_cb) {
+ tBTM_INQ_RESULTS_CB* /* p_results_cb */) {
switch (mode) {
case kInquiryModeOff:
limited_periodic_inquiry_active_ = false;
@@ -393,8 +397,8 @@
return true;
}
-BtmStatus Btm::ReadClassicRemoteDeviceName(const RawAddress& raw_address,
- tBTM_NAME_CMPL_CB* callback) {
+BtmStatus Btm::ReadClassicRemoteDeviceName(const RawAddress& /* raw_address */,
+ tBTM_NAME_CMPL_CB* /* callback */) {
LOG_ALWAYS_FATAL("unreachable");
return BTM_UNDEFINED;
}
@@ -444,7 +448,7 @@
void Btm::CancelObservingTimer() { observing_timer_.Cancel(); }
-void Btm::StartScanning(bool use_active_scanning) {
+void Btm::StartScanning(bool /* use_active_scanning */) {
GetScanning()->RegisterScanningCallback(&scanning_callbacks_);
GetScanning()->Scan(true);
}
@@ -453,6 +457,10 @@
return GetAdvertising()->GetNumberOfAdvertisingInstances();
}
+size_t Btm::GetNumberOfAdvertisingInstancesInUse() const {
+ return GetAdvertising()->GetNumberOfAdvertisingInstancesInUse();
+}
+
uint16_t Btm::GetAclHandle(const RawAddress& remote_bda,
tBT_TRANSPORT transport) {
auto acl_manager = GetAclManager();
diff --git a/system/main/shim/btm.h b/system/main/shim/btm.h
index bfa378c..695724f 100644
--- a/system/main/shim/btm.h
+++ b/system/main/shim/btm.h
@@ -155,6 +155,7 @@
void StopObserving();
size_t GetNumberOfAdvertisingInstances() const;
+ size_t GetNumberOfAdvertisingInstancesInUse() const;
void SetObservingTimer(uint64_t duration_ms,
common::OnceCallback<void()> callback);
diff --git a/system/main/shim/btm_api.cc b/system/main/shim/btm_api.cc
index 654930a..f281986 100644
--- a/system/main/shim/btm_api.cc
+++ b/system/main/shim/btm_api.cc
@@ -131,3 +131,7 @@
btm_ble_reset_id();
return BTM_SUCCESS;
}
+
+size_t bluetooth::shim::BTM_BleGetNumberOfAdvertisingInstancesInUse(void) {
+ return Stack::GetInstance()->GetBtm()->GetNumberOfAdvertisingInstancesInUse();
+}
diff --git a/system/main/shim/btm_api.h b/system/main/shim/btm_api.h
index c4ebdee..b296ecf 100644
--- a/system/main/shim/btm_api.h
+++ b/system/main/shim/btm_api.h
@@ -1118,6 +1118,16 @@
*******************************************************************************/
tBTM_STATUS BTM_BleResetId(void);
+/*******************************************************************************
+ *
+ * Function BTM_BleGetNumberOfAdvertisingInstancesInUse
+ *
+ * Description Obtains the number of BLE advertising instances in use
+ *
+ * Returns Return the number of BLE advertising instances in use
+ *******************************************************************************/
+size_t BTM_BleGetNumberOfAdvertisingInstancesInUse(void);
+
/**
* Send remote name request to GD shim Name module
*/
diff --git a/system/main/shim/controller.cc b/system/main/shim/controller.cc
index 193ebb8..0ca6a4f 100644
--- a/system/main/shim/controller.cc
+++ b/system/main/shim/controller.cc
@@ -229,10 +229,10 @@
FORWARD_GETTER(
uint8_t, get_iso_buffers,
GetController()->GetControllerIsoBufferSize().total_num_le_packets_)
-FORWARD_GETTER(uint8_t, get_le_connect_list_size,
+FORWARD_GETTER(uint8_t, get_le_accept_list_size,
GetController()->GetLeFilterAcceptListSize())
-static void set_ble_resolving_list_max_size(int resolving_list_max_size) {
+static void set_ble_resolving_list_max_size(int /* resolving_list_max_size */) {
LOG_DEBUG("UNSUPPORTED");
}
@@ -366,7 +366,7 @@
.get_acl_buffer_count_ble = get_le_buffers,
.get_iso_buffer_count = get_iso_buffers,
- .get_ble_acceptlist_size = get_le_connect_list_size,
+ .get_ble_acceptlist_size = get_le_accept_list_size,
.get_ble_resolving_list_max_size = get_le_resolving_list_size,
.set_ble_resolving_list_max_size = set_ble_resolving_list_max_size,
diff --git a/system/main/shim/hci_layer.cc b/system/main/shim/hci_layer.cc
index b330769..929966c 100644
--- a/system/main/shim/hci_layer.cc
+++ b/system/main/shim/hci_layer.cc
@@ -37,6 +37,7 @@
#include "stack/include/bt_hdr.h"
#include "stack/include/bt_types.h"
#include "stack/include/btm_iso_api.h"
+#include "stack/include/dev_hci_link_interface.h"
#include "stack/include/hcimsgs.h"
#include "stack/include/main_thread.h"
@@ -90,72 +91,10 @@
}
};
-bool is_valid_subevent_code(bluetooth::hci::SubeventCode subevent_code) {
+static bool register_subevent_code(bluetooth::hci::SubeventCode subevent_code) {
switch (subevent_code) {
- case bluetooth::hci::SubeventCode::CONNECTION_UPDATE_COMPLETE:
- case bluetooth::hci::SubeventCode::DATA_LENGTH_CHANGE:
- case bluetooth::hci::SubeventCode::ENHANCED_CONNECTION_COMPLETE:
- case bluetooth::hci::SubeventCode::PHY_UPDATE_COMPLETE:
case bluetooth::hci::SubeventCode::READ_REMOTE_FEATURES_COMPLETE:
- case bluetooth::hci::SubeventCode::REMOTE_CONNECTION_PARAMETER_REQUEST:
- case bluetooth::hci::SubeventCode::READ_LOCAL_P256_PUBLIC_KEY_COMPLETE:
- case bluetooth::hci::SubeventCode::GENERATE_DHKEY_COMPLETE:
- case bluetooth::hci::SubeventCode::DIRECTED_ADVERTISING_REPORT:
- case bluetooth::hci::SubeventCode::EXTENDED_ADVERTISING_REPORT:
- case bluetooth::hci::SubeventCode::PERIODIC_ADVERTISING_SYNC_ESTABLISHED:
- case bluetooth::hci::SubeventCode::PERIODIC_ADVERTISING_REPORT:
- case bluetooth::hci::SubeventCode::PERIODIC_ADVERTISING_SYNC_LOST:
- case bluetooth::hci::SubeventCode::SCAN_TIMEOUT:
- case bluetooth::hci::SubeventCode::ADVERTISING_SET_TERMINATED:
- case bluetooth::hci::SubeventCode::SCAN_REQUEST_RECEIVED:
- case bluetooth::hci::SubeventCode::CHANNEL_SELECTION_ALGORITHM:
- case bluetooth::hci::SubeventCode::CONNECTIONLESS_IQ_REPORT:
- case bluetooth::hci::SubeventCode::CONNECTION_IQ_REPORT:
- case bluetooth::hci::SubeventCode::CTE_REQUEST_FAILED:
- case bluetooth::hci::SubeventCode::
- PERIODIC_ADVERTISING_SYNC_TRANSFER_RECEIVED:
- case bluetooth::hci::SubeventCode::CIS_ESTABLISHED:
- case bluetooth::hci::SubeventCode::CIS_REQUEST:
- case bluetooth::hci::SubeventCode::CREATE_BIG_COMPLETE:
- case bluetooth::hci::SubeventCode::TERMINATE_BIG_COMPLETE:
- case bluetooth::hci::SubeventCode::BIG_SYNC_ESTABLISHED:
- case bluetooth::hci::SubeventCode::BIG_SYNC_LOST:
- case bluetooth::hci::SubeventCode::REQUEST_PEER_SCA_COMPLETE:
- case bluetooth::hci::SubeventCode::PATH_LOSS_THRESHOLD:
- case bluetooth::hci::SubeventCode::TRANSMIT_POWER_REPORTING:
- case bluetooth::hci::SubeventCode::BIG_INFO_ADVERTISING_REPORT:
- case bluetooth::hci::SubeventCode::ADVERTISING_REPORT:
case bluetooth::hci::SubeventCode::LONG_TERM_KEY_REQUEST:
- return true;
- default:
- return false;
- }
-}
-
-static bool subevent_already_registered_in_le_hci_layer(
- bluetooth::hci::SubeventCode subevent_code) {
- switch (subevent_code) {
- case bluetooth::hci::SubeventCode::CONNECTION_COMPLETE:
- case bluetooth::hci::SubeventCode::CONNECTION_UPDATE_COMPLETE:
- case bluetooth::hci::SubeventCode::DATA_LENGTH_CHANGE:
- case bluetooth::hci::SubeventCode::ENHANCED_CONNECTION_COMPLETE:
- case bluetooth::hci::SubeventCode::PHY_UPDATE_COMPLETE:
- case bluetooth::hci::SubeventCode::REMOTE_CONNECTION_PARAMETER_REQUEST:
- case bluetooth::hci::SubeventCode::ADVERTISING_SET_TERMINATED:
- case bluetooth::hci::SubeventCode::SCAN_REQUEST_RECEIVED:
- case bluetooth::hci::SubeventCode::SCAN_TIMEOUT:
- case bluetooth::hci::SubeventCode::ADVERTISING_REPORT:
- case bluetooth::hci::SubeventCode::DIRECTED_ADVERTISING_REPORT:
- case bluetooth::hci::SubeventCode::EXTENDED_ADVERTISING_REPORT:
- case bluetooth::hci::SubeventCode::PERIODIC_ADVERTISING_REPORT:
- case bluetooth::hci::SubeventCode::PERIODIC_ADVERTISING_SYNC_ESTABLISHED:
- case bluetooth::hci::SubeventCode::PERIODIC_ADVERTISING_SYNC_LOST:
- case bluetooth::hci::SubeventCode::
- PERIODIC_ADVERTISING_SYNC_TRANSFER_RECEIVED:
- case bluetooth::hci::SubeventCode::TRANSMIT_POWER_REPORTING:
- case bluetooth::hci::SubeventCode::BIG_INFO_ADVERTISING_REPORT:
- return true;
- case bluetooth::hci::SubeventCode::READ_REMOTE_FEATURES_COMPLETE:
case bluetooth::hci::SubeventCode::READ_LOCAL_P256_PUBLIC_KEY_COMPLETE:
case bluetooth::hci::SubeventCode::GENERATE_DHKEY_COMPLETE:
case bluetooth::hci::SubeventCode::CHANNEL_SELECTION_ALGORITHM:
@@ -170,7 +109,7 @@
case bluetooth::hci::SubeventCode::BIG_SYNC_LOST:
case bluetooth::hci::SubeventCode::REQUEST_PEER_SCA_COMPLETE:
case bluetooth::hci::SubeventCode::PATH_LOSS_THRESHOLD:
- case bluetooth::hci::SubeventCode::LONG_TERM_KEY_REQUEST:
+ return true;
default:
return false;
}
@@ -228,12 +167,15 @@
static void vendor_specific_event_callback(
bluetooth::hci::VendorSpecificEventView vendor_specific_event_view) {
- if (!send_data_upwards) {
+ auto bqr =
+ bluetooth::hci::BqrEventView::CreateOptional(vendor_specific_event_view);
+ if (!bqr) {
return;
}
- send_data_upwards.Run(
- FROM_HERE,
- WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_EVT, &vendor_specific_event_view));
+
+ auto payload = vendor_specific_event_view.GetPayload();
+ std::vector<uint8_t> bytes{payload.begin(), payload.end()};
+ btm_vendor_specific_evt(bytes.data(), bytes.size());
}
void OnTransmitPacketCommandComplete(command_complete_cb complete_callback,
@@ -454,21 +396,16 @@
subevent_code_raw++) {
auto subevent_code =
static_cast<bluetooth::hci::SubeventCode>(subevent_code_raw);
- if (!is_valid_subevent_code(subevent_code)) {
+ if (!register_subevent_code(subevent_code)) {
continue;
}
- if (subevent_already_registered_in_le_hci_layer(subevent_code)) {
- continue;
- }
-
cpp::register_le_event(subevent_code);
}
// TODO handle BQR event in GD
- auto handler = bluetooth::shim::GetGdShimHandler();
bluetooth::shim::GetVendorSpecificEventManager()->RegisterEventHandler(
bluetooth::hci::VseSubeventCode::BQR_EVENT,
- handler->Bind(cpp::vendor_specific_event_callback));
+ get_main_thread()->Bind(cpp::vendor_specific_event_callback));
cpp::register_for_iso();
}
diff --git a/system/main/shim/le_advertising_manager.cc b/system/main/shim/le_advertising_manager.cc
index b19f99d..a1ec02f 100644
--- a/system/main/shim/le_advertising_manager.cc
+++ b/system/main/shim/le_advertising_manager.cc
@@ -93,7 +93,7 @@
}
void SetParameters(uint8_t advertiser_id, AdvertiseParameters params,
- ParametersCallback cb) override {
+ ParametersCallback /* cb */) override {
LOG(INFO) << __func__ << " in shim layer";
bluetooth::hci::AdvertisingConfig config{};
parse_parameter(config, params);
@@ -101,7 +101,7 @@
}
void SetData(int advertiser_id, bool set_scan_rsp, vector<uint8_t> data,
- StatusCallback cb) override {
+ StatusCallback /* cb */) override {
LOG(INFO) << __func__ << " in shim layer";
std::vector<GapData> advertising_data = {};
parse_gap_data(data, advertising_data);
@@ -109,9 +109,9 @@
advertising_data);
}
- void Enable(uint8_t advertiser_id, bool enable, StatusCallback cb,
+ void Enable(uint8_t advertiser_id, bool enable, StatusCallback /* cb */,
uint16_t duration, uint8_t maxExtAdvEvents,
- StatusCallback timeout_cb) override {
+ StatusCallback /* timeout_cb */) override {
LOG(INFO) << __func__ << " in shim layer";
bluetooth::shim::GetAdvertising()->EnableAdvertiser(
advertiser_id, enable, duration, maxExtAdvEvents);
@@ -137,14 +137,14 @@
}
void StartAdvertisingSet(uint8_t client_id, int reg_id,
- IdTxPowerStatusCallback register_cb,
+ IdTxPowerStatusCallback /* register_cb */,
AdvertiseParameters params,
std::vector<uint8_t> advertise_data,
std::vector<uint8_t> scan_response_data,
PeriodicAdvertisingParameters periodic_params,
std::vector<uint8_t> periodic_data,
uint16_t duration, uint8_t maxExtAdvEvents,
- IdStatusCallback timeout_cb) {
+ IdStatusCallback /* timeout_cb */) {
LOG(INFO) << __func__ << " in shim layer";
bluetooth::hci::AdvertisingConfig config{};
@@ -175,7 +175,7 @@
void SetPeriodicAdvertisingParameters(
int advertiser_id, PeriodicAdvertisingParameters periodic_params,
- StatusCallback cb) override {
+ StatusCallback /* cb */) override {
LOG(INFO) << __func__ << " in shim layer";
bluetooth::hci::PeriodicAdvertisingParameters parameters;
parameters.max_interval = periodic_params.max_interval;
@@ -186,7 +186,7 @@
}
void SetPeriodicAdvertisingData(int advertiser_id, std::vector<uint8_t> data,
- StatusCallback cb) override {
+ StatusCallback /* cb */) override {
LOG(INFO) << __func__ << " in shim layer";
std::vector<GapData> advertising_data = {};
parse_gap_data(data, advertising_data);
@@ -196,7 +196,7 @@
void SetPeriodicAdvertisingEnable(int advertiser_id, bool enable,
bool include_adi,
- StatusCallback cb) override {
+ StatusCallback /* cb */) override {
LOG(INFO) << __func__ << " in shim layer";
bluetooth::shim::GetAdvertising()->EnablePeriodicAdvertising(
advertiser_id, enable, include_adi);
@@ -211,11 +211,11 @@
native_adv_callbacks_map_[client_id] = callbacks;
}
- void on_scan(Address address, AddressType address_type) {
+ void on_scan(Address /* address */, AddressType /* address_type */) {
LOG(INFO) << __func__ << " in shim layer";
}
- void on_set_terminated(ErrorCode error_code, uint8_t, uint8_t) {
+ void on_set_terminated(ErrorCode /* error_code */, uint8_t, uint8_t) {
LOG(INFO) << __func__ << " in shim layer";
}
diff --git a/system/main/shim/le_scanning_manager.cc b/system/main/shim/le_scanning_manager.cc
index 59d83912..58d0ef6 100644
--- a/system/main/shim/le_scanning_manager.cc
+++ b/system/main/shim/le_scanning_manager.cc
@@ -62,48 +62,58 @@
constexpr uint16_t kListLogicOr = 0x01;
class DefaultScanningCallback : public ::ScanningCallbacks {
- void OnScannerRegistered(const bluetooth::Uuid app_uuid, uint8_t scanner_id,
- uint8_t status) override {
+ void OnScannerRegistered(const bluetooth::Uuid /* app_uuid */,
+ uint8_t /* scanner_id */,
+ uint8_t /* status */) override {
LogUnused();
}
- void OnSetScannerParameterComplete(uint8_t scanner_id,
- uint8_t status) override {
+ void OnSetScannerParameterComplete(uint8_t /* scanner_id */,
+ uint8_t /* status */) override {
LogUnused();
}
- void OnScanResult(uint16_t event_type, uint8_t address_type, RawAddress bda,
- uint8_t primary_phy, uint8_t secondary_phy,
- uint8_t advertising_sid, int8_t tx_power, int8_t rssi,
- uint16_t periodic_advertising_interval,
- std::vector<uint8_t> advertising_data) override {
+ void OnScanResult(uint16_t /* event_type */, uint8_t /* address_type */,
+ RawAddress /* bda */, uint8_t /* primary_phy */,
+ uint8_t /* secondary_phy */, uint8_t /* advertising_sid */,
+ int8_t /* tx_power */, int8_t /* rssi */,
+ uint16_t /* periodic_advertising_interval */,
+ std::vector<uint8_t> /* advertising_data */) override {
LogUnused();
}
void OnTrackAdvFoundLost(
- AdvertisingTrackInfo advertising_track_info) override {
+ AdvertisingTrackInfo /* advertising_track_info */) override {
LogUnused();
}
- void OnBatchScanReports(int client_if, int status, int report_format,
- int num_records, std::vector<uint8_t> data) override {
+ void OnBatchScanReports(int /* client_if */, int /* status */,
+ int /* report_format */, int /* num_records */,
+ std::vector<uint8_t> /* data */) override {
LogUnused();
}
- void OnBatchScanThresholdCrossed(int client_if) override { LogUnused(); }
- void OnPeriodicSyncStarted(int reg_id, uint8_t status, uint16_t sync_handle,
- uint8_t advertising_sid, uint8_t address_type,
- RawAddress address, uint8_t phy,
- uint16_t interval) override {
+ void OnBatchScanThresholdCrossed(int /* client_if */) override {
+ LogUnused();
+ }
+ void OnPeriodicSyncStarted(int /* reg_id */, uint8_t /* status */,
+ uint16_t /* sync_handle */,
+ uint8_t /* advertising_sid */,
+ uint8_t /* address_type */,
+ RawAddress /* address */, uint8_t /* phy */,
+ uint16_t /* interval */) override {
LogUnused();
};
- void OnPeriodicSyncReport(uint16_t sync_handle, int8_t tx_power, int8_t rssi,
- uint8_t status,
- std::vector<uint8_t> data) override {
+ void OnPeriodicSyncReport(uint16_t /* sync_handle */, int8_t /* tx_power */,
+ int8_t /* rssi */, uint8_t /* status */,
+ std::vector<uint8_t> /* data */) override {
LogUnused();
};
- void OnPeriodicSyncLost(uint16_t sync_handle) override { LogUnused(); };
- void OnPeriodicSyncTransferred(int pa_source, uint8_t status,
- RawAddress address) override {
+ void OnPeriodicSyncLost(uint16_t /* sync_handle */) override { LogUnused(); };
+ void OnPeriodicSyncTransferred(int /* pa_source */, uint8_t /* status */,
+ RawAddress /* address */) override {
LogUnused();
};
- void OnBigInfoReport(uint16_t sync_handle, bool encrypted) override {LogUnused(); };
+ void OnBigInfoReport(uint16_t /* sync_handle */,
+ bool /* encrypted */) override {
+ LogUnused();
+ };
private:
static void LogUnused() {
@@ -255,8 +265,8 @@
}
/** Clear all scan filter conditions for specific filter index*/
-void BleScannerInterfaceImpl::ScanFilterClear(int filter_index,
- FilterConfigCallback cb) {
+void BleScannerInterfaceImpl::ScanFilterClear(int /* filter_index */,
+ FilterConfigCallback /* cb */) {
LOG(INFO) << __func__ << " in shim layer";
// This function doesn't used in java layer
}
@@ -339,8 +349,10 @@
/** Sets the LE scan interval and window in units of N*0.625 msec */
void BleScannerInterfaceImpl::SetScanParameters(int scanner_id,
+ uint8_t scan_type,
int scan_interval,
- int scan_window, Callback cb) {
+ int scan_window,
+ Callback /* cb */) {
LOG(INFO) << __func__ << " in shim layer";
if (BTM_BLE_ISVALID_PARAM(scan_interval, BTM_BLE_SCAN_INT_MIN,
BTM_BLE_EXT_SCAN_INT_MAX) &&
@@ -351,10 +363,9 @@
btm_cb.ble_ctr_cb.inq_var.scan_window = scan_window;
}
- // use active scan
- auto scan_type = static_cast<bluetooth::hci::LeScanType>(0x01);
- bluetooth::shim::GetScanning()->SetScanParameters(scanner_id, scan_type,
- scan_interval, scan_window);
+ bluetooth::shim::GetScanning()->SetScanParameters(
+ scanner_id, static_cast<bluetooth::hci::LeScanType>(scan_type),
+ scan_interval, scan_window);
}
/* Configure the batchscan storage */
@@ -371,7 +382,8 @@
/* Enable batchscan */
void BleScannerInterfaceImpl::BatchscanEnable(int scan_mode, int scan_interval,
- int scan_window, int addr_type,
+ int scan_window,
+ int /* addr_type */,
int discard_rule, Callback cb) {
LOG(INFO) << __func__ << " in shim layer";
auto batch_scan_mode = static_cast<bluetooth::hci::BatchScanMode>(scan_mode);
@@ -653,14 +665,15 @@
}
void BleScannerInterfaceImpl::OnTimeout() {}
-void BleScannerInterfaceImpl::OnFilterEnable(bluetooth::hci::Enable enable,
- uint8_t status) {}
+void BleScannerInterfaceImpl::OnFilterEnable(
+ bluetooth::hci::Enable /* enable */, uint8_t /* status */) {}
void BleScannerInterfaceImpl::OnFilterParamSetup(
- uint8_t available_spaces, bluetooth::hci::ApcfAction action,
- uint8_t status) {}
+ uint8_t /* available_spaces */, bluetooth::hci::ApcfAction /* action */,
+ uint8_t /* status */) {}
void BleScannerInterfaceImpl::OnFilterConfigCallback(
- bluetooth::hci::ApcfFilterType filter_type, uint8_t available_spaces,
- bluetooth::hci::ApcfAction action, uint8_t status) {}
+ bluetooth::hci::ApcfFilterType /* filter_type */,
+ uint8_t /* available_spaces */, bluetooth::hci::ApcfAction /* action */,
+ uint8_t /* status */) {}
bool BleScannerInterfaceImpl::parse_filter_command(
bluetooth::hci::AdvertisingPacketContentFilterCommand&
diff --git a/system/main/shim/stack.cc b/system/main/shim/stack.cc
index a509b0f..615119e 100644
--- a/system/main/shim/stack.cc
+++ b/system/main/shim/stack.cc
@@ -112,7 +112,7 @@
stack_manager_.StartUp(const_cast<ModuleList*>(modules), stack_thread_);
stack_handler_ = new os::Handler(stack_thread_);
- Start(const_cast<ModuleList*>(modules));
+ num_modules_ = modules->NumModules();
is_running_ = true;
}
diff --git a/system/main/shim/stack.h b/system/main/shim/stack.h
index ae47505..d4a18f3 100644
--- a/system/main/shim/stack.h
+++ b/system/main/shim/stack.h
@@ -63,6 +63,19 @@
// Start the list of modules with the given stack manager thread
void StartModuleStack(const ModuleList* modules, const os::Thread* thread);
+ // Run the callable object on the module instance
+ template <typename T>
+ bool CallOnModule(std::function<void(T* mod)> run) {
+ std::lock_guard<std::recursive_mutex> lock(Stack::GetInstance()->mutex_);
+ if (Stack::GetInstance()->is_running_) {
+ run(Stack::GetInstance()->GetStackManager()->GetInstance<T>());
+ return true;
+ }
+ return false;
+ }
+
+ size_t NumModules() const { return num_modules_; }
+
private:
mutable std::recursive_mutex mutex_;
StackManager stack_manager_;
@@ -71,7 +84,7 @@
os::Handler* stack_handler_ = nullptr;
legacy::Acl* acl_ = nullptr;
Btm* btm_ = nullptr;
-
+ size_t num_modules_{0};
void Start(ModuleList* modules);
};
diff --git a/system/main/shim/utils.cc b/system/main/shim/utils.cc
index 9f18ddc..c660ecd 100644
--- a/system/main/shim/utils.cc
+++ b/system/main/shim/utils.cc
@@ -14,8 +14,12 @@
* limitations under the License.
*/
+#define LOG_TAG "shim"
+
#include "utils.h"
+#include "os/log.h"
+
namespace bluetooth {
namespace shim {
void parse_gap_data(const std::vector<uint8_t> &raw_data,
@@ -26,6 +30,7 @@
uint8_t len = raw_data[offset];
if (offset + len + 1 > raw_data.size()) {
+ LOG_WARN("GAP data out of bound");
break;
}
diff --git a/system/main/stack_config.cc b/system/main/stack_config.cc
index 8b04960..4f0e86c 100644
--- a/system/main/stack_config.cc
+++ b/system/main/stack_config.cc
@@ -23,8 +23,8 @@
#include <base/logging.h>
#include "include/check.h"
+#include "os/log.h"
#include "osi/include/future.h"
-#include "osi/include/log.h"
namespace {
const char* PTS_AVRCP_TEST = "PTS_AvrcpTest";
diff --git a/system/main/test/main_shim_stack_lifecycle_test.cc b/system/main/test/main_shim_stack_lifecycle_test.cc
new file mode 100644
index 0000000..39c9636
--- /dev/null
+++ b/system/main/test/main_shim_stack_lifecycle_test.cc
@@ -0,0 +1,655 @@
+/*
+ * Copyright 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at:
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <bluetooth/log.h>
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <unistd.h>
+
+#include <atomic>
+#include <cstdlib>
+#include <memory>
+#include <thread>
+
+#include "common/strings.h"
+#include "gd/module_jniloop.h"
+#include "gd/module_mainloop.h"
+#include "main/shim/stack.h"
+#include "module.h"
+#include "os/thread.h"
+#include "stack/include/main_thread.h"
+#include "test/mock/mock_main_shim_entry.h"
+
+using ::testing::_;
+
+using namespace bluetooth;
+using namespace testing;
+
+namespace {
+constexpr int kSyncMainLoopTimeoutMs = 3000;
+constexpr int kWaitUntilHandlerStoppedMs = 2000;
+constexpr size_t kNumTestClients = 3;
+constexpr size_t kNumTestModules = 3;
+constexpr int kNumIters = 100;
+constexpr int kAbruptStackShutdownIter = kNumIters * 3 / 4;
+constexpr char kTestStackThreadName[] = "test_stack_thread";
+constexpr char kTestDataTag[] = "This is a test";
+
+inline void maybe_yield() {
+ if (std::rand() & 1) std::this_thread::yield();
+}
+
+constexpr size_t kTagLength = 48 + sizeof(' ') + sizeof(' ');
+inline void log_tag(std::string tag) {
+ std::string prepend(kTagLength / 2 - tag.size() / 2, '=');
+ std::string append(kTagLength / 2 - tag.size() / 2, '=');
+ log::info("{} {} {}", prepend, tag, append);
+}
+
+class MainThread {
+ public:
+ MainThread() { main_thread_start_up(); }
+
+ ~MainThread() {
+ sync_main_handler();
+ main_thread_shut_down();
+ }
+
+ private:
+ void sync_main_handler() {
+ std::promise promise = std::promise<void>();
+ std::future future = promise.get_future();
+ post_on_bt_main([&promise]() { promise.set_value(); });
+ future.wait_for(std::chrono::milliseconds(kSyncMainLoopTimeoutMs));
+ }
+};
+
+class TestStackManager {
+ public:
+ TestStackManager() {
+ // Start is executed by the test after each test adds the default
+ // or their own modules
+ }
+
+ ~TestStackManager() {
+ log::debug("Deleting stack manager");
+ Stop();
+ }
+
+ TestStackManager(const TestStackManager&) = delete;
+
+ template <typename T>
+ void AddModule() {
+ modules_.add<T>();
+ }
+
+ void Start() {
+ if (stack_started_) return;
+ log::info("Started stack manager");
+ stack_started_ = true;
+ bluetooth::os::Thread* stack_thread = new bluetooth::os::Thread(
+ kTestStackThreadName, bluetooth::os::Thread::Priority::NORMAL);
+ bluetooth::shim::Stack::GetInstance()->StartModuleStack(&modules_,
+ stack_thread);
+ }
+
+ void Stop() {
+ if (!stack_started_) return;
+ stack_started_ = false;
+ bluetooth::shim::Stack::GetInstance()->Stop();
+ }
+
+ // NOTE: Stack manager *must* be active else method returns nullptr
+ // if stack manager has not started or shutdown
+ template <typename T>
+ static T* GetUnsafeModule() {
+ return bluetooth::shim::Stack::GetInstance()
+ ->GetStackManager()
+ ->GetInstance<T>();
+ }
+
+ size_t NumModules() const { return modules_.NumModules(); }
+
+ private:
+ bluetooth::ModuleList modules_;
+ bool stack_started_{false};
+};
+
+// Data returned via callback from a stack managed module
+struct TestCallbackData {
+ int iter;
+ std::string tag;
+};
+
+// Data sent to a stack managed module via a module API
+struct TestData {
+ int iter;
+ std::string tag;
+ std::function<void(TestCallbackData callback_data)> callback;
+};
+
+class TestStackModuleBase : public bluetooth::Module,
+ public ModuleMainloop,
+ public ModuleJniloop {
+ public:
+ TestStackModuleBase(const TestStackModuleBase&) = delete;
+ TestStackModuleBase& operator=(const TestStackModuleBase&) = delete;
+
+ virtual ~TestStackModuleBase(){};
+ static const ModuleFactory Factory;
+
+ virtual void TestMethod(TestData test_data) const {
+ log::info("Test base class iter:{} tag:{}", test_data.iter,
+ test_data.tag.c_str());
+ }
+
+ protected:
+ void ListDependencies(ModuleList* list) const override{};
+ void Start() override { log::error("Started TestStackModuleBase"); };
+ void Stop() override { log::error("Stopped TestStackModuleBase"); };
+ std::string ToString() const override { return std::string("TestFunction"); }
+
+ TestStackModuleBase() = default;
+};
+
+class TestStackModule1 : public TestStackModuleBase {
+ public:
+ TestStackModule1(const TestStackModule1&) = delete;
+ TestStackModule1& operator=(const TestStackModule1&) = delete;
+ virtual ~TestStackModule1() = default;
+
+ static const ModuleFactory Factory;
+
+ void TestMethod(TestData test_data) const override;
+
+ private:
+ struct impl;
+ std::shared_ptr<impl> impl_;
+ TestStackModule1();
+};
+
+struct TestStackModule1::impl : public ModuleMainloop, public ModuleJniloop {
+ void test(TestData test_data) {
+ TestCallbackData callback_data{
+ .iter = test_data.iter,
+ .tag = std::string(__func__),
+ };
+ PostFunctionOnMain(
+ [](std::function<void(TestCallbackData callback_data)> callback,
+ TestCallbackData data) { callback(data); },
+ test_data.callback, callback_data);
+ }
+};
+
+TestStackModule1::TestStackModule1() : TestStackModuleBase() {
+ impl_ = std::make_shared<impl>();
+}
+
+void TestStackModule1::TestMethod(TestData test_data) const {
+ PostMethodOnMain(impl_, &impl::test, test_data);
+}
+
+class TestStackModule2 : public TestStackModuleBase {
+ public:
+ TestStackModule2(const TestStackModule2&) = delete;
+ TestStackModule2& operator=(const TestStackModule2&) = delete;
+ virtual ~TestStackModule2() = default;
+
+ static const ModuleFactory Factory;
+
+ void TestMethod(TestData test_data) const override;
+
+ private:
+ struct impl;
+ std::shared_ptr<impl> impl_;
+ TestStackModule2();
+};
+
+struct TestStackModule2::impl : public ModuleMainloop, public ModuleJniloop {
+ void test(TestData test_data) {
+ TestCallbackData callback_data{
+ .iter = test_data.iter,
+ .tag = std::string(__func__),
+ };
+ PostFunctionOnMain(
+ [](std::function<void(TestCallbackData callback_data)> callback,
+ TestCallbackData data) { callback(data); },
+ test_data.callback, callback_data);
+ }
+};
+
+TestStackModule2::TestStackModule2() : TestStackModuleBase() {
+ impl_ = std::make_shared<impl>();
+}
+
+void TestStackModule2::TestMethod(TestData test_data) const {
+ PostMethodOnMain(impl_, &impl::test, test_data);
+}
+
+class TestStackModule3 : public TestStackModuleBase {
+ public:
+ TestStackModule3(const TestStackModule3&) = delete;
+ TestStackModule3& operator=(const TestStackModule3&) = delete;
+ virtual ~TestStackModule3() = default;
+
+ static const ModuleFactory Factory;
+
+ void TestMethod(TestData test_data) const override;
+
+ private:
+ struct impl;
+ std::shared_ptr<impl> impl_;
+ TestStackModule3();
+};
+
+struct TestStackModule3::impl : public ModuleMainloop, public ModuleJniloop {
+ void test(TestData test_data) {
+ TestCallbackData callback_data{
+ .iter = test_data.iter,
+ .tag = std::string(__func__),
+ };
+ PostFunctionOnMain(
+ [](std::function<void(TestCallbackData callback_data)> callback,
+ TestCallbackData data) { callback(data); },
+ test_data.callback, callback_data);
+ }
+};
+
+TestStackModule3::TestStackModule3() : TestStackModuleBase() {
+ impl_ = std::make_shared<impl>();
+}
+
+void TestStackModule3::TestMethod(TestData test_data) const {
+ PostMethodOnMain(impl_, &impl::test, test_data);
+}
+
+class TestStackModule4 : public TestStackModuleBase {
+ public:
+ TestStackModule4(const TestStackModule4&) = delete;
+ TestStackModule4& operator=(const TestStackModule3&) = delete;
+ virtual ~TestStackModule4() = default;
+
+ static const ModuleFactory Factory;
+
+ void TestMethod(TestData test_data) const override {
+ log::info("mod:{} iter:{} tag:{}", __func__, test_data.iter,
+ test_data.tag.c_str());
+ }
+
+ private:
+ struct impl;
+ std::shared_ptr<impl> impl_;
+ TestStackModule4() : TestStackModuleBase() {}
+};
+
+struct TestStackModule4::impl : public ModuleMainloop, public ModuleJniloop {};
+
+} // namespace
+
+const ModuleFactory TestStackModuleBase::Factory =
+ ModuleFactory([]() { return new TestStackModuleBase(); });
+
+const ModuleFactory TestStackModule1::Factory =
+ ModuleFactory([]() { return new TestStackModule1(); });
+const ModuleFactory TestStackModule2::Factory =
+ ModuleFactory([]() { return new TestStackModule2(); });
+const ModuleFactory TestStackModule3::Factory =
+ ModuleFactory([]() { return new TestStackModule3(); });
+const ModuleFactory TestStackModule4::Factory =
+ ModuleFactory([]() { return new TestStackModule4(); });
+
+class StackWithMainThreadUnitTest : public ::testing::Test {
+ protected:
+ void SetUp() override { main_thread_ = std::make_unique<MainThread>(); }
+ void TearDown() override { main_thread_.reset(); }
+
+ private:
+ std::unique_ptr<MainThread> main_thread_;
+};
+
+class StackLifecycleUnitTest : public StackWithMainThreadUnitTest {
+ public:
+ std::shared_ptr<TestStackManager> StackManager() const {
+ return stack_manager_;
+ }
+
+ protected:
+ void SetUp() override {
+ StackWithMainThreadUnitTest::SetUp();
+ stack_manager_ = std::make_shared<TestStackManager>();
+ }
+
+ void TearDown() override {
+ stack_manager_.reset();
+ StackWithMainThreadUnitTest::TearDown();
+ }
+
+ private:
+ std::shared_ptr<TestStackManager> stack_manager_;
+};
+
+TEST_F(StackLifecycleUnitTest, no_modules_in_stack) {
+ ASSERT_EQ(0U, StackManager()->NumModules());
+}
+
+class StackLifecycleWithDefaultModulesUnitTest : public StackLifecycleUnitTest {
+ protected:
+ void SetUp() override {
+ StackLifecycleUnitTest::SetUp();
+ StackManager()->AddModule<TestStackModule1>();
+ StackManager()->AddModule<TestStackModule2>();
+ StackManager()->AddModule<TestStackModule3>();
+ StackManager()->Start();
+ ASSERT_EQ(3U, StackManager()->NumModules());
+ }
+
+ void TearDown() override { StackLifecycleUnitTest::TearDown(); }
+};
+
+struct CallablePostCnt {
+ size_t success{0};
+ size_t misses{0};
+ CallablePostCnt operator+=(const CallablePostCnt& post_cnt) {
+ return CallablePostCnt(
+ {success += post_cnt.success, misses += post_cnt.misses});
+ }
+};
+
+// Provide a client user of the stack manager module services
+class Client {
+ public:
+ Client(int id) : id_(id) {}
+ Client(const Client&) = default;
+ virtual ~Client() = default;
+
+ // Start up the client a thread and handler
+ void Start() {
+ log::info("Started client {}", id_);
+ thread_ = new os::Thread(common::StringFormat("ClientThread%d", id_),
+ os::Thread::Priority::NORMAL);
+ handler_ = new os::Handler(thread_);
+ handler_->Post(common::BindOnce(
+ [](int id) { log::info("Started client {}", id); }, id_));
+ }
+
+ // Ensure all the client handlers are running
+ void Await() {
+ std::promise<void> promise;
+ std::future future = promise.get_future();
+ handler_->Post(
+ base::BindOnce([](std::promise<void> promise) { promise.set_value(); },
+ std::move(promise)));
+ future.wait();
+ }
+
+ // Post a work task on behalf of this client
+ void Post(common::OnceClosure closure) {
+ if (quiesced_) {
+ post_cnt_.misses++;
+ maybe_yield();
+ } else {
+ post_cnt_.success++;
+ handler_->Post(std::move(closure));
+ maybe_yield();
+ }
+ }
+
+ // Safely prevent new work tasks from being posted
+ void Quiesce() {
+ if (quiesced_) return;
+ quiesced_ = true;
+ std::promise promise = std::promise<void>();
+ std::future future = promise.get_future();
+ handler_->Post(common::BindOnce(
+ [](std::promise<void> promise) { promise.set_value(); },
+ std::move(promise)));
+ future.wait_for(std::chrono::milliseconds(kSyncMainLoopTimeoutMs));
+ }
+
+ // Stops the client and associated resources
+ void Stop() {
+ if (!quiesced_) {
+ Quiesce();
+ }
+ handler_->Clear();
+ handler_->WaitUntilStopped(
+ std::chrono::milliseconds(kWaitUntilHandlerStoppedMs));
+ delete handler_;
+ delete thread_;
+ }
+
+ int Id() const { return id_; }
+
+ CallablePostCnt GetCallablePostCnt() const { return post_cnt_; }
+
+ std::string Name() const {
+ return common::StringFormat("%s%d", __func__, id_);
+ }
+
+ private:
+ int id_{0};
+ CallablePostCnt post_cnt_{};
+ bool quiesced_{false};
+ os::Handler* handler_{nullptr};
+ os::Thread* thread_{nullptr};
+};
+
+// Convenience object to handle multiple clients with logging
+class ClientGroup {
+ public:
+ ClientGroup(){};
+
+ void Start() {
+ for (auto& c : clients_) {
+ c->Start();
+ }
+ log_tag("STARTING");
+ }
+
+ void Await() {
+ for (auto& c : clients_) {
+ c->Await();
+ }
+ log_tag("STARTED");
+ }
+
+ void Quiesce() {
+ log_tag("QUIESCING");
+ for (auto& c : clients_) {
+ c->Quiesce();
+ }
+ log_tag("QUIESCED");
+ }
+
+ void Stop() {
+ for (auto& c : clients_) {
+ c->Stop();
+ }
+ log_tag("STOPPED");
+ }
+
+ void Dump() const {
+ for (auto& c : clients_) {
+ log::info("Callable post cnt client_id:{} success:{} misses:{}", c->Id(),
+ c->GetCallablePostCnt().success,
+ c->GetCallablePostCnt().misses);
+ }
+ }
+
+ CallablePostCnt GetCallablePostCnt() const {
+ CallablePostCnt post_cnt{};
+ for (auto& c : clients_) {
+ post_cnt += c->GetCallablePostCnt();
+ }
+ return post_cnt;
+ }
+
+ size_t NumClients() const { return kNumTestClients; }
+
+ std::unique_ptr<Client> clients_[kNumTestClients] = {
+ std::make_unique<Client>(1), std::make_unique<Client>(2),
+ std::make_unique<Client>(3)};
+};
+
+TEST_F(StackLifecycleWithDefaultModulesUnitTest, clients_start) {
+ ClientGroup client_group;
+
+ client_group.Start();
+ client_group.Await();
+
+ // Clients are operational
+
+ client_group.Quiesce();
+ client_group.Stop();
+}
+
+TEST_F(StackLifecycleWithDefaultModulesUnitTest, client_using_stack_manager) {
+ ClientGroup client_group;
+ client_group.Start();
+ client_group.Await();
+
+ for (int i = 0; i < kNumIters; i++) {
+ for (auto& c : client_group.clients_) {
+ c->Post(base::BindOnce(
+ [](int id, int iter,
+ std::shared_ptr<TestStackManager> stack_manager) {
+ stack_manager->GetUnsafeModule<TestStackModule1>()->TestMethod({
+ .iter = iter,
+ .tag = std::string(kTestDataTag),
+ .callback = [](TestCallbackData data) {},
+ });
+ },
+ c->Id(), i, StackManager()));
+ c->Post(base::BindOnce(
+ [](int id, int iter,
+ std::shared_ptr<TestStackManager> stack_manager) {
+ stack_manager->GetUnsafeModule<TestStackModule2>()->TestMethod({
+ .iter = iter,
+ .tag = std::string(kTestDataTag),
+ .callback = [](TestCallbackData data) {},
+ });
+ },
+ c->Id(), i, StackManager()));
+ c->Post(base::BindOnce(
+ [](int id, int iter,
+ std::shared_ptr<TestStackManager> stack_manager) {
+ stack_manager->GetUnsafeModule<TestStackModule3>()->TestMethod({
+ .iter = iter,
+ .tag = std::string(kTestDataTag),
+ .callback = [](TestCallbackData data) {},
+ });
+ },
+ c->Id(), i, StackManager()));
+ }
+ }
+
+ client_group.Quiesce();
+ client_group.Stop();
+ client_group.Dump();
+
+ ASSERT_EQ(client_group.NumClients() * kNumIters * kNumTestModules,
+ client_group.GetCallablePostCnt().success +
+ client_group.GetCallablePostCnt().misses);
+}
+
+TEST_F(StackLifecycleWithDefaultModulesUnitTest,
+ client_using_stack_manager_when_shutdown) {
+ struct Counters {
+ struct {
+ std::atomic_size_t cnt{0};
+ } up, down;
+ } counters;
+
+ ClientGroup client_group;
+ client_group.Start();
+ client_group.Await();
+
+ for (int i = 0; i < kNumIters; i++) {
+ for (auto& c : client_group.clients_) {
+ c->Post(base::BindOnce(
+ [](int id, int iter, Counters* counters,
+ std::shared_ptr<TestStackManager> stack_manager) {
+ TestData test_data = {
+ .iter = iter,
+ .tag = std::string(kTestDataTag),
+ .callback = [](TestCallbackData data) {},
+ };
+ if (bluetooth::shim::Stack::GetInstance()
+ ->CallOnModule<TestStackModule1>(
+ [test_data](TestStackModule1* mod) {
+ mod->TestMethod(test_data);
+ })) {
+ counters->up.cnt++;
+ } else {
+ counters->down.cnt++;
+ }
+ },
+ c->Id(), i, &counters, StackManager()));
+ c->Post(base::BindOnce(
+ [](int id, int iter, Counters* counters,
+ std::shared_ptr<TestStackManager> stack_manager) {
+ TestData test_data = {
+ .iter = iter,
+ .tag = std::string(kTestDataTag),
+ .callback = [](TestCallbackData data) {},
+ };
+ if (bluetooth::shim::Stack::GetInstance()
+ ->CallOnModule<TestStackModule2>(
+ [test_data](TestStackModule2* mod) {
+ mod->TestMethod(test_data);
+ })) {
+ counters->up.cnt++;
+ } else {
+ counters->down.cnt++;
+ }
+ },
+ c->Id(), i, &counters, StackManager()));
+ c->Post(base::BindOnce(
+ [](int id, int iter, Counters* counters,
+ std::shared_ptr<TestStackManager> stack_manager) {
+ TestData test_data = {
+ .iter = iter,
+ .tag = std::string(kTestDataTag),
+ .callback = [](TestCallbackData data) {},
+ };
+ if (bluetooth::shim::Stack::GetInstance()
+ ->CallOnModule<TestStackModule3>(
+ [test_data](TestStackModule3* mod) {
+ mod->TestMethod(test_data);
+ })) {
+ counters->up.cnt++;
+ } else {
+ counters->down.cnt++;
+ }
+ },
+ c->Id(), i, &counters, StackManager()));
+ }
+ // Abruptly shutdown stack at some point through the iterations
+ if (i == kAbruptStackShutdownIter) {
+ log_tag("SHUTTING DOWN STACK");
+ StackManager()->Stop();
+ }
+ }
+
+ client_group.Quiesce();
+ client_group.Stop();
+ log::info("Execution stack availability counters up:{} down:{}",
+ counters.up.cnt, counters.down.cnt);
+
+ ASSERT_EQ(client_group.NumClients() * kNumIters * kNumTestModules,
+ client_group.GetCallablePostCnt().success +
+ client_group.GetCallablePostCnt().misses);
+}
diff --git a/system/osi/BUILD.gn b/system/osi/BUILD.gn
index 1c03506..0fc0671 100644
--- a/system/osi/BUILD.gn
+++ b/system/osi/BUILD.gn
@@ -61,6 +61,7 @@
configs += [
"//bt/system:target_defaults",
+ "//bt/system/log:log_defaults",
]
}
diff --git a/system/osi/include/log.h b/system/osi/include/log.h
deleted file mode 100644
index e2fe11f..0000000
--- a/system/osi/include/log.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/******************************************************************************
- *
- * Copyright 2014 Google, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************************/
-
-#pragma once
-
-#include "common/init_flags.h"
-
-#ifndef OSI_INCLUDE_LOG_H
-#define OSI_INCLUDE_LOG_H
-#endif
-
-#include "os/log.h"
-
-#undef OSI_INCLUDE_LOG_H
\ No newline at end of file
diff --git a/system/osi/src/future.cc b/system/osi/src/future.cc
index fe97b9c..ece49c7 100644
--- a/system/osi/src/future.cc
+++ b/system/osi/src/future.cc
@@ -23,8 +23,8 @@
#include <base/logging.h>
#include "check.h"
+#include "os/log.h"
#include "osi/include/allocator.h"
-#include "osi/include/log.h"
#include "osi/include/osi.h"
#include "osi/semaphore.h"
diff --git a/system/pdl/hci/hci_packets.pdl b/system/pdl/hci/hci_packets.pdl
index 15e9478..212cd29 100644
--- a/system/pdl/hci/hci_packets.pdl
+++ b/system/pdl/hci/hci_packets.pdl
@@ -5325,6 +5325,11 @@
"\x0e\x1c\x01\x53\xfd\x00\x10\x01\x00\x28\x00\x01\x3e\x01\x03\x01\x14\x00\x01\x01\x00\x23\x00\x00\x00\x01\x23\x00\x00\x00",
}
+packet LeGetVendorCapabilitiesComplete104 : LeGetVendorCapabilitiesComplete103 {
+ a2dp_offload_v2_support : 8,
+ _payload_,
+}
+
enum SubOcf : 8 {
SET_PARAM = 0x01,
SET_DATA = 0x02,
diff --git a/system/profile/avrcp/tests/avrcp_connection_handler_test.cc b/system/profile/avrcp/tests/avrcp_connection_handler_test.cc
index 957fdb3..7b3ea7b 100644
--- a/system/profile/avrcp/tests/avrcp_connection_handler_test.cc
+++ b/system/profile/avrcp/tests/avrcp_connection_handler_test.cc
@@ -15,14 +15,13 @@
*/
#include <base/functional/bind.h>
-#include <base/logging.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
-#include "sdpdefs.h"
#include "avrcp_internal.h"
#include "avrcp_test_helper.h"
#include "connection_handler.h"
+#include "sdpdefs.h"
#include "types/raw_address.h"
using ::testing::_;
diff --git a/system/profile/avrcp/tests/avrcp_device_test.cc b/system/profile/avrcp/tests/avrcp_device_test.cc
index 7216a5d..52672ba 100644
--- a/system/profile/avrcp/tests/avrcp_device_test.cc
+++ b/system/profile/avrcp/tests/avrcp_device_test.cc
@@ -15,7 +15,6 @@
*/
#include <base/functional/bind.h>
-#include <base/logging.h>
#include <base/threading/thread.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
diff --git a/system/profile/sdp/Android.bp b/system/profile/sdp/Android.bp
index fe68a2b..88e4916 100644
--- a/system/profile/sdp/Android.bp
+++ b/system/profile/sdp/Android.bp
@@ -23,6 +23,7 @@
static_libs: [
"lib-bt-packets",
"libbluetooth-types",
+ "libbluetooth_log",
],
header_libs: ["libbluetooth_headers"],
}
@@ -47,9 +48,13 @@
"lib-bt-packets-avrcp",
"lib-bt-packets-base",
"libbluetooth-types",
+ "libbluetooth_log",
"libchrome",
"libgmock",
"sdp_service",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
diff --git a/system/profile/sdp/common/data_element_reader.cc b/system/profile/sdp/common/data_element_reader.cc
index 992e7c8..5bba190 100644
--- a/system/profile/sdp/common/data_element_reader.cc
+++ b/system/profile/sdp/common/data_element_reader.cc
@@ -16,7 +16,7 @@
#include "data_element_reader.h"
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include <type_traits>
@@ -27,19 +27,19 @@
// reader to extract without overflowing. end_ - it_ should never be negative
// so casting it to a size_t is always safe. If it does fail, set it_ to end_
// so that all additional readings fail.
-#define CHECK_REMAINING_LEN(x) \
- do { \
- if ((size_t)(end_ - it_) < x) { \
- LOG(WARNING) << __func__ << ": Extract would read past end of data."; \
- return ParseFail(); \
- } \
+#define CHECK_REMAINING_LEN(x) \
+ do { \
+ if ((size_t)(end_ - it_) < x) { \
+ log::warn("Extract would read past end of data."); \
+ return ParseFail(); \
+ } \
} while (0)
namespace bluetooth {
namespace sdp {
DataElementReader::DataElement DataElementReader::ReadNext() {
- if (it_ > end_) LOG(FATAL) << "Beginning of buffer is past end of buffer.";
+ if (it_ > end_) log::fatal("Beginning of buffer is past end of buffer.");
if (it_ == end_) return std::monostate();
uint8_t descriptor = *it_++;
@@ -48,14 +48,14 @@
// All types with a value greater than URL are currently reserved.
if (type > DataElementType::MAX_VALUE) {
- LOG(WARNING) << __func__ << ": Trying to use a reserved data element type";
+ log::warn("Trying to use a reserved data element type");
return ParseFail();
}
switch (type) {
case DataElementType::BOOLEAN:
if (size != DataElementSize::BYTE1) {
- LOG(WARNING) << __func__ << ": Invalid size for bool: " << size;
+ log::warn("Invalid size for bool: {}", size);
return ParseFail();
}
@@ -75,7 +75,7 @@
// TODO: The other data element types are never used in the previous SDP
// implementation. We should properly handle them in the future though
// for completeness.
- LOG(ERROR) << __func__ << ": Unhandled Data Element Type: " << type;
+ log::error("Unhandled Data Element Type: {}", type);
}
return ParseFail();
@@ -120,7 +120,7 @@
case DataElementSize::BYTE16:
return ReadLargeInt();
default:
- LOG(WARNING) << __func__ << ": Invalid size for int: " << size;
+ log::warn("Invalid size for int: {}", size);
}
return ParseFail();
@@ -140,7 +140,7 @@
case DataElementSize::BYTE16:
return ReadLargeInt();
default:
- LOG(WARNING) << __func__ << ": Invalid size for uint: " << size;
+ log::warn("Invalid size for uint: {}", size);
}
return ParseFail();
@@ -169,7 +169,7 @@
return Uuid::From128BitBE(uuid_array);
}
- LOG(WARNING) << __func__ << ": Invalid size for UUID: " << size;
+ log::warn("Invalid size for UUID: {}", size);
return ParseFail();
}
@@ -191,7 +191,7 @@
num_bytes = it_.extractBE<uint32_t>();
break;
default:
- LOG(WARNING) << __func__ << ": Invalid size for string: " << size;
+ log::warn("Invalid size for string: {}", size);
return ParseFail();
}
@@ -223,7 +223,7 @@
num_bytes = it_.extractBE<uint32_t>();
break;
default:
- LOG(WARNING) << __func__ << ": Invalid size for string: " << size;
+ log::warn("Invalid size for string: {}", size);
return ParseFail();
}
diff --git a/system/profile/sdp/common/test/data_element_reader_test.cc b/system/profile/sdp/common/test/data_element_reader_test.cc
index 167f7d1..429eaba 100644
--- a/system/profile/sdp/common/test/data_element_reader_test.cc
+++ b/system/profile/sdp/common/test/data_element_reader_test.cc
@@ -16,7 +16,6 @@
#include "common/data_element_reader.h"
-#include <base/logging.h>
#include <gtest/gtest.h>
#include "types/bluetooth/uuid.h"
diff --git a/system/profile/sdp/sdp_logging_helper.h b/system/profile/sdp/sdp_logging_helper.h
index 253ce92..d556b6e 100644
--- a/system/profile/sdp/sdp_logging_helper.h
+++ b/system/profile/sdp/sdp_logging_helper.h
@@ -16,6 +16,8 @@
#pragma once
+#include <bluetooth/log.h>
+
#include <iomanip>
#include <iostream>
#include <sstream>
@@ -116,3 +118,14 @@
} // namespace sdp
} // namespace bluetooth
+
+namespace fmt {
+template <>
+struct formatter<bluetooth::sdp::PduId> : ostream_formatter {};
+template <>
+struct formatter<bluetooth::sdp::AttributeId> : ostream_formatter {};
+template <>
+struct formatter<bluetooth::sdp::DataElementType> : ostream_formatter {};
+template <>
+struct formatter<bluetooth::sdp::DataElementSize> : ostream_formatter {};
+} // namespace fmt
diff --git a/system/rust/BUILD.gn b/system/rust/BUILD.gn
index 48b94a5..202e9df 100644
--- a/system/rust/BUILD.gn
+++ b/system/rust/BUILD.gn
@@ -36,7 +36,10 @@
"//bt/system/types",
]
- configs += [ "//bt/system:target_defaults" ]
+ configs += [
+ "//bt/system:target_defaults",
+ "//bt/system/log:log_defaults",
+ ]
deps = [
":cxxlibheader",
diff --git a/system/rust/src/core/ffi/module.cc b/system/rust/src/core/ffi/module.cc
index b2c77c4..ace30e9 100644
--- a/system/rust/src/core/ffi/module.cc
+++ b/system/rust/src/core/ffi/module.cc
@@ -19,7 +19,7 @@
#include <hardware/bt_gatt.h>
#include "btcore/include/module.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#ifndef TARGET_FLOSS
#include "src/connection/ffi/connection_shim.h"
#include "src/core/ffi.rs.h"
diff --git a/system/stack/Android.bp b/system/stack/Android.bp
index 40c7998..0a3ee4b 100644
--- a/system/stack/Android.bp
+++ b/system/stack/Android.bp
@@ -235,6 +235,7 @@
"btm/btm_sec.cc",
"btm/btm_sec_cb.cc",
"btm/btm_security_client_interface.cc",
+ "btm/security_event_parser.cc",
"btu/btu_event.cc",
"btu/btu_hcif.cc",
"eatt/eatt.cc",
@@ -338,6 +339,7 @@
"libchrome",
],
shared_libs: [
+ "libbase",
"liblog",
],
target: {
@@ -428,6 +430,7 @@
"BluetoothGeneratedDumpsysDataSchema_h",
],
srcs: [
+ ":BluetoothPacketSources",
":TestCommonMockFunctions",
":TestCommonStackConfig",
":TestFakeOsi",
@@ -435,6 +438,7 @@
":TestMockDevice",
":TestMockGdOsLoggingLogRedaction",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
":TestMockRustFfi",
":TestMockSrvcDis",
":TestMockStackAcl",
@@ -481,6 +485,7 @@
"BluetoothGeneratedDumpsysDataSchema_h",
],
srcs: [
+ ":BluetoothPacketSources",
":TestCommonMockFunctions",
":TestCommonStackConfig",
":TestFakeOsi",
@@ -488,6 +493,7 @@
":TestMockDevice",
":TestMockGdOsLoggingLogRedaction",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
":TestMockStackAcl",
":TestMockStackBtm",
":TestMockStackHcic",
@@ -529,6 +535,7 @@
"BluetoothGeneratedDumpsysDataSchema_h",
],
srcs: [
+ ":BluetoothPacketSources",
":TestCommonMockFunctions",
":TestCommonStackConfig",
":TestFakeOsi",
@@ -536,6 +543,7 @@
":TestMockDevice",
":TestMockGdOsLoggingLogRedaction",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
":TestMockStackAcl",
":TestMockStackBtm",
":TestMockStackHcic",
@@ -572,6 +580,7 @@
"BluetoothGeneratedDumpsysDataSchema_h",
],
srcs: [
+ ":BluetoothPacketSources",
":TestCommonMockFunctions",
":TestCommonStackConfig",
":TestFakeOsi",
@@ -579,6 +588,7 @@
":TestMockDevice",
":TestMockGdOsLoggingLogRedaction",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
":TestMockStackAcl",
":TestMockStackBtm",
":TestMockStackHcic",
@@ -619,6 +629,7 @@
"BluetoothGeneratedDumpsysDataSchema_h",
],
srcs: [
+ ":BluetoothPacketSources",
":TestCommonMockFunctions",
":TestCommonStackConfig",
":TestFakeOsi",
@@ -626,6 +637,7 @@
":TestMockDevice",
":TestMockGdOsLoggingLogRedaction",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
":TestMockStackAcl",
":TestMockStackBtm",
":TestMockStackHcic",
@@ -681,6 +693,7 @@
"android.hardware.bluetooth.audio@2.1",
"libPlatformProperties",
"libaaudio",
+ "libbase",
"libbinder_ndk",
"libcrypto",
"libcutils",
@@ -765,6 +778,7 @@
":TestCommonMockFunctions",
":TestMockHci",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
":TestMockStackMetrics",
"rfcomm/port_api.cc",
"rfcomm/port_rfc.cc",
@@ -792,6 +806,7 @@
"libcutils",
],
static_libs: [
+ "libbase",
"libbluetooth-types",
"libbluetooth_crypto_toolbox",
"libbluetooth_gd",
@@ -852,6 +867,7 @@
":TestMockBtif",
":TestMockDevice",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
":TestMockStackAcl",
":TestMockStackBtm",
":TestMockStackHcic",
@@ -878,6 +894,7 @@
"server_configurable_flags",
],
static_libs: [
+ "libbase",
"libbluetooth-types",
"libbluetooth_crypto_toolbox",
"libbluetooth_gd",
@@ -963,6 +980,7 @@
"libcutils",
],
static_libs: [
+ "libbase",
"libbluetooth-types",
"libbluetooth_gd",
"libbluetooth_log",
@@ -1016,6 +1034,7 @@
"libcutils",
],
static_libs: [
+ "libbase",
"libbluetooth-types",
"libbluetooth_crypto_toolbox",
"libbluetooth_gd",
@@ -1086,6 +1105,7 @@
"libcutils",
],
static_libs: [
+ "libbase",
"libbluetooth-types",
"libbluetooth_crypto_toolbox",
"libbluetooth_gd",
@@ -1203,6 +1223,7 @@
],
static_libs: [
"libFraunhoferAAC",
+ "libbase",
"libbluetooth-types",
"libbluetooth_crypto_toolbox",
"libbluetooth_gd",
@@ -1259,6 +1280,7 @@
"libcutils",
],
static_libs: [
+ "libbase",
"libbluetooth_crypto_toolbox",
"libbluetooth_log",
"libbt-common",
@@ -1315,6 +1337,7 @@
"libcutils",
],
static_libs: [
+ "libbase",
"libbluetooth-types",
"libbluetooth_crypto_toolbox",
"libbluetooth_gd",
@@ -1364,9 +1387,11 @@
"packages/modules/Bluetooth/system/gd",
],
srcs: [
+ ":BluetoothPacketSources",
":TestCommonMockFunctions",
":TestCommonStackConfig",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
"btm/btm_iso.cc",
"test/btm_iso_test.cc",
"test/common/mock_controller.cc",
@@ -1374,6 +1399,7 @@
"test/common/mock_hcic_layer.cc",
],
static_libs: [
+ "libbase",
"libbluetooth-types",
"libbluetooth_hci_pdl",
"libbluetooth_log",
@@ -1441,6 +1467,7 @@
"libcutils",
],
static_libs: [
+ "libbase",
"libbluetooth-types",
"libbluetooth_gd",
"libbluetooth_log",
@@ -1506,6 +1533,7 @@
":TestMockLegacyHciInterface",
":TestMockMainBte",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
":TestMockRustFfi",
":TestMockStackBtu",
":TestMockStackGap",
@@ -1545,6 +1573,7 @@
"btm/hfp_lc3_encoder.cc",
"btm/hfp_msbc_decoder.cc",
"btm/hfp_msbc_encoder.cc",
+ "btm/security_event_parser.cc",
"metrics/stack_metrics_logging.cc",
"test/btm/peer_packet_types_test.cc",
"test/btm/sco_hci_test.cc",
@@ -1632,6 +1661,7 @@
"libosi",
],
shared_libs: [
+ "libPlatformProperties",
"libcrypto",
],
sanitize: {
@@ -1677,6 +1707,7 @@
"test/hid/stack_hid_test.cc",
],
static_libs: [
+ "libbase",
"libbluetooth-types",
"libbluetooth_crypto_toolbox",
"libbluetooth_log",
@@ -1694,6 +1725,7 @@
"libprotobuf-cpp-lite",
],
shared_libs: [
+ "libPlatformProperties",
"libcrypto",
],
target: {
@@ -1742,6 +1774,7 @@
":TestMockHci",
":TestMockLegacyHciCommands",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
":TestMockStackAcl",
":TestMockStackBtm",
":TestMockStackHcic",
@@ -1754,6 +1787,7 @@
"test/stack_btu_test.cc",
],
static_libs: [
+ "libbase",
"libbluetooth-types",
"libbluetooth_gd",
"libbluetooth_log",
@@ -1816,6 +1850,7 @@
":TestMockHci",
":TestMockLegacyHciCommands",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
":TestMockRustFfi",
":TestMockSrvcDis",
":TestMockStackAcl",
@@ -1840,6 +1875,7 @@
],
static_libs: [
"bluetooth_flags_c_lib",
+ "libbase",
"libbluetooth-types",
"libbluetooth_crypto_toolbox",
"libbluetooth_gd",
@@ -1912,8 +1948,10 @@
":TestMockBta",
":TestMockBtif",
":TestMockHci",
+ ":TestMockJni",
":TestMockLegacyHciCommands",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
":TestMockStackAcl",
":TestMockStackBtm",
":TestMockStackHcic",
@@ -2007,6 +2045,7 @@
":TestMockLegacyHciCommands",
":TestMockLegacyHciInterface",
":TestMockMainShim",
+ ":TestMockMainShimEntry",
":TestMockRustFfi",
":TestMockStackBtm",
":TestMockStackBtu",
@@ -2096,6 +2135,7 @@
"libcutils",
],
static_libs: [
+ "libbase",
"libbluetooth-types",
"libbluetooth_gd",
"libbluetooth_log",
diff --git a/system/stack/BUILD.gn b/system/stack/BUILD.gn
index 286c87d..07999bc 100644
--- a/system/stack/BUILD.gn
+++ b/system/stack/BUILD.gn
@@ -46,6 +46,7 @@
configs += [
"//bt/system:target_defaults",
+ "//bt/system/log:log_defaults",
]
}
}
@@ -113,6 +114,7 @@
"btm/btm_sec.cc",
"btm/btm_sec_cb.cc",
"btm/btm_security_client_interface.cc",
+ "btm/security_event_parser.cc",
"btm/hfp_lc3_encoder_linux.cc",
"btm/hfp_lc3_decoder_linux.cc",
"btm/hfp_msbc_encoder.cc",
@@ -225,6 +227,7 @@
configs += [
"//bt/system:target_defaults",
+ "//bt/system/log:log_defaults",
]
}
diff --git a/system/stack/a2dp/a2dp_aac.cc b/system/stack/a2dp/a2dp_aac.cc
index 52a14f4..05b7412 100644
--- a/system/stack/a2dp/a2dp_aac.cc
+++ b/system/stack/a2dp/a2dp_aac.cc
@@ -25,7 +25,7 @@
#include "a2dp_aac.h"
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include <string.h>
#include "a2dp_aac_decoder.h"
@@ -40,6 +40,8 @@
#define A2DP_AAC_DEFAULT_BITRATE 320000 // 320 kbps
#define A2DP_AAC_MIN_BITRATE 64000 // 64 kbps
+using namespace bluetooth;
+
// data type for the AAC Codec Information Element */
// NOTE: bits_per_sample is needed only for AAC encoder initialization.
typedef struct {
@@ -296,23 +298,22 @@
/* parse configuration */
status = A2DP_ParseInfoAac(&cfg_cie, p_codec_info, is_capability);
if (status != A2DP_SUCCESS) {
- LOG_ERROR("%s: parsing failed %d", __func__, status);
+ log::error("parsing failed {}", status);
return status;
}
/* verify that each parameter is in range */
- LOG_VERBOSE("%s: Object Type peer: 0x%x, capability 0x%x", __func__,
- cfg_cie.objectType, p_cap->objectType);
- LOG_VERBOSE("%s: Sample Rate peer: %u, capability %u", __func__,
- cfg_cie.sampleRate, p_cap->sampleRate);
- LOG_VERBOSE("%s: Channel Mode peer: 0x%x, capability 0x%x", __func__,
- cfg_cie.channelMode, p_cap->channelMode);
- LOG_VERBOSE("%s: Variable Bit Rate Support peer: 0x%x, capability 0x%x",
- __func__, cfg_cie.variableBitRateSupport,
- p_cap->variableBitRateSupport);
- LOG_VERBOSE("%s: Bit Rate peer: %u, capability %u", __func__, cfg_cie.bitRate,
- p_cap->bitRate);
+ log::verbose("Object Type peer: 0x{:x}, capability 0x{:x}",
+ cfg_cie.objectType, p_cap->objectType);
+ log::verbose("Sample Rate peer: {}, capability {}", cfg_cie.sampleRate,
+ p_cap->sampleRate);
+ log::verbose("Channel Mode peer: 0x{:x}, capability 0x{:x}",
+ cfg_cie.channelMode, p_cap->channelMode);
+ log::verbose("Variable Bit Rate Support peer: 0x{:x}, capability 0x{:x}",
+ cfg_cie.variableBitRateSupport, p_cap->variableBitRateSupport);
+ log::verbose("Bit Rate peer: {}, capability {}", cfg_cie.bitRate,
+ p_cap->bitRate);
/* Object Type */
if ((cfg_cie.objectType & p_cap->objectType) == 0) return A2DP_BAD_OBJ_TYPE;
@@ -344,12 +345,12 @@
tA2DP_STATUS a2dp_status =
A2DP_ParseInfoAac(&aac_cie_a, p_codec_info_a, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
a2dp_status = A2DP_ParseInfoAac(&aac_cie_b, p_codec_info_b, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
@@ -365,12 +366,12 @@
tA2DP_STATUS a2dp_status =
A2DP_ParseInfoAac(&aac_cie_a, p_codec_info_a, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
a2dp_status = A2DP_ParseInfoAac(&aac_cie_b, p_codec_info_b, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
@@ -388,7 +389,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoAac(&aac_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -428,7 +429,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoAac(&aac_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -442,7 +443,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoAac(&aac_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -462,7 +463,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoAac(&aac_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -482,7 +483,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoAac(&aac_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -505,7 +506,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoAac(&aac_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -526,7 +527,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoAac(&aac_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -547,7 +548,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoAac(&aac_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -560,7 +561,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoAac(&aac_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -797,7 +798,7 @@
// Load the encoder
if (!A2DP_LoadEncoderAac()) {
- LOG_ERROR("%s: cannot load the encoder", __func__);
+ log::error("cannot load the encoder");
return false;
}
@@ -1033,8 +1034,7 @@
tA2DP_STATUS status =
A2DP_ParseInfoAac(&peer_info_cie, p_peer_codec_info, is_capability);
if (status != A2DP_SUCCESS) {
- LOG_ERROR("%s: can't parse peer's capabilities: error = %d", __func__,
- status);
+ log::error("can't parse peer's capabilities: error = {}", status);
goto fail;
}
@@ -1171,10 +1171,10 @@
}
} while (false);
if (codec_config_.sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) {
- LOG_ERROR(
- "%s: cannot match sample frequency: source caps = 0x%x "
- "peer info = 0x%x",
- __func__, p_a2dp_aac_caps->sampleRate, peer_info_cie.sampleRate);
+ log::error(
+ "cannot match sample frequency: source caps = 0x{:x} peer info = "
+ "0x{:x}",
+ p_a2dp_aac_caps->sampleRate, peer_info_cie.sampleRate);
goto fail;
}
@@ -1246,10 +1246,10 @@
}
} while (false);
if (codec_config_.bits_per_sample == BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) {
- LOG_ERROR(
- "%s: cannot match bits per sample: default = 0x%x "
- "user preference = 0x%x",
- __func__, a2dp_aac_default_config.bits_per_sample,
+ log::error(
+ "cannot match bits per sample: default = 0x{:x} user preference = "
+ "0x{:x}",
+ a2dp_aac_default_config.bits_per_sample,
codec_user_config_.bits_per_sample);
goto fail;
}
@@ -1321,10 +1321,9 @@
}
} while (false);
if (codec_config_.channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) {
- LOG_ERROR(
- "%s: cannot match channel mode: source caps = 0x%x "
- "peer info = 0x%x",
- __func__, p_a2dp_aac_caps->channelMode, peer_info_cie.channelMode);
+ log::error(
+ "cannot match channel mode: source caps = 0x{:x} peer info = 0x{:x}",
+ p_a2dp_aac_caps->channelMode, peer_info_cie.channelMode);
goto fail;
}
@@ -1425,8 +1424,7 @@
tA2DP_STATUS status =
A2DP_ParseInfoAac(&peer_info_cie, p_peer_codec_capabilities, true);
if (status != A2DP_SUCCESS) {
- LOG_ERROR("%s: can't parse peer's capabilities: error = %d", __func__,
- status);
+ log::error("can't parse peer's capabilities: error = {}", status);
goto fail;
}
@@ -1501,7 +1499,7 @@
// Load the decoder
if (!A2DP_LoadDecoderAac()) {
- LOG_ERROR("%s: cannot load the decoder", __func__);
+ log::error("cannot load the decoder");
return false;
}
diff --git a/system/stack/a2dp/a2dp_aac_decoder.cc b/system/stack/a2dp/a2dp_aac_decoder.cc
index 639512b..b45bdce 100644
--- a/system/stack/a2dp/a2dp_aac_decoder.cc
+++ b/system/stack/a2dp/a2dp_aac_decoder.cc
@@ -19,7 +19,7 @@
#include "a2dp_aac_decoder.h"
#include <aacdecoder_lib.h>
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include "os/log.h"
#include "osi/include/allocator.h"
@@ -27,6 +27,8 @@
#define DECODE_BUF_LEN (8 * 2 * 1024)
+using namespace bluetooth;
+
typedef struct {
HANDLE_AACDECODER aac_handle;
bool has_aac_handle; // True if aac_handle is valid
@@ -70,8 +72,7 @@
AAC_DECODER_ERROR err = aacDecoder_Fill(a2dp_aac_decoder_cb.aac_handle,
&pBuffer, &bufferSize, &bytesValid);
if (err != AAC_DEC_OK) {
- LOG_ERROR("%s: aacDecoder_Fill failed: 0x%x", __func__,
- static_cast<unsigned>(err));
+ log::error("aacDecoder_Fill failed: 0x{:x}", static_cast<unsigned>(err));
return false;
}
@@ -83,15 +84,15 @@
break;
}
if (err != AAC_DEC_OK) {
- LOG_ERROR("%s: aacDecoder_DecodeFrame failed: 0x%x", __func__,
- static_cast<int>(err));
+ log::error("aacDecoder_DecodeFrame failed: 0x{:x}",
+ static_cast<int>(err));
break;
}
CStreamInfo* info =
aacDecoder_GetStreamInfo(a2dp_aac_decoder_cb.aac_handle);
if (!info || info->sampleRate <= 0) {
- LOG_ERROR("%s: Invalid stream info", __func__);
+ log::error("Invalid stream info");
break;
}
diff --git a/system/stack/a2dp/a2dp_aac_encoder.cc b/system/stack/a2dp/a2dp_aac_encoder.cc
index 4231170..7cee859 100644
--- a/system/stack/a2dp/a2dp_aac_encoder.cc
+++ b/system/stack/a2dp/a2dp_aac_encoder.cc
@@ -19,7 +19,7 @@
#include "a2dp_aac_encoder.h"
#include <aacenc_lib.h>
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
@@ -42,6 +42,13 @@
// offset
#define A2DP_AAC_OFFSET AVDT_MEDIA_OFFSET
+using namespace bluetooth;
+
+namespace fmt {
+template <>
+struct formatter<AACENC_ERROR> : enum_formatter<AACENC_ERROR> {};
+} // namespace fmt
+
typedef struct {
uint32_t sample_rate;
uint8_t channel_mode;
@@ -163,18 +170,15 @@
AACENC_ERROR aac_error = aacEncOpen(&a2dp_aac_encoder_cb.aac_handle, 0,
2 /* max 2 channels: stereo */);
if (aac_error != AACENC_OK) {
- LOG_ERROR("%s: Cannot open AAC encoder handle: AAC error 0x%x", __func__,
- aac_error);
+ log::error("Cannot open AAC encoder handle: AAC error 0x{:x}", aac_error);
return; // TODO: Return an error?
}
a2dp_aac_encoder_cb.has_aac_handle = true;
}
if (!a2dp_codec_config->copyOutOtaCodecConfig(codec_info)) {
- LOG_ERROR(
- "%s: Cannot update the codec encoder for %s: "
- "invalid codec config",
- __func__, a2dp_codec_config->name().c_str());
+ log::error("Cannot update the codec encoder for {}: invalid codec config",
+ a2dp_codec_config->name().c_str());
return;
}
const uint8_t* p_codec_info = codec_info;
@@ -185,9 +189,9 @@
p_feeding_params->bits_per_sample =
a2dp_codec_config->getAudioBitsPerSample();
p_feeding_params->channel_count = A2DP_GetTrackChannelCountAac(p_codec_info);
- LOG_INFO("%s: sample_rate=%u bits_per_sample=%u channel_count=%u", __func__,
- p_feeding_params->sample_rate, p_feeding_params->bits_per_sample,
- p_feeding_params->channel_count);
+ log::info("sample_rate={} bits_per_sample={} channel_count={}",
+ p_feeding_params->sample_rate, p_feeding_params->bits_per_sample,
+ p_feeding_params->channel_count);
// The codec parameters
p_encoder_params->sample_rate =
@@ -197,10 +201,10 @@
const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params =
a2dp_aac_encoder_cb.peer_params;
a2dp_aac_encoder_cb.TxAaMtuSize = adjust_effective_mtu(peer_params);
- LOG_INFO("%s: MTU=%d, peer_mtu=%d", __func__, a2dp_aac_encoder_cb.TxAaMtuSize,
- peer_params.peer_mtu);
- LOG_INFO("%s: sample_rate: %d channel_mode: %d ", __func__,
- p_encoder_params->sample_rate, p_encoder_params->channel_mode);
+ log::info("MTU={}, peer_mtu={}", a2dp_aac_encoder_cb.TxAaMtuSize,
+ peer_params.peer_mtu);
+ log::info("sample_rate: {} channel_mode: {} ", p_encoder_params->sample_rate,
+ p_encoder_params->channel_mode);
// Set the encoder's parameters: Audio Object Type - MANDATORY
// A2DP_AAC_OBJECT_TYPE_MPEG2_LC -> AOT_AAC_LC
@@ -223,19 +227,15 @@
aac_param_value = AOT_AAC_SCAL;
break;
default:
- LOG_ERROR(
- "%s: Cannot set AAC parameter AACENC_AOT: "
- "invalid object type %d",
- __func__, object_type);
+ log::error("Cannot set AAC parameter AACENC_AOT: invalid object type {}",
+ object_type);
return; // TODO: Return an error?
}
aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle, AACENC_AOT,
aac_param_value);
if (aac_error != AACENC_OK) {
- LOG_ERROR(
- "%s: Cannot set AAC parameter AACENC_AOT to %d: "
- "AAC error 0x%x",
- __func__, aac_param_value, aac_error);
+ log::error("Cannot set AAC parameter AACENC_AOT to {}: AAC error 0x{:x}",
+ aac_param_value, aac_error);
return; // TODO: Return an error?
}
@@ -244,10 +244,9 @@
aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle,
AACENC_AUDIOMUXVER, aac_param_value);
if (aac_error != AACENC_OK) {
- LOG_ERROR(
- "%s: Cannot set AAC parameter AACENC_AUDIOMUXVER to %d: "
- "AAC error 0x%x",
- __func__, aac_param_value, aac_error);
+ log::error(
+ "Cannot set AAC parameter AACENC_AUDIOMUXVER to {}: AAC error 0x{:x}",
+ aac_param_value, aac_error);
return; // TODO: Return an error?
}
@@ -256,10 +255,10 @@
aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle,
AACENC_SIGNALING_MODE, aac_param_value);
if (aac_error != AACENC_OK) {
- LOG_ERROR(
- "%s: Cannot set AAC parameter AACENC_SIGNALING_MODE to %d: "
- "AAC error 0x%x",
- __func__, aac_param_value, aac_error);
+ log::error(
+ "Cannot set AAC parameter AACENC_SIGNALING_MODE to {}: AAC error "
+ "0x{:x}",
+ aac_param_value, aac_error);
return; // TODO: Return an error?
}
@@ -268,10 +267,9 @@
aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle,
AACENC_SAMPLERATE, aac_param_value);
if (aac_error != AACENC_OK) {
- LOG_ERROR(
- "%s: Cannot set AAC parameter AACENC_SAMPLERATE to %d: "
- "AAC error 0x%x",
- __func__, aac_param_value, aac_error);
+ log::error(
+ "Cannot set AAC parameter AACENC_SAMPLERATE to {}: AAC error 0x{:x}",
+ aac_param_value, aac_error);
return; // TODO: Return an error?
}
aac_sampling_freq = aac_param_value; // Save for extra usage below
@@ -282,22 +280,20 @@
aac_peak_bit_rate =
A2DP_ComputeMaxBitRateAac(p_codec_info, a2dp_aac_encoder_cb.TxAaMtuSize);
aac_param_value = std::min(aac_param_value, aac_peak_bit_rate);
- LOG_INFO("%s: MTU = %d Sampling Frequency = %d Bit Rate = %d", __func__,
- a2dp_aac_encoder_cb.TxAaMtuSize, aac_sampling_freq, aac_param_value);
+ log::info("MTU = {} Sampling Frequency = {} Bit Rate = {}",
+ a2dp_aac_encoder_cb.TxAaMtuSize, aac_sampling_freq,
+ aac_param_value);
if (aac_param_value == -1) {
- LOG_ERROR(
- "%s: Cannot set AAC parameter AACENC_BITRATE: "
- "invalid codec bit rate",
- __func__);
+ log::error(
+ "Cannot set AAC parameter AACENC_BITRATE: invalid codec bit rate");
return; // TODO: Return an error?
}
aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle,
AACENC_BITRATE, aac_param_value);
if (aac_error != AACENC_OK) {
- LOG_ERROR(
- "%s: Cannot set AAC parameter AACENC_BITRATE to %d: "
- "AAC error 0x%x",
- __func__, aac_param_value, aac_error);
+ log::error(
+ "Cannot set AAC parameter AACENC_BITRATE to {}: AAC error 0x{:x}",
+ aac_param_value, aac_error);
return; // TODO: Return an error?
}
@@ -305,10 +301,9 @@
aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle,
AACENC_PEAK_BITRATE, aac_peak_bit_rate);
if (aac_error != AACENC_OK) {
- LOG_ERROR(
- "%s: Cannot set AAC parameter AACENC_PEAK_BITRATE to %d: "
- "AAC error 0x%x",
- __func__, aac_peak_bit_rate, aac_error);
+ log::error(
+ "Cannot set AAC parameter AACENC_PEAK_BITRATE to {}: AAC error 0x{:x}",
+ aac_peak_bit_rate, aac_error);
return; // TODO: Return an error?
}
@@ -321,10 +316,9 @@
aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle,
AACENC_CHANNELMODE, aac_param_value);
if (aac_error != AACENC_OK) {
- LOG_ERROR(
- "%s: Cannot set AAC parameter AACENC_CHANNELMODE to %d: "
- "AAC error 0x%x",
- __func__, aac_param_value, aac_error);
+ log::error(
+ "Cannot set AAC parameter AACENC_CHANNELMODE to {}: AAC error 0x{:x}",
+ aac_param_value, aac_error);
return; // TODO: Return an error?
}
@@ -333,10 +327,9 @@
aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle,
AACENC_TRANSMUX, aac_param_value);
if (aac_error != AACENC_OK) {
- LOG_ERROR(
- "%s: Cannot set AAC parameter AACENC_TRANSMUX to %d: "
- "AAC error 0x%x",
- __func__, aac_param_value, aac_error);
+ log::error(
+ "Cannot set AAC parameter AACENC_TRANSMUX to {}: AAC error 0x{:x}",
+ aac_param_value, aac_error);
return; // TODO: Return an error?
}
@@ -345,20 +338,18 @@
aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle,
AACENC_HEADER_PERIOD, aac_param_value);
if (aac_error != AACENC_OK) {
- LOG_ERROR(
- "%s: Cannot set AAC parameter AACENC_HEADER_PERIOD to %d: "
- "AAC error 0x%x",
- __func__, aac_param_value, aac_error);
+ log::error(
+ "Cannot set AAC parameter AACENC_HEADER_PERIOD to {}: AAC error 0x{:x}",
+ aac_param_value, aac_error);
return; // TODO: Return an error?
}
// Set the encoder's parameters: Variable Bit Rate Support
aac_param_value = A2DP_GetVariableBitRateSupportAac(p_codec_info);
if (aac_param_value == -1) {
- LOG_ERROR(
- "%s: Cannot set AAC parameter AACENC_BITRATEMODE: "
- "invalid codec bit rate mode",
- __func__);
+ log::error(
+ "Cannot set AAC parameter AACENC_BITRATEMODE: invalid codec bit rate "
+ "mode");
return; // TODO: Return an error?
} else if (aac_param_value == A2DP_AAC_VARIABLE_BIT_RATE_ENABLED) {
// VBR has 5 modes defined in external/aac/libAACenc/src/aacenc.h
@@ -382,14 +373,13 @@
aac_param_value =
static_cast<uint8_t>(bitrate_mode) & ~A2DP_AAC_VARIABLE_BIT_RATE_MASK;
}
- LOG_INFO("%s: AACENC_BITRATEMODE: %d", __func__, aac_param_value);
+ log::info("AACENC_BITRATEMODE: {}", aac_param_value);
aac_error = aacEncoder_SetParam(a2dp_aac_encoder_cb.aac_handle,
AACENC_BITRATEMODE, aac_param_value);
if (aac_error != AACENC_OK) {
- LOG_ERROR(
- "%s: Cannot set AAC parameter AACENC_BITRATEMODE to %d: "
- "AAC error 0x%x",
- __func__, aac_param_value, aac_error);
+ log::error(
+ "Cannot set AAC parameter AACENC_BITRATEMODE to {}: AAC error 0x{:x}",
+ aac_param_value, aac_error);
return; // TODO: Return an error?
}
@@ -397,8 +387,8 @@
aac_error =
aacEncEncode(a2dp_aac_encoder_cb.aac_handle, NULL, NULL, NULL, NULL);
if (aac_error != AACENC_OK) {
- LOG_ERROR("%s: Cannot complete setting the AAC parameters: AAC error 0x%x",
- __func__, aac_error);
+ log::error("Cannot complete setting the AAC parameters: AAC error 0x{:x}",
+ aac_error);
return; // TODO: Return an error?
}
@@ -406,18 +396,17 @@
AACENC_InfoStruct aac_info;
aac_error = aacEncInfo(a2dp_aac_encoder_cb.aac_handle, &aac_info);
if (aac_error != AACENC_OK) {
- LOG_ERROR("%s: Cannot retrieve the AAC encoder info: AAC error 0x%x",
- __func__, aac_error);
+ log::error("Cannot retrieve the AAC encoder info: AAC error 0x{:x}",
+ aac_error);
return; // TODO: Return an error?
}
p_encoder_params->frame_length = aac_info.frameLength;
p_encoder_params->input_channels_n = aac_info.inputChannels;
p_encoder_params->max_encoded_buffer_bytes = aac_info.maxOutBufBytes;
- LOG_INFO(
- "%s: AAC frame_length = %u input_channels_n = %u "
- "max_encoded_buffer_bytes = %d",
- __func__, p_encoder_params->frame_length,
- p_encoder_params->input_channels_n,
+ log::info(
+ "AAC frame_length = {} input_channels_n = {} max_encoded_buffer_bytes = "
+ "{}",
+ p_encoder_params->frame_length, p_encoder_params->input_channels_n,
p_encoder_params->max_encoded_buffer_bytes);
// After encoder params ready, reset the feeding state and its interval.
@@ -434,7 +423,7 @@
auto frame_length = a2dp_aac_encoder_cb.aac_encoder_params.frame_length;
auto sample_rate = a2dp_aac_encoder_cb.feeding_params.sample_rate;
if (frame_length == 0 || sample_rate == 0) {
- LOG_WARN("%s: AAC encoder is not configured", __func__);
+ log::warn("AAC encoder is not configured");
a2dp_aac_encoder_interval_ms = A2DP_AAC_ENCODER_INTERVAL_MS;
} else {
// PCM data size per AAC frame (bits)
@@ -459,9 +448,9 @@
a2dp_aac_encoder_interval_ms) /
1000;
- LOG_INFO("%s: PCM bytes %u per tick %u ms", __func__,
- a2dp_aac_encoder_cb.aac_feeding_state.bytes_per_tick,
- a2dp_aac_encoder_interval_ms);
+ log::info("PCM bytes {} per tick {} ms",
+ a2dp_aac_encoder_cb.aac_feeding_state.bytes_per_tick,
+ a2dp_aac_encoder_interval_ms);
}
void a2dp_aac_feeding_flush(void) {
@@ -481,8 +470,8 @@
uint8_t nb_iterations = 0;
a2dp_aac_get_num_frame_iteration(&nb_iterations, &nb_frame, timestamp_us);
- LOG_VERBOSE("%s: Sending %d frames per iteration, %d iterations", __func__,
- nb_frame, nb_iterations);
+ log::verbose("Sending {} frames per iteration, {} iterations", nb_frame,
+ nb_iterations);
if (nb_frame == 0) return;
for (uint8_t counter = 0; counter < nb_iterations; counter++) {
@@ -505,7 +494,7 @@
a2dp_aac_encoder_cb.aac_encoder_params.frame_length *
a2dp_aac_encoder_cb.feeding_params.channel_count *
a2dp_aac_encoder_cb.feeding_params.bits_per_sample / 8;
- LOG_VERBOSE("%s: pcm_bytes_per_frame %u", __func__, pcm_bytes_per_frame);
+ log::verbose("pcm_bytes_per_frame {}", pcm_bytes_per_frame);
uint32_t us_this_tick = a2dp_aac_encoder_interval_ms * 1000;
uint64_t now_us = timestamp_us;
@@ -522,8 +511,7 @@
a2dp_aac_encoder_cb.aac_feeding_state.counter -= result * pcm_bytes_per_frame;
nof = result;
- LOG_VERBOSE("%s: effective num of frames %u, iterations %u", __func__, nof,
- noi);
+ log::verbose("effective num of frames {}, iterations {}", nof, noi);
*num_of_frames = nof;
*num_of_iterations = noi;
@@ -595,7 +583,7 @@
if (a2dp_aac_read_feeding(read_buffer, &bytes_read)) {
uint8_t* packet = (uint8_t*)(p_buf + 1) + p_buf->offset + p_buf->len;
if (!a2dp_aac_encoder_cb.has_aac_handle) {
- LOG_ERROR("%s: invalid AAC handle", __func__);
+ log::error("invalid AAC handle");
a2dp_aac_encoder_cb.stats.media_read_total_dropped_packets++;
osi_free(p_buf);
return;
@@ -606,7 +594,7 @@
aacEncEncode(a2dp_aac_encoder_cb.aac_handle, &in_buf_desc,
&out_buf_desc, &aac_in_args, &aac_out_args);
if (aac_error != AACENC_OK) {
- LOG_ERROR("%s: AAC encoding error: 0x%x", __func__, aac_error);
+ log::error("AAC encoding error: 0x{:x}", aac_error);
a2dp_aac_encoder_cb.stats.media_read_total_dropped_packets++;
osi_free(p_buf);
return;
@@ -617,7 +605,7 @@
nb_frame--;
p_buf->layer_specific++; // added a frame to the buffer
} else {
- LOG_WARN("%s: underflow %d", __func__, nb_frame);
+ log::warn("underflow {}", nb_frame);
a2dp_aac_encoder_cb.aac_feeding_state.counter +=
nb_frame * p_encoder_params->frame_length *
p_feeding_params->channel_count *
@@ -687,16 +675,15 @@
if (mtu_size > peer_params.peer_mtu) {
mtu_size = peer_params.peer_mtu;
}
- LOG_VERBOSE("%s: original AVDTP MTU size: %d", __func__, mtu_size);
+ log::verbose("original AVDTP MTU size: {}", mtu_size);
if (peer_params.is_peer_edr && !peer_params.peer_supports_3mbps) {
// This condition would be satisfied only if the remote device is
// EDR and supports only 2 Mbps, but the effective AVDTP MTU size
// exceeds the 2DH5 packet size.
- LOG_VERBOSE("%s: The remote device is EDR but does not support 3 Mbps",
- __func__);
+ log::verbose("The remote device is EDR but does not support 3 Mbps");
if (mtu_size > MAX_2MBPS_AVDTP_MTU) {
- LOG_WARN("%s: Restricting AVDTP MTU size from %d to %d", __func__,
- mtu_size, MAX_2MBPS_AVDTP_MTU);
+ log::warn("Restricting AVDTP MTU size from {} to {}", mtu_size,
+ MAX_2MBPS_AVDTP_MTU);
mtu_size = MAX_2MBPS_AVDTP_MTU;
}
}
diff --git a/system/stack/a2dp/a2dp_aac_encoder_linux.cc b/system/stack/a2dp/a2dp_aac_encoder_linux.cc
index 7c61830..f374bcf 100644
--- a/system/stack/a2dp/a2dp_aac_encoder_linux.cc
+++ b/system/stack/a2dp/a2dp_aac_encoder_linux.cc
@@ -16,6 +16,7 @@
#define LOG_TAG "a2dp_aac_encoder"
+#include <bluetooth/log.h>
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
@@ -29,7 +30,6 @@
#include "internal_include/bt_target.h"
#include "mmc/codec_client/codec_client.h"
#include "mmc/proto/mmc_config.pb.h"
-#include "os/log.h"
#include "os/rand.h"
#include "osi/include/allocator.h"
#include "stack/include/bt_hdr.h"
@@ -63,8 +63,7 @@
int rc = client->init(config);
if (rc < 0) {
- LOG_ERROR("%s: Init failed with error message, %s", __func__,
- strerror(-rc));
+ log::error("Init failed with error message, {}", strerror(-rc));
}
return rc;
}
@@ -81,20 +80,19 @@
// Otherwise returns the length of the encoded frame stored in `o_buf`.
int encode_pcm(uint8_t* i_buf, int i_len, uint8_t* o_buf, int o_len) {
if (i_buf == nullptr || o_buf == nullptr) {
- LOG_ERROR("%s: Buffer is null", __func__);
+ log::error("Buffer is null");
return -EINVAL;
}
if (!client) {
- LOG_ERROR("%s: CodecClient does not init", __func__);
+ log::error("CodecClient does not init");
return -ENOENT;
}
int rc = client->transcode(i_buf, i_len, o_buf, o_len);
if (rc < 0) {
- LOG_ERROR("%s: Encode failed with error message, %s", __func__,
- strerror(-rc));
+ log::error("Encode failed with error message, {}", strerror(-rc));
}
return rc;
}
@@ -158,10 +156,8 @@
a2dp_source_enqueue_callback_t enqueue_callback) {
uint8_t codec_info[AVDT_CODEC_SIZE];
if (!a2dp_codec_config->copyOutOtaCodecConfig(codec_info)) {
- LOG_ERROR(
- "%s: Cannot update the codec encoder for %s: "
- "invalid codec config",
- __func__, a2dp_codec_config->name().c_str());
+ log::error("Cannot update the codec encoder for {}: invalid codec config",
+ a2dp_codec_config->name().c_str());
return;
}
@@ -181,8 +177,7 @@
sample_rate, channel_count, bit_rate, bits_per_sample, mtu);
if (pcm_samples_per_frame < 0) {
- LOG_ERROR("%s: Failed to prepare context: %d", __func__,
- pcm_samples_per_frame);
+ log::error("Failed to prepare context: {}", pcm_samples_per_frame);
codec_intf.clear_context();
return; // TODO(b/294165759): need to return an error
}
@@ -225,7 +220,7 @@
auto frame_length = a2dp_aac_encoder_cb.pcm_samples_per_frame;
auto sample_rate = a2dp_aac_encoder_cb.feeding_params.sample_rate;
if (sample_rate == 0) {
- LOG_WARN("%s: Sample rate is not configured", __func__);
+ log::warn("Sample rate is not configured");
return;
}
@@ -239,9 +234,9 @@
1000,
};
- LOG_WARN("%s: PCM bytes %d per tick (%dms)", __func__,
- a2dp_aac_encoder_cb.aac_feeding_state.bytes_per_tick,
- a2dp_aac_encoder_cb.encoder_interval_ms);
+ log::warn("PCM bytes {} per tick ({}ms)",
+ a2dp_aac_encoder_cb.aac_feeding_state.bytes_per_tick,
+ a2dp_aac_encoder_cb.encoder_interval_ms);
}
void a2dp_aac_feeding_flush() {
@@ -282,7 +277,7 @@
a2dp_aac_encoder_cb.pcm_samples_per_frame *
a2dp_aac_encoder_cb.feeding_params.channel_count *
a2dp_aac_encoder_cb.feeding_params.bits_per_sample / 8;
- LOG_VERBOSE("%s: pcm_bytes_per_frame %u", __func__, pcm_bytes_per_frame);
+ log::verbose("pcm_bytes_per_frame {}", pcm_bytes_per_frame);
uint32_t us_this_tick = a2dp_aac_encoder_cb.encoder_interval_ms * 1000;
uint64_t now_us = timestamp_us;
@@ -299,8 +294,7 @@
a2dp_aac_encoder_cb.aac_feeding_state.counter -= result * pcm_bytes_per_frame;
nof = result;
- LOG_VERBOSE("%s: effective num of frames %u, iterations %u", __func__, nof,
- noi);
+ log::verbose("effective num of frames {}, iterations {}", nof, noi);
*num_of_frames = nof;
*num_of_iterations = noi;
@@ -319,7 +313,7 @@
uint32_t bytes_read = 0;
if (!a2dp_aac_read_feeding(read_buffer, &bytes_read)) {
- LOG_WARN("%s: Underflow %u", __func__, nb_frame);
+ log::warn("Underflow {}", nb_frame);
a2dp_aac_encoder_cb.aac_feeding_state.counter +=
nb_frame * a2dp_aac_encoder_cb.pcm_samples_per_frame *
a2dp_aac_encoder_cb.feeding_params.channel_count *
@@ -343,7 +337,7 @@
}
if (written == 0) {
- LOG_INFO("%s: Dropped a frame, likely due to buffering", __func__);
+ log::info("Dropped a frame, likely due to buffering");
a2dp_aac_encoder_cb.stats.media_read_total_dropped_packets++;
osi_free(p_buf);
continue;
@@ -396,16 +390,15 @@
if (mtu_size > peer_params.peer_mtu) {
mtu_size = peer_params.peer_mtu;
}
- LOG_VERBOSE("%s: original AVDTP MTU size: %d", __func__, mtu_size);
+ log::verbose("original AVDTP MTU size: {}", mtu_size);
if (peer_params.is_peer_edr && !peer_params.peer_supports_3mbps) {
// This condition would be satisfied only if the remote device is
// EDR and supports only 2 Mbps, but the effective AVDTP MTU size
// exceeds the 2DH5 packet size.
- LOG_VERBOSE("%s: The remote device is EDR but does not support 3 Mbps",
- __func__);
+ log::verbose("The remote device is EDR but does not support 3 Mbps");
if (mtu_size > MAX_2MBPS_AVDTP_MTU) {
- LOG_WARN("%s: Restricting AVDTP MTU size from %d to %d", __func__,
- mtu_size, MAX_2MBPS_AVDTP_MTU);
+ log::warn("Restricting AVDTP MTU size from {} to {}", mtu_size,
+ MAX_2MBPS_AVDTP_MTU);
mtu_size = MAX_2MBPS_AVDTP_MTU;
}
}
diff --git a/system/stack/a2dp/a2dp_api.cc b/system/stack/a2dp/a2dp_api.cc
index 13bda9f..bdee82b 100644
--- a/system/stack/a2dp/a2dp_api.cc
+++ b/system/stack/a2dp/a2dp_api.cc
@@ -26,12 +26,12 @@
#include "a2dp_api.h"
+#include <bluetooth/log.h>
#include <string.h>
#include "a2dp_int.h"
#include "avdt_api.h"
#include "internal_include/bt_target.h"
-#include "os/log.h"
#include "osi/include/allocator.h"
#include "osi/include/osi.h" // UNUSED_ATTR
#include "sdpdefs.h"
@@ -41,6 +41,7 @@
#include "types/bluetooth/uuid.h"
#include "types/raw_address.h"
+using namespace bluetooth;
using namespace bluetooth::legacy::stack::sdp;
using bluetooth::Uuid;
@@ -79,7 +80,7 @@
tSDP_PROTOCOL_ELEM elem;
RawAddress peer_address = RawAddress::kEmpty;
- LOG_INFO("%s: status: %d", __func__, status);
+ log::info("status: {}", status);
if (status == SDP_SUCCESS) {
/* loop through all records we found */
@@ -99,10 +100,10 @@
a2dp_svc.p_service_name = (char*)p_attr->attr_value.v.array;
a2dp_svc.service_len = SDP_DISC_ATTR_LEN(p_attr->attr_len_type);
} else {
- LOG_ERROR("ATTR_ID_SERVICE_NAME attr type not STR!!");
+ log::error("ATTR_ID_SERVICE_NAME attr type not STR!!");
}
} else {
- LOG_ERROR("ATTR_ID_SERVICE_NAME attr not found!!");
+ log::error("ATTR_ID_SERVICE_NAME attr not found!!");
}
/* get provider name */
@@ -112,10 +113,10 @@
a2dp_svc.p_provider_name = (char*)p_attr->attr_value.v.array;
a2dp_svc.provider_len = SDP_DISC_ATTR_LEN(p_attr->attr_len_type);
} else {
- LOG_ERROR("ATTR_ID_PROVIDER_NAME attr type not STR!!");
+ log::error("ATTR_ID_PROVIDER_NAME attr type not STR!!");
}
} else {
- LOG_ERROR("ATTR_ID_PROVIDER_NAME attr not found!!");
+ log::error("ATTR_ID_PROVIDER_NAME attr not found!!");
}
/* get supported features */
@@ -125,17 +126,17 @@
SDP_DISC_ATTR_LEN(p_attr->attr_len_type) >= 2) {
a2dp_svc.features = p_attr->attr_value.v.u16;
} else {
- LOG_ERROR("ATTR_ID_SUPPORTED_FEATURES attr type not STR!!");
+ log::error("ATTR_ID_SUPPORTED_FEATURES attr type not STR!!");
}
} else {
- LOG_ERROR("ATTR_ID_SUPPORTED_FEATURES attr not found!!");
+ log::error("ATTR_ID_SUPPORTED_FEATURES attr not found!!");
}
/* get AVDTP version */
if (get_legacy_stack_sdp_api()->record.SDP_FindProtocolListElemInRec(
p_rec, UUID_PROTOCOL_AVDTP, &elem)) {
a2dp_svc.avdt_version = elem.params[0];
- LOG_VERBOSE("avdt_version: 0x%x", a2dp_svc.avdt_version);
+ log::verbose("avdt_version: 0x{:x}", a2dp_svc.avdt_version);
}
/* we've got everything, we're done */
@@ -208,7 +209,7 @@
uint8_t* p;
tSDP_PROTOCOL_ELEM proto_list[A2DP_NUM_PROTO_ELEMS];
- LOG_VERBOSE("%s: uuid: 0x%x", __func__, service_uuid);
+ log::verbose("uuid: 0x{:x}", service_uuid);
if ((sdp_handle == 0) || (service_uuid != UUID_SERVCLASS_AUDIO_SOURCE &&
service_uuid != UUID_SERVCLASS_AUDIO_SINK))
@@ -308,16 +309,17 @@
if ((service_uuid != UUID_SERVCLASS_AUDIO_SOURCE &&
service_uuid != UUID_SERVCLASS_AUDIO_SINK) ||
p_db == NULL || p_cback == NULL) {
- LOG_ERROR("Cannot find service for peer %s UUID 0x%04x: invalid parameters",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), service_uuid);
+ log::error(
+ "Cannot find service for peer {} UUID 0x{:04x}: invalid parameters",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr), service_uuid);
return A2DP_INVALID_PARAMS;
}
if (a2dp_cb.find.service_uuid == UUID_SERVCLASS_AUDIO_SOURCE ||
a2dp_cb.find.service_uuid == UUID_SERVCLASS_AUDIO_SINK ||
a2dp_cb.find.p_db != NULL) {
- LOG_ERROR("Cannot find service for peer %s UUID 0x%04x: busy",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), service_uuid);
+ log::error("Cannot find service for peer {} UUID 0x{:04x}: busy",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr), service_uuid);
return A2DP_BUSY;
}
@@ -333,8 +335,8 @@
a2dp_cb.find.p_db, p_db->db_len, 1, &uuid_list, p_db->num_attr,
p_db->p_attrs)) {
osi_free_and_reset((void**)&a2dp_cb.find.p_db);
- LOG_ERROR("Unable to initialize SDP discovery for peer %s UUID 0x%04X",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), service_uuid);
+ log::error("Unable to initialize SDP discovery for peer {} UUID 0x{:04X}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr), service_uuid);
return A2DP_FAIL;
}
@@ -348,12 +350,13 @@
a2dp_cb.find.service_uuid = 0;
a2dp_cb.find.p_cback = NULL;
osi_free_and_reset((void**)&a2dp_cb.find.p_db);
- LOG_ERROR("Cannot find service for peer %s UUID 0x%04x: SDP error",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), service_uuid);
+ log::error("Cannot find service for peer {} UUID 0x{:04x}: SDP error",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr), service_uuid);
return A2DP_FAIL;
}
- LOG_INFO("A2DP service discovery for peer %s UUID 0x%04x: SDP search started",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), service_uuid);
+ log::info(
+ "A2DP service discovery for peer {} UUID 0x{:04x}: SDP search started",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr), service_uuid);
return A2DP_SUCCESS;
}
diff --git a/system/stack/a2dp/a2dp_codec_config.cc b/system/stack/a2dp/a2dp_codec_config.cc
index 3772c4b..da537fb 100644
--- a/system/stack/a2dp/a2dp_codec_config.cc
+++ b/system/stack/a2dp/a2dp_codec_config.cc
@@ -20,7 +20,7 @@
#define LOG_TAG "a2dp_codec"
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include "a2dp_aac.h"
#include "a2dp_codec_api.h"
@@ -40,7 +40,6 @@
#include "bta/av/bta_av_int.h"
#include "device/include/device_iot_config.h"
#include "internal_include/bt_trace.h"
-#include "os/log.h"
#include "osi/include/properties.h"
#include "stack/include/bt_hdr.h"
@@ -52,6 +51,8 @@
// |codec_index| and |codec_priority| are the codec type and priority to use
// for the initialization.
+using namespace bluetooth;
+
static void init_btav_a2dp_codec_config(
btav_a2dp_codec_config_t* codec_config, btav_a2dp_codec_index_t codec_index,
btav_a2dp_codec_priority_t codec_priority) {
@@ -113,7 +114,7 @@
A2dpCodecConfig* A2dpCodecConfig::createCodec(
btav_a2dp_codec_index_t codec_index,
btav_a2dp_codec_priority_t codec_priority) {
- LOG_INFO("%s", A2DP_CodecIndexStr(codec_index));
+ log::info("{}", A2DP_CodecIndexStr(codec_index));
// Hardware offload codec extensibility:
// management of the codec is moved under the ProviderInfo
@@ -176,7 +177,7 @@
memcpy(p_codec_info, ota_codec_config_, sizeof(ota_codec_config_));
tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info);
- LOG_VERBOSE("%s: codec_type = 0x%x", __func__, codec_type);
+ log::verbose("codec_type = 0x{:x}", codec_type);
switch (codec_type) {
case A2DP_MEDIA_CT_SBC:
@@ -191,7 +192,7 @@
break;
}
- LOG_ERROR("%s: unsupported codec type 0x%x", __func__, codec_type);
+ log::error("unsupported codec type 0x{:x}", codec_type);
return -1;
}
@@ -261,8 +262,8 @@
}
p_a2dp_offload->codec_info[7] =
codec_config[10]; // LDAC specific channel mode
- LOG_VERBOSE("%s: Ldac specific channelmode =%d", __func__,
- p_a2dp_offload->codec_info[7]);
+ log::verbose("Ldac specific channelmode ={}",
+ p_a2dp_offload->codec_info[7]);
}
break;
#endif
@@ -536,7 +537,7 @@
int A2DP_IotGetPeerSinkCodecType(const uint8_t* p_codec_info) {
int peer_codec_type = 0;
tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info);
- LOG_VERBOSE("%s: codec_type = 0x%x", __func__, codec_type);
+ log::verbose("codec_type = 0x{:x}", codec_type);
switch (codec_type) {
case A2DP_MEDIA_CT_SBC:
peer_codec_type = IOT_CONF_VAL_A2DP_CODECTYPE_SBC;
@@ -546,8 +547,8 @@
uint16_t codec_id = A2DP_VendorCodecGetCodecId(p_codec_info);
uint32_t vendor_id = A2DP_VendorCodecGetVendorId(p_codec_info);
- LOG_VERBOSE("%s codec_id = %d", __func__, codec_id);
- LOG_VERBOSE("%s vendor_id = %x", __func__, vendor_id);
+ log::verbose("codec_id = {}", codec_id);
+ log::verbose("vendor_id = {:x}", vendor_id);
if (codec_id == A2DP_APTX_CODEC_ID_BLUETOOTH &&
vendor_id == A2DP_APTX_VENDOR_ID) {
@@ -605,7 +606,7 @@
}
bool A2dpCodecs::init() {
- LOG_INFO("%s", __func__);
+ log::info("");
std::lock_guard<std::recursive_mutex> lock(codec_mutex_);
bool opus_enabled =
@@ -636,8 +637,7 @@
// If OPUS is not supported it is disabled
if (codec_index == BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS && !opus_enabled) {
codec_priority = BTAV_A2DP_CODEC_PRIORITY_DISABLED;
- LOG_INFO("%s: OPUS codec disabled, updated priority to %d", __func__,
- codec_priority);
+ log::info("OPUS codec disabled, updated priority to {}", codec_priority);
}
A2dpCodecConfig* codec_config =
@@ -645,8 +645,8 @@
if (codec_config == nullptr) continue;
if (codec_priority != BTAV_A2DP_CODEC_PRIORITY_DEFAULT) {
- LOG_INFO("%s: updated %s codec priority to %d", __func__,
- codec_config->name().c_str(), codec_priority);
+ log::info("updated {} codec priority to {}", codec_config->name().c_str(),
+ codec_priority);
}
// Test if the codec is disabled
@@ -667,19 +667,19 @@
}
if (ordered_source_codecs_.empty()) {
- LOG_ERROR("%s: no Source codecs were initialized", __func__);
+ log::error("no Source codecs were initialized");
} else {
for (auto iter : ordered_source_codecs_) {
- LOG_INFO("%s: initialized Source codec %s, idx %d", __func__,
- iter->name().c_str(), iter->codecIndex());
+ log::info("initialized Source codec {}, idx {}", iter->name().c_str(),
+ iter->codecIndex());
}
}
if (ordered_sink_codecs_.empty()) {
- LOG_ERROR("%s: no Sink codecs were initialized", __func__);
+ log::error("no Sink codecs were initialized");
} else {
for (auto iter : ordered_sink_codecs_) {
- LOG_INFO("%s: initialized Sink codec %s, idx %d", __func__,
- iter->name().c_str(), iter->codecIndex());
+ log::info("initialized Sink codec {}, idx {}", iter->name().c_str(),
+ iter->codecIndex());
}
}
@@ -768,8 +768,7 @@
*p_restart_output = false;
*p_config_updated = false;
- LOG_INFO("%s: Configuring: %s", __func__,
- codec_user_config.ToString().c_str());
+ log::info("Configuring: {}", codec_user_config.ToString().c_str());
if (codec_user_config.codec_type < BTAV_A2DP_CODEC_INDEX_MAX) {
auto iter = indexed_codecs_.find(codec_user_config.codec_type);
@@ -848,10 +847,9 @@
if (*p_restart_input || *p_restart_output) *p_config_updated = true;
- LOG_INFO(
- "%s: Configured: restart_input = %d restart_output = %d "
- "config_updated = %d",
- __func__, *p_restart_input, *p_restart_output, *p_config_updated);
+ log::info(
+ "Configured: restart_input = {} restart_output = {} config_updated = {}",
+ *p_restart_input, *p_restart_output, *p_config_updated);
return true;
@@ -906,10 +904,10 @@
if (current_codec_config_ != nullptr) {
codec_user_config = current_codec_config_->getCodecUserConfig();
if (!A2dpCodecConfig::isCodecConfigEmpty(codec_user_config)) {
- LOG_WARN(
- "%s: ignoring peer OTA configuration for codec %s: "
- "existing user configuration for current codec %s",
- __func__, A2DP_CodecName(p_ota_codec_config),
+ log::warn(
+ "ignoring peer OTA configuration for codec {}: existing user "
+ "configuration for current codec {}",
+ A2DP_CodecName(p_ota_codec_config),
current_codec_config_->name().c_str());
goto fail;
}
@@ -920,16 +918,13 @@
// ignored.
codec_type = A2DP_SourceCodecIndex(p_ota_codec_config);
if (codec_type == BTAV_A2DP_CODEC_INDEX_MAX) {
- LOG_WARN(
- "%s: ignoring peer OTA codec configuration: "
- "invalid codec",
- __func__);
+ log::warn("ignoring peer OTA codec configuration: invalid codec");
goto fail; // Invalid codec
} else {
auto iter = indexed_codecs_.find(codec_type);
if (iter == indexed_codecs_.end()) {
- LOG_WARN("%s: cannot find codec configuration for peer OTA codec %s",
- __func__, A2DP_CodecName(p_ota_codec_config));
+ log::warn("cannot find codec configuration for peer OTA codec {}",
+ A2DP_CodecName(p_ota_codec_config));
goto fail;
}
a2dp_codec_config = iter->second;
@@ -937,10 +932,10 @@
if (a2dp_codec_config == nullptr) goto fail;
codec_user_config = a2dp_codec_config->getCodecUserConfig();
if (!A2dpCodecConfig::isCodecConfigEmpty(codec_user_config)) {
- LOG_WARN(
- "%s: ignoring peer OTA configuration for codec %s: "
- "existing user configuration for same codec",
- __func__, A2DP_CodecName(p_ota_codec_config));
+ log::warn(
+ "ignoring peer OTA configuration for codec {}: existing user "
+ "configuration for same codec",
+ A2DP_CodecName(p_ota_codec_config));
goto fail;
}
current_codec_config_ = a2dp_codec_config;
@@ -951,8 +946,8 @@
codec_user_config, codec_audio_config, p_peer_params,
p_ota_codec_config, false, p_result_codec_config, p_restart_input,
p_restart_output, p_config_updated)) {
- LOG_WARN("%s: cannot set codec configuration for peer OTA codec %s",
- __func__, A2DP_CodecName(p_ota_codec_config));
+ log::warn("cannot set codec configuration for peer OTA codec {}",
+ A2DP_CodecName(p_ota_codec_config));
goto fail;
}
CHECK(current_codec_config_ != nullptr);
@@ -1059,7 +1054,7 @@
bool A2DP_IsSourceCodecValid(const uint8_t* p_codec_info) {
tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info);
- LOG_VERBOSE("%s: codec_type = 0x%x", __func__, codec_type);
+ log::verbose("codec_type = 0x{:x}", codec_type);
switch (codec_type) {
case A2DP_MEDIA_CT_SBC:
@@ -1080,7 +1075,7 @@
bool A2DP_IsSinkCodecValid(const uint8_t* p_codec_info) {
tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info);
- LOG_VERBOSE("%s: codec_type = 0x%x", __func__, codec_type);
+ log::verbose("codec_type = 0x{:x}", codec_type);
switch (codec_type) {
case A2DP_MEDIA_CT_SBC:
@@ -1101,7 +1096,7 @@
bool A2DP_IsPeerSourceCodecValid(const uint8_t* p_codec_info) {
tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info);
- LOG_VERBOSE("%s: codec_type = 0x%x", __func__, codec_type);
+ log::verbose("codec_type = 0x{:x}", codec_type);
switch (codec_type) {
case A2DP_MEDIA_CT_SBC:
@@ -1122,7 +1117,7 @@
bool A2DP_IsPeerSinkCodecValid(const uint8_t* p_codec_info) {
tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info);
- LOG_VERBOSE("%s: codec_type = 0x%x", __func__, codec_type);
+ log::verbose("codec_type = 0x{:x}", codec_type);
switch (codec_type) {
case A2DP_MEDIA_CT_SBC:
@@ -1143,7 +1138,7 @@
bool A2DP_IsSinkCodecSupported(const uint8_t* p_codec_info) {
tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info);
- LOG_VERBOSE("%s: codec_type = 0x%x", __func__, codec_type);
+ log::verbose("codec_type = 0x{:x}", codec_type);
switch (codec_type) {
case A2DP_MEDIA_CT_SBC:
@@ -1158,14 +1153,14 @@
break;
}
- LOG_ERROR("%s: unsupported codec type 0x%x", __func__, codec_type);
+ log::error("unsupported codec type 0x{:x}", codec_type);
return false;
}
bool A2DP_IsPeerSourceCodecSupported(const uint8_t* p_codec_info) {
tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info);
- LOG_VERBOSE("%s: codec_type = 0x%x", __func__, codec_type);
+ log::verbose("codec_type = 0x{:x}", codec_type);
switch (codec_type) {
case A2DP_MEDIA_CT_SBC:
@@ -1180,7 +1175,7 @@
break;
}
- LOG_ERROR("%s: unsupported codec type 0x%x", __func__, codec_type);
+ log::error("unsupported codec type 0x{:x}", codec_type);
return false;
}
@@ -1209,7 +1204,7 @@
const char* A2DP_CodecName(const uint8_t* p_codec_info) {
tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info);
- LOG_VERBOSE("%s: codec_type = 0x%x", __func__, codec_type);
+ log::verbose("codec_type = 0x{:x}", codec_type);
switch (codec_type) {
case A2DP_MEDIA_CT_SBC:
@@ -1224,7 +1219,7 @@
break;
}
- LOG_ERROR("%s: unsupported codec type 0x%x", __func__, codec_type);
+ log::error("unsupported codec type 0x{:x}", codec_type);
return "UNKNOWN CODEC";
}
@@ -1248,7 +1243,7 @@
break;
}
- LOG_ERROR("%s: unsupported codec type 0x%x", __func__, codec_type_a);
+ log::error("unsupported codec type 0x{:x}", codec_type_a);
return false;
}
@@ -1272,14 +1267,14 @@
break;
}
- LOG_ERROR("%s: unsupported codec type 0x%x", __func__, codec_type_a);
+ log::error("unsupported codec type 0x{:x}", codec_type_a);
return false;
}
int A2DP_GetTrackSampleRate(const uint8_t* p_codec_info) {
tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info);
- LOG_VERBOSE("%s: codec_type = 0x%x", __func__, codec_type);
+ log::verbose("codec_type = 0x{:x}", codec_type);
switch (codec_type) {
case A2DP_MEDIA_CT_SBC:
@@ -1294,14 +1289,14 @@
break;
}
- LOG_ERROR("%s: unsupported codec type 0x%x", __func__, codec_type);
+ log::error("unsupported codec type 0x{:x}", codec_type);
return -1;
}
int A2DP_GetTrackBitsPerSample(const uint8_t* p_codec_info) {
tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info);
- LOG_VERBOSE("%s: codec_type = 0x%x", __func__, codec_type);
+ log::verbose("codec_type = 0x{:x}", codec_type);
switch (codec_type) {
case A2DP_MEDIA_CT_SBC:
@@ -1316,14 +1311,14 @@
break;
}
- LOG_ERROR("%s: unsupported codec type 0x%x", __func__, codec_type);
+ log::error("unsupported codec type 0x{:x}", codec_type);
return -1;
}
int A2DP_GetTrackChannelCount(const uint8_t* p_codec_info) {
tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info);
- LOG_VERBOSE("%s: codec_type = 0x%x", __func__, codec_type);
+ log::verbose("codec_type = 0x{:x}", codec_type);
switch (codec_type) {
case A2DP_MEDIA_CT_SBC:
@@ -1338,14 +1333,14 @@
break;
}
- LOG_ERROR("%s: unsupported codec type 0x%x", __func__, codec_type);
+ log::error("unsupported codec type 0x{:x}", codec_type);
return -1;
}
int A2DP_GetSinkTrackChannelType(const uint8_t* p_codec_info) {
tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info);
- LOG_VERBOSE("%s: codec_type = 0x%x", __func__, codec_type);
+ log::verbose("codec_type = 0x{:x}", codec_type);
switch (codec_type) {
case A2DP_MEDIA_CT_SBC:
@@ -1360,7 +1355,7 @@
break;
}
- LOG_ERROR("%s: unsupported codec type 0x%x", __func__, codec_type);
+ log::error("unsupported codec type 0x{:x}", codec_type);
return -1;
}
@@ -1381,7 +1376,7 @@
break;
}
- LOG_ERROR("%s: unsupported codec type 0x%x", __func__, codec_type);
+ log::error("unsupported codec type 0x{:x}", codec_type);
return false;
}
@@ -1403,7 +1398,7 @@
break;
}
- LOG_ERROR("%s: unsupported codec type 0x%x", __func__, codec_type);
+ log::error("unsupported codec type 0x{:x}", codec_type);
return false;
}
@@ -1411,7 +1406,7 @@
const uint8_t* p_codec_info) {
tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info);
- LOG_VERBOSE("%s: codec_type = 0x%x", __func__, codec_type);
+ log::verbose("codec_type = 0x{:x}", codec_type);
if (::bluetooth::audio::a2dp::provider::supports_codec(
A2DP_SourceCodecIndex(p_codec_info))) {
@@ -1431,7 +1426,7 @@
break;
}
- LOG_ERROR("%s: unsupported codec type 0x%x", __func__, codec_type);
+ log::error("unsupported codec type 0x{:x}", codec_type);
return NULL;
}
@@ -1439,7 +1434,7 @@
const uint8_t* p_codec_info) {
tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info);
- LOG_VERBOSE("%s: codec_type = 0x%x", __func__, codec_type);
+ log::verbose("codec_type = 0x{:x}", codec_type);
switch (codec_type) {
case A2DP_MEDIA_CT_SBC:
@@ -1454,7 +1449,7 @@
break;
}
- LOG_ERROR("%s: unsupported codec type 0x%x", __func__, codec_type);
+ log::error("unsupported codec type 0x{:x}", codec_type);
return NULL;
}
@@ -1474,14 +1469,14 @@
break;
}
- LOG_ERROR("%s: unsupported codec type 0x%x", __func__, codec_type);
+ log::error("unsupported codec type 0x{:x}", codec_type);
return false;
}
btav_a2dp_codec_index_t A2DP_SourceCodecIndex(const uint8_t* p_codec_info) {
tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info);
- LOG_VERBOSE("%s: codec_type = 0x%x", __func__, codec_type);
+ log::verbose("codec_type = 0x{:x}", codec_type);
auto ext_codec_index =
bluetooth::audio::a2dp::provider::source_codec_index(p_codec_info);
@@ -1502,14 +1497,14 @@
break;
}
- LOG_ERROR("%s: unsupported codec type 0x%x", __func__, codec_type);
+ log::error("unsupported codec type 0x{:x}", codec_type);
return BTAV_A2DP_CODEC_INDEX_MAX;
}
btav_a2dp_codec_index_t A2DP_SinkCodecIndex(const uint8_t* p_codec_info) {
tA2DP_CODEC_TYPE codec_type = A2DP_GetCodecType(p_codec_info);
- LOG_VERBOSE("%s: codec_type = 0x%x", __func__, codec_type);
+ log::verbose("codec_type = 0x{:x}", codec_type);
auto ext_codec_index =
bluetooth::audio::a2dp::provider::sink_codec_index(p_codec_info);
@@ -1530,7 +1525,7 @@
break;
}
- LOG_ERROR("%s: unsupported codec type 0x%x", __func__, codec_type);
+ log::error("unsupported codec type 0x{:x}", codec_type);
return BTAV_A2DP_CODEC_INDEX_MAX;
}
@@ -1571,7 +1566,7 @@
bool A2DP_InitCodecConfig(btav_a2dp_codec_index_t codec_index,
AvdtpSepConfig* p_cfg) {
- LOG_VERBOSE("%s: codec %s", __func__, A2DP_CodecIndexStr(codec_index));
+ log::verbose("codec {}", A2DP_CodecIndexStr(codec_index));
/* Default: no content protection info */
p_cfg->num_protect = 0;
diff --git a/system/stack/a2dp/a2dp_ext.cc b/system/stack/a2dp/a2dp_ext.cc
index 0eec9b6..a0bb2eb 100644
--- a/system/stack/a2dp/a2dp_ext.cc
+++ b/system/stack/a2dp/a2dp_ext.cc
@@ -17,10 +17,13 @@
#include "a2dp_ext.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include "a2dp_codec_api.h"
#include "audio_hal_interface/a2dp_encoding.h"
+using namespace bluetooth;
+
static uint64_t codec_id(btav_a2dp_codec_index_t codec_index) {
uint64_t id = 0;
auto result = ::bluetooth::audio::a2dp::provider::codec_info(
@@ -62,7 +65,7 @@
std::vector<provider::a2dp_remote_capabilities>{capabilities},
codec_user_config_);
if (!result.has_value()) {
- LOG(ERROR) << "Failed to set a configuration for " << name_;
+ log::error("Failed to set a configuration for {}", name_);
return false;
}
diff --git a/system/stack/a2dp/a2dp_sbc.cc b/system/stack/a2dp/a2dp_sbc.cc
index 2928f8e..d50fd53 100644
--- a/system/stack/a2dp/a2dp_sbc.cc
+++ b/system/stack/a2dp/a2dp_sbc.cc
@@ -27,7 +27,7 @@
#include "a2dp_sbc.h"
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include <string.h>
#include "a2dp_sbc_decoder.h"
@@ -35,12 +35,13 @@
#include "embdrv/sbc/encoder/include/sbc_encoder.h"
#include "include/check.h"
#include "internal_include/bt_trace.h"
-#include "os/log.h"
#include "osi/include/osi.h"
#include "stack/include/bt_hdr.h"
#define A2DP_SBC_MAX_BITPOOL 53
+using namespace bluetooth;
+
/* data type for the SBC Codec Information Element */
typedef struct {
uint8_t samp_freq; /* Sampling frequency */
@@ -335,7 +336,7 @@
void A2DP_InitDefaultCodecSbc(uint8_t* p_codec_info) {
if (A2DP_BuildInfoSbc(AVDT_MEDIA_TYPE_AUDIO, &a2dp_sbc_default_config,
p_codec_info) != A2DP_SUCCESS) {
- LOG_ERROR("%s: A2DP_BuildInfoSbc failed", __func__);
+ log::error("A2DP_BuildInfoSbc failed");
}
}
@@ -354,26 +355,26 @@
/* parse configuration */
status = A2DP_ParseInfoSbc(&cfg_cie, p_codec_info, is_capability);
if (status != A2DP_SUCCESS) {
- LOG_ERROR("%s: parsing failed %d", __func__, status);
+ log::error("parsing failed {}", status);
return status;
}
/* verify that each parameter is in range */
- LOG_VERBOSE("%s: FREQ peer: 0x%x, capability 0x%x", __func__,
- cfg_cie.samp_freq, p_cap->samp_freq);
- LOG_VERBOSE("%s: CH_MODE peer: 0x%x, capability 0x%x", __func__,
- cfg_cie.ch_mode, p_cap->ch_mode);
- LOG_VERBOSE("%s: BLOCK_LEN peer: 0x%x, capability 0x%x", __func__,
- cfg_cie.block_len, p_cap->block_len);
- LOG_VERBOSE("%s: SUB_BAND peer: 0x%x, capability 0x%x", __func__,
- cfg_cie.num_subbands, p_cap->num_subbands);
- LOG_VERBOSE("%s: ALLOC_METHOD peer: 0x%x, capability 0x%x", __func__,
- cfg_cie.alloc_method, p_cap->alloc_method);
- LOG_VERBOSE("%s: MIN_BitPool peer: 0x%x, capability 0x%x", __func__,
- cfg_cie.min_bitpool, p_cap->min_bitpool);
- LOG_VERBOSE("%s: MAX_BitPool peer: 0x%x, capability 0x%x", __func__,
- cfg_cie.max_bitpool, p_cap->max_bitpool);
+ log::verbose("FREQ peer: 0x{:x}, capability 0x{:x}", cfg_cie.samp_freq,
+ p_cap->samp_freq);
+ log::verbose("CH_MODE peer: 0x{:x}, capability 0x{:x}", cfg_cie.ch_mode,
+ p_cap->ch_mode);
+ log::verbose("BLOCK_LEN peer: 0x{:x}, capability 0x{:x}", cfg_cie.block_len,
+ p_cap->block_len);
+ log::verbose("SUB_BAND peer: 0x{:x}, capability 0x{:x}", cfg_cie.num_subbands,
+ p_cap->num_subbands);
+ log::verbose("ALLOC_METHOD peer: 0x{:x}, capability 0x{:x}",
+ cfg_cie.alloc_method, p_cap->alloc_method);
+ log::verbose("MIN_BitPool peer: 0x{:x}, capability 0x{:x}",
+ cfg_cie.min_bitpool, p_cap->min_bitpool);
+ log::verbose("MAX_BitPool peer: 0x{:x}, capability 0x{:x}",
+ cfg_cie.max_bitpool, p_cap->max_bitpool);
/* sampling frequency */
if ((cfg_cie.samp_freq & p_cap->samp_freq) == 0) return A2DP_NS_SAMP_FREQ;
@@ -410,12 +411,12 @@
tA2DP_STATUS a2dp_status =
A2DP_ParseInfoSbc(&sbc_cie_a, p_codec_info_a, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
a2dp_status = A2DP_ParseInfoSbc(&sbc_cie_b, p_codec_info_b, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
@@ -434,12 +435,12 @@
tA2DP_STATUS a2dp_status =
A2DP_ParseInfoSbc(&sbc_cie_a, p_codec_info_a, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
a2dp_status = A2DP_ParseInfoSbc(&sbc_cie_b, p_codec_info_b, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
@@ -463,7 +464,7 @@
tA2DP_STATUS a2dp_status = A2DP_ParseInfoSbc(&sbc_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -488,7 +489,7 @@
tA2DP_STATUS a2dp_status = A2DP_ParseInfoSbc(&sbc_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -501,7 +502,7 @@
tA2DP_STATUS a2dp_status = A2DP_ParseInfoSbc(&sbc_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -524,7 +525,7 @@
tA2DP_STATUS a2dp_status = A2DP_ParseInfoSbc(&sbc_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -545,7 +546,7 @@
tA2DP_STATUS a2dp_status = A2DP_ParseInfoSbc(&sbc_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -570,7 +571,7 @@
tA2DP_STATUS a2dp_status = A2DP_ParseInfoSbc(&sbc_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -591,7 +592,7 @@
tA2DP_STATUS a2dp_status = A2DP_ParseInfoSbc(&sbc_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -616,7 +617,7 @@
tA2DP_STATUS a2dp_status = A2DP_ParseInfoSbc(&sbc_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -641,7 +642,7 @@
tA2DP_STATUS a2dp_status = A2DP_ParseInfoSbc(&sbc_cie, p_codec_info, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -653,7 +654,7 @@
tA2DP_STATUS a2dp_status = A2DP_ParseInfoSbc(&sbc_cie, p_codec_info, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -666,7 +667,7 @@
tA2DP_STATUS a2dp_status = A2DP_ParseInfoSbc(&sbc_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -798,8 +799,8 @@
// Updated the max bitpool
if (cfg_cie.max_bitpool > A2DP_SBC_MAX_BITPOOL) {
- LOG_WARN("%s: Updated the SBC codec max bitpool from %d to %d", __func__,
- cfg_cie.max_bitpool, A2DP_SBC_MAX_BITPOOL);
+ log::warn("Updated the SBC codec max bitpool from {} to {}",
+ cfg_cie.max_bitpool, A2DP_SBC_MAX_BITPOOL);
cfg_cie.max_bitpool = A2DP_SBC_MAX_BITPOOL;
}
@@ -891,7 +892,7 @@
// Load the encoder
if (!A2DP_LoadEncoderSbc()) {
- LOG_ERROR("%s: cannot load the encoder", __func__);
+ log::error("cannot load the encoder");
return false;
}
@@ -1092,8 +1093,7 @@
tA2DP_STATUS status =
A2DP_ParseInfoSbc(&peer_info_cie, p_peer_codec_info, is_capability);
if (status != A2DP_SUCCESS) {
- LOG_ERROR("%s: can't parse peer's capabilities: error = %d", __func__,
- status);
+ log::error("can't parse peer's capabilities: error = {}", status);
goto fail;
}
// Try using the prefered peer codec config (if valid), instead of the peer
@@ -1195,10 +1195,9 @@
}
} while (false);
if (codec_config_.sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) {
- LOG_ERROR(
- "%s: cannot match sample frequency: local caps = 0x%x "
- "peer info = 0x%x",
- __func__, p_a2dp_sbc_caps->samp_freq, peer_info_cie.samp_freq);
+ log::error(
+ "cannot match sample frequency: local caps = 0x{:x} peer info = 0x{:x}",
+ p_a2dp_sbc_caps->samp_freq, peer_info_cie.samp_freq);
goto fail;
}
@@ -1250,8 +1249,8 @@
}
} while (false);
if (codec_config_.bits_per_sample == BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) {
- LOG_ERROR("%s: cannot match bits per sample: user preference = 0x%x",
- __func__, codec_user_config_.bits_per_sample);
+ log::error("cannot match bits per sample: user preference = 0x{:x}",
+ codec_user_config_.bits_per_sample);
goto fail;
}
@@ -1343,10 +1342,9 @@
}
} while (false);
if (codec_config_.channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) {
- LOG_ERROR(
- "%s: cannot match channel mode: local caps = 0x%x "
- "peer info = 0x%x",
- __func__, p_a2dp_sbc_caps->ch_mode, peer_info_cie.ch_mode);
+ log::error(
+ "cannot match channel mode: local caps = 0x{:x} peer info = 0x{:x}",
+ p_a2dp_sbc_caps->ch_mode, peer_info_cie.ch_mode);
goto fail;
}
@@ -1363,10 +1361,9 @@
} else if (block_len & A2DP_SBC_IE_BLOCKS_4) {
result_config_cie.block_len = A2DP_SBC_IE_BLOCKS_4;
} else {
- LOG_ERROR(
- "%s: cannot match block length: local caps = 0x%x "
- "peer info = 0x%x",
- __func__, p_a2dp_sbc_caps->block_len, peer_info_cie.block_len);
+ log::error(
+ "cannot match block length: local caps = 0x{:x} peer info = 0x{:x}",
+ p_a2dp_sbc_caps->block_len, peer_info_cie.block_len);
goto fail;
}
@@ -1379,10 +1376,10 @@
} else if (num_subbands & A2DP_SBC_IE_SUBBAND_4) {
result_config_cie.num_subbands = A2DP_SBC_IE_SUBBAND_4;
} else {
- LOG_ERROR(
- "%s: cannot match number of sub-bands: local caps = 0x%x "
- "peer info = 0x%x",
- __func__, p_a2dp_sbc_caps->num_subbands, peer_info_cie.num_subbands);
+ log::error(
+ "cannot match number of sub-bands: local caps = 0x{:x} peer info = "
+ "0x{:x}",
+ p_a2dp_sbc_caps->num_subbands, peer_info_cie.num_subbands);
goto fail;
}
@@ -1395,10 +1392,10 @@
} else if (alloc_method & A2DP_SBC_IE_ALLOC_MD_S) {
result_config_cie.alloc_method = A2DP_SBC_IE_ALLOC_MD_S;
} else {
- LOG_ERROR(
- "%s: cannot match allocation method: local caps = 0x%x "
- "peer info = 0x%x",
- __func__, p_a2dp_sbc_caps->alloc_method, peer_info_cie.alloc_method);
+ log::error(
+ "cannot match allocation method: local caps = 0x{:x} peer info = "
+ "0x{:x}",
+ p_a2dp_sbc_caps->alloc_method, peer_info_cie.alloc_method);
goto fail;
}
@@ -1412,10 +1409,10 @@
if (result_config_cie.max_bitpool > peer_info_cie.max_bitpool)
result_config_cie.max_bitpool = peer_info_cie.max_bitpool;
if (result_config_cie.min_bitpool > result_config_cie.max_bitpool) {
- LOG_ERROR(
- "%s: cannot match min/max bitpool: "
- "local caps min/max = 0x%x/0x%x peer info min/max = 0x%x/0x%x",
- __func__, p_a2dp_sbc_caps->min_bitpool, p_a2dp_sbc_caps->max_bitpool,
+ log::error(
+ "cannot match min/max bitpool: local caps min/max = 0x{:x}/0x{:x} peer "
+ "info min/max = 0x{:x}/0x{:x}",
+ p_a2dp_sbc_caps->min_bitpool, p_a2dp_sbc_caps->max_bitpool,
peer_info_cie.min_bitpool, peer_info_cie.max_bitpool);
goto fail;
}
@@ -1486,8 +1483,7 @@
tA2DP_STATUS status =
A2DP_ParseInfoSbc(&peer_info_cie, p_peer_codec_capabilities, true);
if (status != A2DP_SUCCESS) {
- LOG_ERROR("%s: can't parse peer's capabilities: error = %d", __func__,
- status);
+ log::error("can't parse peer's capabilities: error = {}", status);
goto fail;
}
@@ -1551,7 +1547,7 @@
// Load the decoder
if (!A2DP_LoadDecoderSbc()) {
- LOG_ERROR("%s: cannot load the decoder", __func__);
+ log::error("cannot load the decoder");
return false;
}
diff --git a/system/stack/a2dp/a2dp_sbc_decoder.cc b/system/stack/a2dp/a2dp_sbc_decoder.cc
index da28cac..ed3324a 100644
--- a/system/stack/a2dp/a2dp_sbc_decoder.cc
+++ b/system/stack/a2dp/a2dp_sbc_decoder.cc
@@ -18,13 +18,19 @@
#include "a2dp_sbc_decoder.h"
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include "embdrv/sbc/decoder/include/oi_codec_sbc.h"
#include "embdrv/sbc/decoder/include/oi_status.h"
-#include "os/log.h"
#include "stack/include/bt_hdr.h"
+using namespace bluetooth;
+
+namespace fmt {
+template <>
+struct formatter<OI_STATUS> : enum_formatter<OI_STATUS> {};
+} // namespace fmt
+
typedef struct {
OI_CODEC_SBC_DECODER_CONTEXT decoder_context;
uint32_t context_data[CODEC_DATA_WORDS(2, SBC_CODEC_FAST_FILTER_BUFFERS)];
@@ -46,8 +52,7 @@
&a2dp_sbc_decoder_cb.decoder_context, a2dp_sbc_decoder_cb.context_data,
sizeof(a2dp_sbc_decoder_cb.context_data), 2, 2, false);
if (!OI_SUCCESS(status)) {
- LOG_ERROR("%s: OI_CODEC_SBC_DecoderReset failed with error code %d",
- __func__, status);
+ log::error("OI_CODEC_SBC_DecoderReset failed with error code {}", status);
return false;
}
@@ -64,7 +69,7 @@
size_t data_size = p_buf->len;
if (data_size == 0) {
- LOG_ERROR("%s: Empty packet", __func__);
+ log::error("Empty packet");
return false;
}
size_t num_frames = data[0] & 0xf;
@@ -82,7 +87,7 @@
OI_CODEC_SBC_DecodeFrame(&a2dp_sbc_decoder_cb.decoder_context, &oi_data,
&oi_size, out_ptr, &out_size);
if (!OI_SUCCESS(status)) {
- LOG_ERROR("%s: Decoding failure: %d", __func__, status);
+ log::error("Decoding failure: {}", status);
return false;
}
out_avail -= out_size;
diff --git a/system/stack/a2dp/a2dp_sbc_encoder.cc b/system/stack/a2dp/a2dp_sbc_encoder.cc
index 9771984..fab6f23 100644
--- a/system/stack/a2dp/a2dp_sbc_encoder.cc
+++ b/system/stack/a2dp/a2dp_sbc_encoder.cc
@@ -21,6 +21,7 @@
#include "a2dp_sbc_encoder.h"
+#include <bluetooth/log.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
@@ -30,7 +31,6 @@
#include "common/time_util.h"
#include "embdrv/sbc/encoder/include/sbc_encoder.h"
#include "internal_include/bt_target.h"
-#include "os/log.h"
#include "osi/include/allocator.h"
#include "stack/include/bt_hdr.h"
@@ -61,6 +61,8 @@
#define A2DP_HDR_SIZE 1
#define A2DP_SBC_OFFSET (AVDT_MEDIA_OFFSET + A2DP_SBC_MPL_HDR_LEN)
+using namespace bluetooth;
+
typedef struct {
uint32_t aa_frame_counter;
int32_t aa_feed_counter;
@@ -169,10 +171,8 @@
*p_restart_output = false;
*p_config_updated = false;
if (!a2dp_codec_config->copyOutOtaCodecConfig(codec_info)) {
- LOG_ERROR(
- "%s: Cannot update the codec encoder for %s: "
- "invalid codec config",
- __func__, a2dp_codec_config->name().c_str());
+ log::error("Cannot update the codec encoder for {}: invalid codec config",
+ a2dp_codec_config->name().c_str());
return;
}
const uint8_t* p_codec_info = codec_info;
@@ -185,9 +185,9 @@
p_feeding_params->bits_per_sample =
a2dp_codec_config->getAudioBitsPerSample();
p_feeding_params->channel_count = A2DP_GetTrackChannelCountSbc(p_codec_info);
- LOG_INFO("%s: sample_rate=%u bits_per_sample=%u channel_count=%u", __func__,
- p_feeding_params->sample_rate, p_feeding_params->bits_per_sample,
- p_feeding_params->channel_count);
+ log::info("sample_rate={} bits_per_sample={} channel_count={}",
+ p_feeding_params->sample_rate, p_feeding_params->bits_per_sample,
+ p_feeding_params->channel_count);
a2dp_sbc_feeding_reset();
// The codec parameters
@@ -204,18 +204,18 @@
// Reset invalid parameters
if (!p_encoder_params->s16NumOfSubBands) {
- LOG_WARN("%s: SubBands are set to 0, resetting to max (%d)", __func__,
- SBC_MAX_NUM_OF_SUBBANDS);
+ log::warn("SubBands are set to 0, resetting to max ({})",
+ SBC_MAX_NUM_OF_SUBBANDS);
p_encoder_params->s16NumOfSubBands = SBC_MAX_NUM_OF_SUBBANDS;
}
if (!p_encoder_params->s16NumOfBlocks) {
- LOG_WARN("%s: Blocks are set to 0, resetting to max (%d)", __func__,
- SBC_MAX_NUM_OF_BLOCKS);
+ log::warn("Blocks are set to 0, resetting to max ({})",
+ SBC_MAX_NUM_OF_BLOCKS);
p_encoder_params->s16NumOfBlocks = SBC_MAX_NUM_OF_BLOCKS;
}
if (!p_encoder_params->s16NumOfChannels) {
- LOG_WARN("%s: Channels are set to 0, resetting to max (%d)", __func__,
- SBC_MAX_NUM_OF_CHANNELS);
+ log::warn("Channels are set to 0, resetting to max ({})",
+ SBC_MAX_NUM_OF_CHANNELS);
p_encoder_params->s16NumOfChannels = SBC_MAX_NUM_OF_CHANNELS;
}
@@ -234,16 +234,16 @@
p_encoder_params->u16BitRate = a2dp_sbc_source_rate(peer_params.is_peer_edr);
a2dp_sbc_encoder_cb.TxAaMtuSize = adjust_effective_mtu(peer_params);
- LOG_INFO("%s: MTU=%d, peer_mtu=%d min_bitpool=%d max_bitpool=%d", __func__,
- a2dp_sbc_encoder_cb.TxAaMtuSize, peer_params.peer_mtu, min_bitpool,
- max_bitpool);
- LOG_INFO(
- "%s: ChannelMode=%d, NumOfSubBands=%d, NumOfBlocks=%d, "
- "AllocationMethod=%d, BitRate=%d, SamplingFreq=%d BitPool=%d",
- __func__, p_encoder_params->s16ChannelMode,
- p_encoder_params->s16NumOfSubBands, p_encoder_params->s16NumOfBlocks,
- p_encoder_params->s16AllocationMethod, p_encoder_params->u16BitRate,
- s16SamplingFreq, p_encoder_params->s16BitPool);
+ log::info("MTU={}, peer_mtu={} min_bitpool={} max_bitpool={}",
+ a2dp_sbc_encoder_cb.TxAaMtuSize, peer_params.peer_mtu, min_bitpool,
+ max_bitpool);
+ log::info(
+ "ChannelMode={}, NumOfSubBands={}, NumOfBlocks={}, AllocationMethod={}, "
+ "BitRate={}, SamplingFreq={} BitPool={}",
+ p_encoder_params->s16ChannelMode, p_encoder_params->s16NumOfSubBands,
+ p_encoder_params->s16NumOfBlocks, p_encoder_params->s16AllocationMethod,
+ p_encoder_params->u16BitRate, s16SamplingFreq,
+ p_encoder_params->s16BitPool);
do {
if ((p_encoder_params->s16ChannelMode == SBC_JOINT_STEREO) ||
@@ -293,17 +293,17 @@
if (s16BitPool < 0) s16BitPool = 0;
- LOG_VERBOSE("%s: bitpool candidate: %d (%d kbps)", __func__, s16BitPool,
- p_encoder_params->u16BitRate);
+ log::verbose("bitpool candidate: {} ({} kbps)", s16BitPool,
+ p_encoder_params->u16BitRate);
if (s16BitPool > max_bitpool) {
- LOG_VERBOSE("%s: computed bitpool too large (%d)", __func__, s16BitPool);
+ log::verbose("computed bitpool too large ({})", s16BitPool);
/* Decrease bitrate */
p_encoder_params->u16BitRate -= A2DP_SBC_BITRATE_STEP;
/* Record that we have decreased the bitrate */
protect |= 1;
} else if (s16BitPool < min_bitpool) {
- LOG_WARN("%s: computed bitpool too small (%d)", __func__, s16BitPool);
+ log::warn("computed bitpool too small ({})", s16BitPool);
/* Increase bitrate */
uint16_t previous_u16BitRate = p_encoder_params->u16BitRate;
@@ -317,7 +317,7 @@
}
/* In case we have already increased and decreased the bitrate, just stop */
if (protect == 3) {
- LOG_ERROR("%s: could not find bitpool in range", __func__);
+ log::error("could not find bitpool in range");
break;
}
} while (true);
@@ -325,8 +325,8 @@
/* Finally update the bitpool in the encoder structure */
p_encoder_params->s16BitPool = s16BitPool;
- LOG_INFO("%s: final bit rate %d, final bit pool %d", __func__,
- p_encoder_params->u16BitRate, p_encoder_params->s16BitPool);
+ log::info("final bit rate {}, final bit pool {}",
+ p_encoder_params->u16BitRate, p_encoder_params->s16BitPool);
/* Reset the SBC encoder */
SBC_Encoder_Init(&a2dp_sbc_encoder_cb.sbc_encoder_params);
@@ -349,8 +349,8 @@
A2DP_SBC_ENCODER_INTERVAL_MS) /
1000;
- LOG_INFO("%s: PCM bytes per tick %u", __func__,
- a2dp_sbc_encoder_cb.feeding_state.bytes_per_tick);
+ log::info("PCM bytes per tick {}",
+ a2dp_sbc_encoder_cb.feeding_state.bytes_per_tick);
}
void a2dp_sbc_feeding_flush(void) {
@@ -371,8 +371,8 @@
uint8_t nb_iterations = 0;
a2dp_sbc_get_num_frame_iteration(&nb_iterations, &nb_frame, timestamp_us);
- LOG_VERBOSE("%s: Sending %d frames per iteration, %d iterations", __func__,
- nb_frame, nb_iterations);
+ log::verbose("Sending {} frames per iteration, {} iterations", nb_frame,
+ nb_iterations);
if (nb_frame == 0) return;
for (uint8_t counter = 0; counter < nb_iterations; counter++) {
@@ -396,7 +396,7 @@
a2dp_sbc_encoder_cb.sbc_encoder_params.s16NumOfBlocks *
a2dp_sbc_encoder_cb.feeding_params.channel_count *
a2dp_sbc_encoder_cb.feeding_params.bits_per_sample / 8;
- LOG_VERBOSE("%s: pcm_bytes_per_frame %u", __func__, pcm_bytes_per_frame);
+ log::verbose("pcm_bytes_per_frame {}", pcm_bytes_per_frame);
uint32_t us_this_tick = A2DP_SBC_ENCODER_INTERVAL_MS * 1000;
uint64_t now_us = timestamp_us;
@@ -415,8 +415,8 @@
a2dp_sbc_encoder_cb.stats.media_read_total_expected_frames += projected_nof;
if (projected_nof > MAX_PCM_FRAME_NUM_PER_TICK) {
- LOG_WARN("%s: limiting frames to be sent from %d to %d", __func__,
- projected_nof, MAX_PCM_FRAME_NUM_PER_TICK);
+ log::warn("limiting frames to be sent from {} to {}", projected_nof,
+ MAX_PCM_FRAME_NUM_PER_TICK);
// Update the stats
size_t delta = projected_nof - MAX_PCM_FRAME_NUM_PER_TICK;
@@ -425,26 +425,25 @@
projected_nof = MAX_PCM_FRAME_NUM_PER_TICK;
}
- LOG_VERBOSE("%s: frames for available PCM data %u", __func__, projected_nof);
+ log::verbose("frames for available PCM data {}", projected_nof);
if (a2dp_sbc_encoder_cb.peer_params.is_peer_edr) {
if (!a2dp_sbc_encoder_cb.tx_sbc_frames) {
- LOG_ERROR("%s: tx_sbc_frames not updated, update from here", __func__);
+ log::error("tx_sbc_frames not updated, update from here");
a2dp_sbc_encoder_cb.tx_sbc_frames = calculate_max_frames_per_packet();
}
nof = a2dp_sbc_encoder_cb.tx_sbc_frames;
if (!nof) {
- LOG_ERROR("%s: number of frames not updated, set calculated values",
- __func__);
+ log::error("number of frames not updated, set calculated values");
nof = projected_nof;
noi = 1;
} else {
if (nof < projected_nof) {
noi = projected_nof / nof; // number of iterations would vary
if (noi > A2DP_SBC_MAX_PCM_ITER_NUM_PER_TICK) {
- LOG_ERROR("%s: Audio Congestion (iterations:%d > max (%d))", __func__,
- noi, A2DP_SBC_MAX_PCM_ITER_NUM_PER_TICK);
+ log::error("Audio Congestion (iterations:{} > max ({}))", noi,
+ A2DP_SBC_MAX_PCM_ITER_NUM_PER_TICK);
noi = A2DP_SBC_MAX_PCM_ITER_NUM_PER_TICK;
a2dp_sbc_encoder_cb.feeding_state.counter =
noi * nof * (float)pcm_bytes_per_frame;
@@ -452,16 +451,16 @@
projected_nof = nof;
} else {
noi = 1; // number of iterations is 1
- LOG_VERBOSE("%s: reducing frames for available PCM data", __func__);
+ log::verbose("reducing frames for available PCM data");
nof = projected_nof;
}
}
} else {
// For BR cases nof will be same as the value retrieved at projected_nof
- LOG_VERBOSE("%s: headset BR, number of frames %u", __func__, nof);
+ log::verbose("headset BR, number of frames {}", nof);
if (projected_nof > MAX_PCM_FRAME_NUM_PER_TICK) {
- LOG_ERROR("%s: Audio Congestion (frames: %d > max (%d))", __func__,
- projected_nof, MAX_PCM_FRAME_NUM_PER_TICK);
+ log::error("Audio Congestion (frames: {} > max ({}))", projected_nof,
+ MAX_PCM_FRAME_NUM_PER_TICK);
// Update the stats
size_t delta = projected_nof - MAX_PCM_FRAME_NUM_PER_TICK;
@@ -475,8 +474,7 @@
}
a2dp_sbc_encoder_cb.feeding_state.counter -=
noi * nof * (float)pcm_bytes_per_frame;
- LOG_VERBOSE("%s: effective num of frames %u, iterations %u", __func__, nof,
- noi);
+ log::verbose("effective num of frames {}, iterations {}", nof, noi);
*num_of_frames = nof;
*num_of_iterations = noi;
@@ -520,8 +518,8 @@
bytes_read += num_bytes;
} else {
- LOG_WARN("%s: underflow %d, %d", __func__, nb_frame,
- a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue);
+ log::warn("underflow {}, {}", nb_frame,
+ a2dp_sbc_encoder_cb.feeding_state.aa_feed_residue);
a2dp_sbc_encoder_cb.feeding_state.counter +=
nb_frame * p_encoder_params->s16NumOfSubBands *
p_encoder_params->s16NumOfBlocks *
@@ -719,16 +717,15 @@
if (mtu_size > peer_params.peer_mtu) {
mtu_size = peer_params.peer_mtu;
}
- LOG_VERBOSE("%s: original AVDTP MTU size: %d", __func__, mtu_size);
+ log::verbose("original AVDTP MTU size: {}", mtu_size);
if (peer_params.is_peer_edr && !peer_params.peer_supports_3mbps) {
// This condition would be satisfied only if the remote device is
// EDR and supports only 2 Mbps, but the effective AVDTP MTU size
// exceeds the 2DH5 packet size.
- LOG_VERBOSE("%s: The remote device is EDR but does not support 3 Mbps",
- __func__);
+ log::verbose("The remote device is EDR but does not support 3 Mbps");
if (mtu_size > MAX_2MBPS_AVDTP_MTU) {
- LOG_WARN("%s: Restricting AVDTP MTU size from %d to %d", __func__,
- mtu_size, MAX_2MBPS_AVDTP_MTU);
+ log::warn("Restricting AVDTP MTU size from {} to {}", mtu_size,
+ MAX_2MBPS_AVDTP_MTU);
mtu_size = MAX_2MBPS_AVDTP_MTU;
}
}
@@ -745,49 +742,47 @@
const uint16_t& effective_mtu_size = a2dp_sbc_encoder_cb.TxAaMtuSize;
if (!p_encoder_params->s16NumOfSubBands) {
- LOG_ERROR("%s: SubBands are set to 0, resetting to %d", __func__,
- SBC_MAX_NUM_OF_SUBBANDS);
+ log::error("SubBands are set to 0, resetting to {}",
+ SBC_MAX_NUM_OF_SUBBANDS);
p_encoder_params->s16NumOfSubBands = SBC_MAX_NUM_OF_SUBBANDS;
}
if (!p_encoder_params->s16NumOfBlocks) {
- LOG_ERROR("%s: Blocks are set to 0, resetting to %d", __func__,
- SBC_MAX_NUM_OF_BLOCKS);
+ log::error("Blocks are set to 0, resetting to {}", SBC_MAX_NUM_OF_BLOCKS);
p_encoder_params->s16NumOfBlocks = SBC_MAX_NUM_OF_BLOCKS;
}
if (!p_encoder_params->s16NumOfChannels) {
- LOG_ERROR("%s: Channels are set to 0, resetting to %d", __func__,
- SBC_MAX_NUM_OF_CHANNELS);
+ log::error("Channels are set to 0, resetting to {}",
+ SBC_MAX_NUM_OF_CHANNELS);
p_encoder_params->s16NumOfChannels = SBC_MAX_NUM_OF_CHANNELS;
}
frame_len = a2dp_sbc_frame_length();
- LOG_VERBOSE("%s: Effective Tx MTU to be considered: %d", __func__,
- effective_mtu_size);
+ log::verbose("Effective Tx MTU to be considered: {}", effective_mtu_size);
switch (p_encoder_params->s16SamplingFreq) {
case SBC_sf44100:
if (frame_len == 0) {
- LOG_ERROR("%s: Calculating frame length, resetting it to default %d",
- __func__, A2DP_SBC_MAX_HQ_FRAME_SIZE_44_1);
+ log::error("Calculating frame length, resetting it to default {}",
+ A2DP_SBC_MAX_HQ_FRAME_SIZE_44_1);
frame_len = A2DP_SBC_MAX_HQ_FRAME_SIZE_44_1;
}
result = (effective_mtu_size - A2DP_HDR_SIZE) / frame_len;
- LOG_VERBOSE("%s: Max number of SBC frames: %d", __func__, result);
+ log::verbose("Max number of SBC frames: {}", result);
break;
case SBC_sf48000:
if (frame_len == 0) {
- LOG_ERROR("%s: Calculating frame length, resetting it to default %d",
- __func__, A2DP_SBC_MAX_HQ_FRAME_SIZE_48);
+ log::error("Calculating frame length, resetting it to default {}",
+ A2DP_SBC_MAX_HQ_FRAME_SIZE_48);
frame_len = A2DP_SBC_MAX_HQ_FRAME_SIZE_48;
}
result = (effective_mtu_size - A2DP_HDR_SIZE) / frame_len;
- LOG_VERBOSE("%s: Max number of SBC frames: %d", __func__, result);
+ log::verbose("Max number of SBC frames: {}", result);
break;
default:
- LOG_ERROR("%s: Max number of SBC frames: %d", __func__, result);
+ log::error("Max number of SBC frames: {}", result);
break;
}
return result;
@@ -799,8 +794,7 @@
/* restrict bitrate if a2dp link is non-edr */
if (!is_peer_edr) {
rate = A2DP_SBC_NON_EDR_MAX_RATE;
- LOG_VERBOSE("%s: non-edr a2dp sink detected, restrict rate to %d", __func__,
- rate);
+ log::verbose("non-edr a2dp sink detected, restrict rate to {}", rate);
}
return rate;
@@ -810,13 +804,12 @@
SBC_ENC_PARAMS* p_encoder_params = &a2dp_sbc_encoder_cb.sbc_encoder_params;
uint32_t frame_len = 0;
- LOG_VERBOSE(
- "%s: channel mode: %d, sub-band: %d, number of block: %d, "
- "bitpool: %d, sampling frequency: %d, num channels: %d",
- __func__, p_encoder_params->s16ChannelMode,
- p_encoder_params->s16NumOfSubBands, p_encoder_params->s16NumOfBlocks,
- p_encoder_params->s16BitPool, p_encoder_params->s16SamplingFreq,
- p_encoder_params->s16NumOfChannels);
+ log::verbose(
+ "channel mode: {}, sub-band: {}, number of block: {}, bitpool: {}, "
+ "sampling frequency: {}, num channels: {}",
+ p_encoder_params->s16ChannelMode, p_encoder_params->s16NumOfSubBands,
+ p_encoder_params->s16NumOfBlocks, p_encoder_params->s16BitPool,
+ p_encoder_params->s16SamplingFreq, p_encoder_params->s16NumOfChannels);
switch (p_encoder_params->s16ChannelMode) {
case SBC_MONO:
@@ -854,17 +847,17 @@
CHAR_BIT);
break;
default:
- LOG_VERBOSE("%s: Invalid channel number: %d", __func__,
- p_encoder_params->s16ChannelMode);
+ log::verbose("Invalid channel number: {}",
+ p_encoder_params->s16ChannelMode);
break;
}
- LOG_VERBOSE("%s: calculated frame length: %d", __func__, frame_len);
+ log::verbose("calculated frame length: {}", frame_len);
return frame_len;
}
uint32_t a2dp_sbc_get_bitrate() {
SBC_ENC_PARAMS* p_encoder_params = &a2dp_sbc_encoder_cb.sbc_encoder_params;
- LOG_INFO("%s: bit rate %d ", __func__, p_encoder_params->u16BitRate);
+ log::info("bit rate {} ", p_encoder_params->u16BitRate);
return p_encoder_params->u16BitRate * 1000;
}
diff --git a/system/stack/a2dp/a2dp_vendor_aptx.cc b/system/stack/a2dp/a2dp_vendor_aptx.cc
index f718225..7700043 100644
--- a/system/stack/a2dp/a2dp_vendor_aptx.cc
+++ b/system/stack/a2dp/a2dp_vendor_aptx.cc
@@ -25,7 +25,7 @@
#include "a2dp_vendor_aptx.h"
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include <string.h>
#include "a2dp_vendor.h"
@@ -33,10 +33,11 @@
#include "btif/include/btif_av_co.h"
#include "include/check.h"
#include "internal_include/bt_trace.h"
-#include "os/log.h"
#include "osi/include/osi.h"
#include "stack/include/bt_hdr.h"
+using namespace bluetooth;
+
// data type for the aptX Codec Information Element */
typedef struct {
uint32_t vendorId;
@@ -209,16 +210,16 @@
/* parse configuration */
status = A2DP_ParseInfoAptx(&cfg_cie, p_codec_info, is_capability);
if (status != A2DP_SUCCESS) {
- LOG_ERROR("%s: parsing failed %d", __func__, status);
+ log::error("parsing failed {}", status);
return status;
}
/* verify that each parameter is in range */
- LOG_VERBOSE("%s: FREQ peer: 0x%x, capability 0x%x", __func__,
- cfg_cie.sampleRate, p_cap->sampleRate);
- LOG_VERBOSE("%s: CH_MODE peer: 0x%x, capability 0x%x", __func__,
- cfg_cie.channelMode, p_cap->channelMode);
+ log::verbose("FREQ peer: 0x{:x}, capability 0x{:x}", cfg_cie.sampleRate,
+ p_cap->sampleRate);
+ log::verbose("CH_MODE peer: 0x{:x}, capability 0x{:x}", cfg_cie.channelMode,
+ p_cap->channelMode);
/* sampling frequency */
if ((cfg_cie.sampleRate & p_cap->sampleRate) == 0) return A2DP_NS_SAMP_FREQ;
@@ -248,12 +249,12 @@
tA2DP_STATUS a2dp_status =
A2DP_ParseInfoAptx(&aptx_cie_a, p_codec_info_a, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
a2dp_status = A2DP_ParseInfoAptx(&aptx_cie_b, p_codec_info_b, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
@@ -269,12 +270,12 @@
tA2DP_STATUS a2dp_status =
A2DP_ParseInfoAptx(&aptx_cie_a, p_codec_info_a, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
a2dp_status = A2DP_ParseInfoAptx(&aptx_cie_b, p_codec_info_b, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
@@ -295,7 +296,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoAptx(&aptx_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -311,7 +312,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoAptx(&aptx_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -325,7 +326,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoAptx(&aptx_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -451,7 +452,7 @@
// Load the encoder
if (A2DP_VendorLoadEncoderAptx() != LOAD_SUCCESS) {
- LOG_ERROR("%s: cannot load the encoder", __func__);
+ log::error("cannot load the encoder");
return false;
}
@@ -631,8 +632,7 @@
tA2DP_STATUS status =
A2DP_ParseInfoAptx(&peer_info_cie, p_peer_codec_info, is_capability);
if (status != A2DP_SUCCESS) {
- LOG_ERROR("%s: can't parse peer's capabilities: error = %d", __func__,
- status);
+ log::error("can't parse peer's capabilities: error = {}", status);
goto fail;
}
@@ -715,10 +715,9 @@
}
} while (false);
if (codec_config_.sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) {
- LOG_ERROR(
- "%s: cannot match sample frequency: local caps = 0x%x "
- "peer info = 0x%x",
- __func__, a2dp_aptx_source_caps.sampleRate, peer_info_cie.sampleRate);
+ log::error(
+ "cannot match sample frequency: local caps = 0x{:x} peer info = 0x{:x}",
+ a2dp_aptx_source_caps.sampleRate, peer_info_cie.sampleRate);
goto fail;
}
@@ -770,8 +769,8 @@
}
} while (false);
if (codec_config_.bits_per_sample == BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) {
- LOG_ERROR("%s: cannot match bits per sample: user preference = 0x%x",
- __func__, codec_user_config_.bits_per_sample);
+ log::error("cannot match bits per sample: user preference = 0x{:x}",
+ codec_user_config_.bits_per_sample);
goto fail;
}
@@ -841,10 +840,9 @@
}
} while (false);
if (codec_config_.channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) {
- LOG_ERROR(
- "%s: cannot match channel mode: local caps = 0x%x "
- "peer info = 0x%x",
- __func__, a2dp_aptx_source_caps.channelMode, peer_info_cie.channelMode);
+ log::error(
+ "cannot match channel mode: local caps = 0x{:x} peer info = 0x{:x}",
+ a2dp_aptx_source_caps.channelMode, peer_info_cie.channelMode);
goto fail;
}
@@ -921,8 +919,7 @@
tA2DP_STATUS status =
A2DP_ParseInfoAptx(&peer_info_cie, p_peer_codec_capabilities, true);
if (status != A2DP_SUCCESS) {
- LOG_ERROR("%s: can't parse peer's capabilities: error = %d", __func__,
- status);
+ log::error("can't parse peer's capabilities: error = {}", status);
goto fail;
}
diff --git a/system/stack/a2dp/a2dp_vendor_aptx_encoder.cc b/system/stack/a2dp/a2dp_vendor_aptx_encoder.cc
index 3568492..f39b205 100644
--- a/system/stack/a2dp/a2dp_vendor_aptx_encoder.cc
+++ b/system/stack/a2dp/a2dp_vendor_aptx_encoder.cc
@@ -18,6 +18,7 @@
#include "a2dp_vendor_aptx_encoder.h"
+#include <bluetooth/log.h>
#include <dlfcn.h>
#include <inttypes.h>
#include <stdio.h>
@@ -32,6 +33,8 @@
#include "osi/include/allocator.h"
#include "stack/include/bt_hdr.h"
+using namespace bluetooth;
+
//
// Encoder for aptX Source Codec
//
@@ -142,7 +145,7 @@
if (a2dp_aptx_encoder_cb.aptx_encoder_state != NULL) {
aptx_api.init_func(a2dp_aptx_encoder_cb.aptx_encoder_state, 0);
} else {
- LOG_ERROR("%s: Cannot allocate aptX encoder state", __func__);
+ log::error("Cannot allocate aptX encoder state");
// TODO: Return an error?
}
@@ -167,10 +170,8 @@
*p_restart_output = false;
*p_config_updated = false;
if (!a2dp_codec_config->copyOutOtaCodecConfig(codec_info)) {
- LOG_ERROR(
- "%s: Cannot update the codec encoder for %s: "
- "invalid codec config",
- __func__, a2dp_codec_config->name().c_str());
+ log::error("Cannot update the codec encoder for {}: invalid codec config",
+ a2dp_codec_config->name().c_str());
return;
}
const uint8_t* p_codec_info = codec_info;
@@ -183,9 +184,9 @@
a2dp_codec_config->getAudioBitsPerSample();
p_feeding_params->channel_count =
A2DP_VendorGetTrackChannelCountAptx(p_codec_info);
- LOG_INFO("%s: sample_rate=%u bits_per_sample=%u channel_count=%u", __func__,
- p_feeding_params->sample_rate, p_feeding_params->bits_per_sample,
- p_feeding_params->channel_count);
+ log::info("sample_rate={} bits_per_sample={} channel_count={}",
+ p_feeding_params->sample_rate, p_feeding_params->bits_per_sample,
+ p_feeding_params->channel_count);
a2dp_vendor_aptx_feeding_reset();
}
@@ -220,8 +221,7 @@
}
}
- LOG_INFO("%s: sleep_time_ns = %" PRIu64, __func__,
- framing_params->sleep_time_ns);
+ log::info("{}: sleep_time_ns = %", PRIu64);
}
//
@@ -275,12 +275,10 @@
}
}
- LOG_VERBOSE("%s: sleep_time_ns = %" PRIu64
- " aptx_bytes = %u "
- "pcm_bytes_per_read = %u pcm_reads = %u frame_size_counter = %u",
- __func__, framing_params->sleep_time_ns,
- framing_params->aptx_bytes, framing_params->pcm_bytes_per_read,
- framing_params->pcm_reads, framing_params->frame_size_counter);
+ log::verbose(
+ "{}: sleep_time_ns = %", PRIu64
+ " aptx_bytes = %u "
+ "pcm_bytes_per_read = %u pcm_reads = %u frame_size_counter = %u");
}
void a2dp_vendor_aptx_feeding_reset(void) {
@@ -328,13 +326,13 @@
a2dp_aptx_encoder_cb.stats.media_read_total_expected_read_bytes +=
expected_read_bytes;
- LOG_VERBOSE("%s: PCM read of size %u", __func__, expected_read_bytes);
+ log::verbose("PCM read of size {}", expected_read_bytes);
bytes_read = a2dp_aptx_encoder_cb.read_callback((uint8_t*)read_buffer16,
expected_read_bytes);
a2dp_aptx_encoder_cb.stats.media_read_total_actual_read_bytes += bytes_read;
if (bytes_read < expected_read_bytes) {
- LOG_WARN("%s: underflow at PCM reading: read %u bytes instead of %u",
- __func__, bytes_read, expected_read_bytes);
+ log::warn("underflow at PCM reading: read {} bytes instead of {}",
+ bytes_read, expected_read_bytes);
a2dp_aptx_encoder_cb.stats.media_read_total_dropped_packets++;
osi_free(p_buf);
return;
@@ -352,8 +350,7 @@
const int COMPRESSION_RATIO = 4;
size_t encoded_bytes = pcm_bytes_encoded / COMPRESSION_RATIO;
p_buf->len += encoded_bytes;
- LOG_VERBOSE("%s: encoded %zu PCM bytes to %zu", __func__, pcm_bytes_encoded,
- encoded_bytes);
+ log::verbose("encoded {} PCM bytes to {}", pcm_bytes_encoded, encoded_bytes);
// Update the RTP timestamp
*((uint32_t*)(p_buf + 1)) = a2dp_aptx_encoder_cb.timestamp;
diff --git a/system/stack/a2dp/a2dp_vendor_aptx_hd.cc b/system/stack/a2dp/a2dp_vendor_aptx_hd.cc
index a8d0942..965704c 100644
--- a/system/stack/a2dp/a2dp_vendor_aptx_hd.cc
+++ b/system/stack/a2dp/a2dp_vendor_aptx_hd.cc
@@ -26,6 +26,7 @@
#include "a2dp_vendor_aptx_hd.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <string.h>
#include "a2dp_vendor.h"
@@ -37,6 +38,8 @@
#include "osi/include/osi.h"
#include "stack/include/bt_hdr.h"
+using namespace bluetooth;
+
// data type for the aptX-HD Codec Information Element */
typedef struct {
uint32_t vendorId;
@@ -227,16 +230,16 @@
/* parse configuration */
status = A2DP_ParseInfoAptxHd(&cfg_cie, p_codec_info, is_capability);
if (status != A2DP_SUCCESS) {
- LOG_ERROR("%s: parsing failed %d", __func__, status);
+ log::error("parsing failed {}", status);
return status;
}
/* verify that each parameter is in range */
- LOG_VERBOSE("%s: FREQ peer: 0x%x, capability 0x%x", __func__,
- cfg_cie.sampleRate, p_cap->sampleRate);
- LOG_VERBOSE("%s: CH_MODE peer: 0x%x, capability 0x%x", __func__,
- cfg_cie.channelMode, p_cap->channelMode);
+ log::verbose("FREQ peer: 0x{:x}, capability 0x{:x}", cfg_cie.sampleRate,
+ p_cap->sampleRate);
+ log::verbose("CH_MODE peer: 0x{:x}, capability 0x{:x}", cfg_cie.channelMode,
+ p_cap->channelMode);
/* sampling frequency */
if ((cfg_cie.sampleRate & p_cap->sampleRate) == 0) return A2DP_NS_SAMP_FREQ;
@@ -266,12 +269,12 @@
tA2DP_STATUS a2dp_status =
A2DP_ParseInfoAptxHd(&aptx_hd_cie_a, p_codec_info_a, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
a2dp_status = A2DP_ParseInfoAptxHd(&aptx_hd_cie_b, p_codec_info_b, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
@@ -287,12 +290,12 @@
tA2DP_STATUS a2dp_status =
A2DP_ParseInfoAptxHd(&aptx_hd_cie_a, p_codec_info_a, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
a2dp_status = A2DP_ParseInfoAptxHd(&aptx_hd_cie_b, p_codec_info_b, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
@@ -314,7 +317,7 @@
tA2DP_STATUS a2dp_status =
A2DP_ParseInfoAptxHd(&aptx_hd_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -331,7 +334,7 @@
tA2DP_STATUS a2dp_status =
A2DP_ParseInfoAptxHd(&aptx_hd_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -346,7 +349,7 @@
tA2DP_STATUS a2dp_status =
A2DP_ParseInfoAptxHd(&aptx_hd_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -474,7 +477,7 @@
// Load the encoder
if (A2DP_VendorLoadEncoderAptxHd() != LOAD_SUCCESS) {
- LOG_ERROR("%s: cannot load the encoder", __func__);
+ log::error("cannot load the encoder");
return false;
}
@@ -651,8 +654,7 @@
tA2DP_STATUS status =
A2DP_ParseInfoAptxHd(&peer_info_cie, p_peer_codec_info, is_capability);
if (status != A2DP_SUCCESS) {
- LOG_ERROR("%s: can't parse peer's capabilities: error = %d", __func__,
- status);
+ log::error("can't parse peer's capabilities: error = {}", status);
goto fail;
}
@@ -735,11 +737,9 @@
}
} while (false);
if (codec_config_.sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) {
- LOG_ERROR(
- "%s: cannot match sample frequency: local caps = 0x%x "
- "peer info = 0x%x",
- __func__, a2dp_aptx_hd_source_caps.sampleRate,
- peer_info_cie.sampleRate);
+ log::error(
+ "cannot match sample frequency: local caps = 0x{:x} peer info = 0x{:x}",
+ a2dp_aptx_hd_source_caps.sampleRate, peer_info_cie.sampleRate);
goto fail;
}
@@ -791,8 +791,8 @@
}
} while (false);
if (codec_config_.bits_per_sample == BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) {
- LOG_ERROR("%s: cannot match bits per sample: user preference = 0x%x",
- __func__, codec_user_config_.bits_per_sample);
+ log::error("cannot match bits per sample: user preference = 0x{:x}",
+ codec_user_config_.bits_per_sample);
goto fail;
}
@@ -863,11 +863,9 @@
}
} while (false);
if (codec_config_.channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) {
- LOG_ERROR(
- "%s: cannot match channel mode: local caps = 0x%x "
- "peer info = 0x%x",
- __func__, a2dp_aptx_hd_source_caps.channelMode,
- peer_info_cie.channelMode);
+ log::error(
+ "cannot match channel mode: local caps = 0x{:x} peer info = 0x{:x}",
+ a2dp_aptx_hd_source_caps.channelMode, peer_info_cie.channelMode);
goto fail;
}
@@ -951,8 +949,7 @@
tA2DP_STATUS status =
A2DP_ParseInfoAptxHd(&peer_info_cie, p_peer_codec_capabilities, true);
if (status != A2DP_SUCCESS) {
- LOG_ERROR("%s: can't parse peer's capabilities: error = %d", __func__,
- status);
+ log::error("can't parse peer's capabilities: error = {}", status);
goto fail;
}
diff --git a/system/stack/a2dp/a2dp_vendor_aptx_hd_encoder.cc b/system/stack/a2dp/a2dp_vendor_aptx_hd_encoder.cc
index bfef8c2..a399c24 100644
--- a/system/stack/a2dp/a2dp_vendor_aptx_hd_encoder.cc
+++ b/system/stack/a2dp/a2dp_vendor_aptx_hd_encoder.cc
@@ -18,6 +18,7 @@
#include "a2dp_vendor_aptx_hd_encoder.h"
+#include <bluetooth/log.h>
#include <dlfcn.h>
#include <inttypes.h>
#include <stdio.h>
@@ -32,6 +33,8 @@
#include "osi/include/allocator.h"
#include "stack/include/bt_hdr.h"
+using namespace bluetooth;
+
//
// Encoder for aptX-HD Source Codec
//
@@ -142,7 +145,7 @@
if (a2dp_aptx_hd_encoder_cb.aptx_hd_encoder_state != NULL) {
aptx_hd_api.init_func(a2dp_aptx_hd_encoder_cb.aptx_hd_encoder_state, 0);
} else {
- LOG_ERROR("%s: Cannot allocate aptX-HD encoder state", __func__);
+ log::error("Cannot allocate aptX-HD encoder state");
// TODO: Return an error?
}
@@ -166,10 +169,8 @@
*p_restart_output = false;
*p_config_updated = false;
if (!a2dp_codec_config->copyOutOtaCodecConfig(codec_info)) {
- LOG_ERROR(
- "%s: Cannot update the codec encoder for %s: "
- "invalid codec config",
- __func__, a2dp_codec_config->name().c_str());
+ log::error("Cannot update the codec encoder for {}: invalid codec config",
+ a2dp_codec_config->name().c_str());
return;
}
const uint8_t* p_codec_info = codec_info;
@@ -183,9 +184,9 @@
a2dp_codec_config->getAudioBitsPerSample();
p_feeding_params->channel_count =
A2DP_VendorGetTrackChannelCountAptxHd(p_codec_info);
- LOG_INFO("%s: sample_rate=%u bits_per_sample=%u channel_count=%u", __func__,
- p_feeding_params->sample_rate, p_feeding_params->bits_per_sample,
- p_feeding_params->channel_count);
+ log::info("sample_rate={} bits_per_sample={} channel_count={}",
+ p_feeding_params->sample_rate, p_feeding_params->bits_per_sample,
+ p_feeding_params->channel_count);
a2dp_vendor_aptx_hd_feeding_reset();
}
@@ -208,8 +209,7 @@
framing_params->sleep_time_ns = 9000000;
- LOG_INFO("%s: sleep_time_ns = %" PRIu64, __func__,
- framing_params->sleep_time_ns);
+ log::info("{}: sleep_time_ns = %", PRIu64);
}
//
@@ -258,12 +258,10 @@
framing_params->frame_size_counter = 0;
}
- LOG_VERBOSE("%s: sleep_time_ns = %" PRIu64
- " aptx_hd_bytes = %u "
- "pcm_bytes_per_read = %u pcm_reads = %u frame_size_counter = %u",
- __func__, framing_params->sleep_time_ns,
- framing_params->aptx_hd_bytes, framing_params->pcm_bytes_per_read,
- framing_params->pcm_reads, framing_params->frame_size_counter);
+ log::verbose(
+ "{}: sleep_time_ns = %", PRIu64
+ " aptx_hd_bytes = %u "
+ "pcm_bytes_per_read = %u pcm_reads = %u frame_size_counter = %u");
}
void a2dp_vendor_aptx_hd_feeding_reset(void) {
@@ -313,14 +311,14 @@
a2dp_aptx_hd_encoder_cb.stats.media_read_total_expected_read_bytes +=
expected_read_bytes;
- LOG_VERBOSE("%s: PCM read of size %u", __func__, expected_read_bytes);
+ log::verbose("PCM read of size {}", expected_read_bytes);
bytes_read = a2dp_aptx_hd_encoder_cb.read_callback((uint8_t*)read_buffer32,
expected_read_bytes);
a2dp_aptx_hd_encoder_cb.stats.media_read_total_actual_read_bytes +=
bytes_read;
if (bytes_read < expected_read_bytes) {
- LOG_WARN("%s: underflow at PCM reading: read %u bytes instead of %u",
- __func__, bytes_read, expected_read_bytes);
+ log::warn("underflow at PCM reading: read {} bytes instead of {}",
+ bytes_read, expected_read_bytes);
a2dp_aptx_hd_encoder_cb.stats.media_read_total_dropped_packets++;
osi_free(p_buf);
return;
@@ -339,8 +337,7 @@
const int COMPRESSION_RATIO = 4;
size_t encoded_bytes = pcm_bytes_encoded / COMPRESSION_RATIO;
p_buf->len += encoded_bytes;
- LOG_VERBOSE("%s: encoded %zu PCM bytes to %zu", __func__, pcm_bytes_encoded,
- encoded_bytes);
+ log::verbose("encoded {} PCM bytes to {}", pcm_bytes_encoded, encoded_bytes);
// Update the RTP timestamp
*((uint32_t*)(p_buf + 1)) = a2dp_aptx_hd_encoder_cb.timestamp;
diff --git a/system/stack/a2dp/a2dp_vendor_ldac.cc b/system/stack/a2dp/a2dp_vendor_ldac.cc
index 72a7c7b..356f528 100644
--- a/system/stack/a2dp/a2dp_vendor_ldac.cc
+++ b/system/stack/a2dp/a2dp_vendor_ldac.cc
@@ -26,6 +26,7 @@
#include "a2dp_vendor_ldac.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <string.h>
#include "a2dp_vendor_ldac_decoder.h"
@@ -36,6 +37,8 @@
#include "osi/include/osi.h"
#include "stack/include/bt_hdr.h"
+using namespace bluetooth;
+
// data type for the LDAC Codec Information Element */
// NOTE: bits_per_sample is needed only for LDAC encoder initialization.
typedef struct {
@@ -279,16 +282,16 @@
/* parse configuration */
status = A2DP_ParseInfoLdac(&cfg_cie, p_codec_info, is_capability);
if (status != A2DP_SUCCESS) {
- LOG_ERROR("%s: parsing failed %d", __func__, status);
+ log::error("parsing failed {}", status);
return status;
}
/* verify that each parameter is in range */
- LOG_VERBOSE("%s: FREQ peer: 0x%x, capability 0x%x", __func__,
- cfg_cie.sampleRate, p_cap->sampleRate);
- LOG_VERBOSE("%s: CH_MODE peer: 0x%x, capability 0x%x", __func__,
- cfg_cie.channelMode, p_cap->channelMode);
+ log::verbose("FREQ peer: 0x{:x}, capability 0x{:x}", cfg_cie.sampleRate,
+ p_cap->sampleRate);
+ log::verbose("CH_MODE peer: 0x{:x}, capability 0x{:x}", cfg_cie.channelMode,
+ p_cap->channelMode);
/* sampling frequency */
if ((cfg_cie.sampleRate & p_cap->sampleRate) == 0) return A2DP_NS_SAMP_FREQ;
@@ -318,12 +321,12 @@
tA2DP_STATUS a2dp_status =
A2DP_ParseInfoLdac(&ldac_cie_a, p_codec_info_a, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
a2dp_status = A2DP_ParseInfoLdac(&ldac_cie_b, p_codec_info_b, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
@@ -339,12 +342,12 @@
tA2DP_STATUS a2dp_status =
A2DP_ParseInfoLdac(&ldac_cie_a, p_codec_info_a, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
a2dp_status = A2DP_ParseInfoLdac(&ldac_cie_b, p_codec_info_b, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
@@ -388,7 +391,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoLdac(&ldac_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -416,7 +419,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoLdac(&ldac_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -444,7 +447,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoLdac(&ldac_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -466,7 +469,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoLdac(&ldac_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -488,7 +491,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoLdac(&ldac_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("%s: cannot decode codec information: %d", __func__, a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -699,7 +702,7 @@
// Load the encoder
if (!A2DP_VendorLoadEncoderLdac()) {
- LOG_ERROR("%s: cannot load the encoder", __func__);
+ log::error("cannot load the encoder");
return false;
}
@@ -967,8 +970,7 @@
tA2DP_STATUS status =
A2DP_ParseInfoLdac(&peer_info_cie, p_peer_codec_info, is_capability);
if (status != A2DP_SUCCESS) {
- LOG_ERROR("%s: can't parse peer's capabilities: error = %d", __func__,
- status);
+ log::error("can't parse peer's capabilities: error = {}", status);
goto fail;
}
@@ -1099,10 +1101,9 @@
}
} while (false);
if (codec_config_.sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) {
- LOG_ERROR(
- "%s: cannot match sample frequency: local caps = 0x%x "
- "peer info = 0x%x",
- __func__, p_a2dp_ldac_caps->sampleRate, peer_info_cie.sampleRate);
+ log::error(
+ "cannot match sample frequency: local caps = 0x{:x} peer info = 0x{:x}",
+ p_a2dp_ldac_caps->sampleRate, peer_info_cie.sampleRate);
goto fail;
}
@@ -1174,10 +1175,10 @@
}
} while (false);
if (codec_config_.bits_per_sample == BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) {
- LOG_ERROR(
- "%s: cannot match bits per sample: default = 0x%x "
- "user preference = 0x%x",
- __func__, a2dp_ldac_default_config.bits_per_sample,
+ log::error(
+ "cannot match bits per sample: default = 0x{:x} user preference = "
+ "0x{:x}",
+ a2dp_ldac_default_config.bits_per_sample,
codec_user_config_.bits_per_sample);
goto fail;
}
@@ -1261,10 +1262,9 @@
}
} while (false);
if (codec_config_.channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) {
- LOG_ERROR(
- "%s: cannot match channel mode: local caps = 0x%x "
- "peer info = 0x%x",
- __func__, p_a2dp_ldac_caps->channelMode, peer_info_cie.channelMode);
+ log::error(
+ "cannot match channel mode: local caps = 0x{:x} peer info = 0x{:x}",
+ p_a2dp_ldac_caps->channelMode, peer_info_cie.channelMode);
goto fail;
}
@@ -1334,8 +1334,7 @@
tA2DP_STATUS status =
A2DP_ParseInfoLdac(&peer_info_cie, p_peer_codec_capabilities, true);
if (status != A2DP_SUCCESS) {
- LOG_ERROR("%s: can't parse peer's capabilities: error = %d", __func__,
- status);
+ log::error("can't parse peer's capabilities: error = {}", status);
goto fail;
}
@@ -1411,7 +1410,7 @@
// Load the decoder
if (!A2DP_VendorLoadDecoderLdac()) {
- LOG_ERROR("%s: cannot load the decoder", __func__);
+ log::error("cannot load the decoder");
return false;
}
diff --git a/system/stack/a2dp/a2dp_vendor_ldac_decoder.cc b/system/stack/a2dp/a2dp_vendor_ldac_decoder.cc
index 3b73452..6327ff4 100644
--- a/system/stack/a2dp/a2dp_vendor_ldac_decoder.cc
+++ b/system/stack/a2dp/a2dp_vendor_ldac_decoder.cc
@@ -19,6 +19,7 @@
#include "a2dp_vendor_ldac_decoder.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <dlfcn.h>
#include <ldacBT.h>
#include <ldacBT_bco_for_fluoride.h>
@@ -30,6 +31,13 @@
#include "os/log.h"
#include "stack/include/bt_hdr.h"
+using namespace bluetooth;
+
+namespace fmt {
+template <>
+struct formatter<LDACBT_SMPL_FMT_T> : enum_formatter<LDACBT_SMPL_FMT_T> {};
+} // namespace fmt
+
//
// Decoder for LDAC Source Codec
//
@@ -100,8 +108,8 @@
static void* load_func(const char* func_name) {
void* func_ptr = dlsym(ldac_bco_lib_handle, func_name);
if (func_ptr == NULL) {
- LOG_ERROR("%s: cannot find function '%s' in the decoder library: %s",
- __func__, func_name, dlerror());
+ log::error("cannot find function '{}' in the decoder library: {}",
+ func_name, dlerror());
A2DP_VendorUnloadDecoderLdac();
return NULL;
}
@@ -119,8 +127,8 @@
// Open the decoder library
ldac_bco_lib_handle = dlopen(LDAC_BCO_LIB_NAME, RTLD_NOW);
if (ldac_bco_lib_handle == NULL) {
- LOG_INFO("%s: cannot open LDAC decoder library %s: %s", __func__,
- LDAC_BCO_LIB_NAME, dlerror());
+ log::info("cannot open LDAC decoder library {}: {}", LDAC_BCO_LIB_NAME,
+ dlerror());
return false;
}
@@ -192,7 +200,7 @@
bool a2dp_vendor_ldac_decoder_decode_packet(BT_HDR* p_buf) {
if (p_buf == nullptr) {
- LOG_ERROR("%s Dropping packet with nullptr", __func__);
+ log::error("Dropping packet with nullptr");
return false;
}
pthread_mutex_lock(&(a2dp_ldac_decoder_cb.mutex));
@@ -202,7 +210,7 @@
unsigned int bytesValid = p_buf->len;
if (bytesValid == 0) {
pthread_mutex_unlock(&(a2dp_ldac_decoder_cb.mutex));
- LOG_WARN("%s Dropping packet with zero length", __func__);
+ log::warn("Dropping packet with zero length");
return false;
}
@@ -211,7 +219,7 @@
frame_number = (int)pBuffer[0];
bs_bytes = (int)bytesValid;
bytesValid -= 1;
- LOG_INFO("%s:INPUT size : %d, frame : %d", __func__, bs_bytes, frame_number);
+ log::info("INPUT size : {}, frame : {}", bs_bytes, frame_number);
if (a2dp_ldac_decoder_cb.has_ldac_handle)
ldac_BCO_decode_packet_func(a2dp_ldac_decoder_cb.ldac_handle_bco, pBuffer,
@@ -223,7 +231,7 @@
void a2dp_vendor_ldac_decoder_start(void) {
pthread_mutex_lock(&(a2dp_ldac_decoder_cb.mutex));
- LOG_INFO("%s", __func__);
+ log::info("");
if (a2dp_ldac_decoder_cb.has_ldac_handle)
ldac_BCO_start_func(a2dp_ldac_decoder_cb.ldac_handle_bco);
pthread_mutex_unlock(&(a2dp_ldac_decoder_cb.mutex));
@@ -231,7 +239,7 @@
void a2dp_vendor_ldac_decoder_suspend(void) {
pthread_mutex_lock(&(a2dp_ldac_decoder_cb.mutex));
- LOG_INFO("%s", __func__);
+ log::info("");
if (a2dp_ldac_decoder_cb.has_ldac_handle)
ldac_BCO_suspend_func(a2dp_ldac_decoder_cb.ldac_handle_bco);
pthread_mutex_unlock(&(a2dp_ldac_decoder_cb.mutex));
@@ -243,7 +251,7 @@
int32_t channel_mode;
if (p_codec_info == NULL) {
- LOG_ERROR("%s: p_codec_info is NULL", __func__);
+ log::error("p_codec_info is NULL");
return;
}
@@ -252,8 +260,8 @@
bits_per_sample = A2DP_VendorGetTrackBitsPerSampleLdac(p_codec_info);
channel_mode = A2DP_VendorGetChannelModeCodeLdac(p_codec_info);
- LOG_INFO("%s , sample_rate=%d, bits_per_sample=%d, channel_mode=%d", __func__,
- sample_rate, bits_per_sample, channel_mode);
+ log::info(", sample_rate={}, bits_per_sample={}, channel_mode={}",
+ sample_rate, bits_per_sample, channel_mode);
if (a2dp_ldac_decoder_cb.has_ldac_handle)
ldac_BCO_configure_func(a2dp_ldac_decoder_cb.ldac_handle_bco, sample_rate,
diff --git a/system/stack/a2dp/a2dp_vendor_ldac_encoder.cc b/system/stack/a2dp/a2dp_vendor_ldac_encoder.cc
index 369e10b..8a88a2d 100644
--- a/system/stack/a2dp/a2dp_vendor_ldac_encoder.cc
+++ b/system/stack/a2dp/a2dp_vendor_ldac_encoder.cc
@@ -22,6 +22,7 @@
#ifdef __ANDROID__
#include <cutils/trace.h>
#endif
+#include <bluetooth/log.h>
#include <dlfcn.h>
#include <inttypes.h>
#include <ldacBT_abr.h>
@@ -50,6 +51,13 @@
// offset
#define A2DP_LDAC_OFFSET (AVDT_MEDIA_OFFSET + A2DP_LDAC_MPL_HDR_LEN)
+using namespace bluetooth;
+
+namespace fmt {
+template <>
+struct formatter<LDACBT_SMPL_FMT_T> : enum_formatter<LDACBT_SMPL_FMT_T> {};
+} // namespace fmt
+
typedef struct {
uint32_t sample_rate;
uint8_t channel_mode;
@@ -176,7 +184,7 @@
if (!a2dp_ldac_encoder_cb.has_ldac_handle) {
a2dp_ldac_encoder_cb.ldac_handle = ldacBT_get_handle();
if (a2dp_ldac_encoder_cb.ldac_handle == NULL) {
- LOG_ERROR("%s: Cannot get LDAC encoder handle", __func__);
+ log::error("Cannot get LDAC encoder handle");
return; // TODO: Return an error?
}
a2dp_ldac_encoder_cb.has_ldac_handle = true;
@@ -184,10 +192,8 @@
CHECK(a2dp_ldac_encoder_cb.ldac_handle != nullptr);
if (!a2dp_codec_config->copyOutOtaCodecConfig(codec_info)) {
- LOG_ERROR(
- "%s: Cannot update the codec encoder for %s: "
- "invalid codec config",
- __func__, a2dp_codec_config->name().c_str());
+ log::error("Cannot update the codec encoder for {}: invalid codec config",
+ a2dp_codec_config->name().c_str());
return;
}
const uint8_t* p_codec_info = codec_info;
@@ -201,9 +207,9 @@
a2dp_codec_config->getAudioBitsPerSample();
p_feeding_params->channel_count =
A2DP_VendorGetTrackChannelCountLdac(p_codec_info);
- LOG_INFO("%s: sample_rate=%u bits_per_sample=%u channel_count=%u", __func__,
- p_feeding_params->sample_rate, p_feeding_params->bits_per_sample,
- p_feeding_params->channel_count);
+ log::info("sample_rate={} bits_per_sample={} channel_count={}",
+ p_feeding_params->sample_rate, p_feeding_params->bits_per_sample,
+ p_feeding_params->channel_count);
a2dp_vendor_ldac_feeding_reset();
// The codec parameters
@@ -216,35 +222,32 @@
int old_quality_mode_index = p_encoder_params->quality_mode_index;
if (codec_config.codec_specific_1 != 0) {
p_encoder_params->quality_mode_index = codec_config.codec_specific_1 % 10;
- LOG_INFO("%s: setting quality mode to %s", __func__,
- quality_mode_index_to_name(p_encoder_params->quality_mode_index)
- .c_str());
+ log::info("setting quality mode to {}",
+ quality_mode_index_to_name(p_encoder_params->quality_mode_index)
+ .c_str());
} else {
p_encoder_params->quality_mode_index = A2DP_LDAC_QUALITY_ABR;
- LOG_INFO("%s: setting quality mode to default %s", __func__,
- quality_mode_index_to_name(p_encoder_params->quality_mode_index)
- .c_str());
+ log::info("setting quality mode to default {}",
+ quality_mode_index_to_name(p_encoder_params->quality_mode_index)
+ .c_str());
}
int ldac_eqmid = LDAC_ABR_MODE_EQMID;
if (p_encoder_params->quality_mode_index == A2DP_LDAC_QUALITY_ABR) {
if (!ldac_abr_loaded) {
p_encoder_params->quality_mode_index = A2DP_LDAC_QUALITY_MID;
- LOG_WARN(
-
- "%s: LDAC ABR library is not loaded, resetting quality mode to %s",
- __func__,
- quality_mode_index_to_name(p_encoder_params->quality_mode_index)
- .c_str());
+ log::warn("LDAC ABR library is not loaded, resetting quality mode to {}",
+ quality_mode_index_to_name(p_encoder_params->quality_mode_index)
+ .c_str());
} else {
- LOG_INFO("%s: changing mode from %s to %s", __func__,
- quality_mode_index_to_name(old_quality_mode_index).c_str(),
- quality_mode_index_to_name(p_encoder_params->quality_mode_index)
- .c_str());
+ log::info("changing mode from {} to {}",
+ quality_mode_index_to_name(old_quality_mode_index).c_str(),
+ quality_mode_index_to_name(p_encoder_params->quality_mode_index)
+ .c_str());
if (a2dp_ldac_encoder_cb.ldac_abr_handle != NULL) {
- LOG_INFO("%s: already in LDAC ABR mode, do nothing.", __func__);
+ log::info("already in LDAC ABR mode, do nothing.");
} else {
- LOG_INFO("%s: get and init LDAC ABR handle.", __func__);
+ log::info("get and init LDAC ABR handle.");
a2dp_ldac_encoder_cb.ldac_abr_handle = ldac_ABR_get_handle();
if (a2dp_ldac_encoder_cb.ldac_abr_handle != NULL) {
a2dp_ldac_encoder_cb.has_ldac_abr_handle = true;
@@ -254,10 +257,8 @@
A2DP_LDAC_ENCODER_INTERVAL_MS);
} else {
p_encoder_params->quality_mode_index = A2DP_LDAC_QUALITY_MID;
- LOG_INFO(
-
- "%s: get LDAC ABR handle failed, resetting quality mode to %s.",
- __func__,
+ log::info(
+ "get LDAC ABR handle failed, resetting quality mode to {}.",
quality_mode_index_to_name(p_encoder_params->quality_mode_index)
.c_str());
}
@@ -265,8 +266,8 @@
}
} else {
ldac_eqmid = p_encoder_params->quality_mode_index;
- LOG_INFO("%s: in %s mode, free LDAC ABR handle.", __func__,
- quality_mode_index_to_name(ldac_eqmid).c_str());
+ log::info("in {} mode, free LDAC ABR handle.",
+ quality_mode_index_to_name(ldac_eqmid).c_str());
if (a2dp_ldac_encoder_cb.has_ldac_abr_handle) {
ldac_ABR_free_handle(a2dp_ldac_encoder_cb.ldac_abr_handle);
a2dp_ldac_encoder_cb.ldac_abr_handle = NULL;
@@ -293,12 +294,12 @@
const tA2DP_ENCODER_INIT_PEER_PARAMS& peer_params =
a2dp_ldac_encoder_cb.peer_params;
a2dp_ldac_encoder_cb.TxAaMtuSize = adjust_effective_mtu(peer_params);
- LOG_INFO("%s: MTU=%d, peer_mtu=%d", __func__,
- a2dp_ldac_encoder_cb.TxAaMtuSize, peer_params.peer_mtu);
- LOG_INFO(
- "%s: sample_rate: %d channel_mode: %d "
- "quality_mode_index: %d pcm_wlength: %d pcm_fmt: %d",
- __func__, p_encoder_params->sample_rate, p_encoder_params->channel_mode,
+ log::info("MTU={}, peer_mtu={}", a2dp_ldac_encoder_cb.TxAaMtuSize,
+ peer_params.peer_mtu);
+ log::info(
+ "sample_rate: {} channel_mode: {} quality_mode_index: {} pcm_wlength: {} "
+ "pcm_fmt: {}",
+ p_encoder_params->sample_rate, p_encoder_params->channel_mode,
p_encoder_params->quality_mode_index, p_encoder_params->pcm_wlength,
p_encoder_params->pcm_fmt);
@@ -311,10 +312,10 @@
p_encoder_params->sample_rate);
if (result != 0) {
int err_code = ldacBT_get_error_code(a2dp_ldac_encoder_cb.ldac_handle);
- LOG_ERROR(
- "%s: error initializing the LDAC encoder: %d api_error = %d "
- "handle_error = %d block_error = %d error_code = 0x%x",
- __func__, result, LDACBT_API_ERR(err_code), LDACBT_HANDLE_ERR(err_code),
+ log::error(
+ "error initializing the LDAC encoder: {} api_error = {} handle_error = "
+ "{} block_error = {} error_code = 0x{:x}",
+ result, LDACBT_API_ERR(err_code), LDACBT_HANDLE_ERR(err_code),
LDACBT_BLOCK_ERR(err_code), err_code);
}
}
@@ -341,8 +342,8 @@
A2DP_LDAC_ENCODER_INTERVAL_MS) /
1000;
- LOG_INFO("%s: PCM bytes per tick %u", __func__,
- a2dp_ldac_encoder_cb.ldac_feeding_state.bytes_per_tick);
+ log::info("PCM bytes per tick {}",
+ a2dp_ldac_encoder_cb.ldac_feeding_state.bytes_per_tick);
}
void a2dp_vendor_ldac_feeding_flush(void) {
@@ -362,8 +363,8 @@
uint8_t nb_iterations = 0;
a2dp_ldac_get_num_frame_iteration(&nb_iterations, &nb_frame, timestamp_us);
- LOG_VERBOSE("%s: Sending %d frames per iteration, %d iterations", __func__,
- nb_frame, nb_iterations);
+ log::verbose("Sending {} frames per iteration, {} iterations", nb_frame,
+ nb_iterations);
if (nb_frame == 0) return;
for (uint8_t counter = 0; counter < nb_iterations; counter++) {
@@ -399,7 +400,7 @@
A2DP_LDAC_MEDIA_BYTES_PER_FRAME *
a2dp_ldac_encoder_cb.feeding_params.channel_count *
a2dp_ldac_encoder_cb.feeding_params.bits_per_sample / 8;
- LOG_VERBOSE("%s: pcm_bytes_per_frame %u", __func__, pcm_bytes_per_frame);
+ log::verbose("pcm_bytes_per_frame {}", pcm_bytes_per_frame);
uint32_t us_this_tick = A2DP_LDAC_ENCODER_INTERVAL_MS * 1000;
uint64_t now_us = timestamp_us;
@@ -418,8 +419,7 @@
result * pcm_bytes_per_frame;
nof = result;
- LOG_VERBOSE("%s: effective num of frames %u, iterations %u", __func__, nof,
- noi);
+ log::verbose("effective num of frames {}, iterations {}", nof, noi);
*num_of_frames = nof;
*num_of_iterations = noi;
@@ -471,7 +471,7 @@
bytes_read += temp_bytes_read;
uint8_t* packet = (uint8_t*)(p_buf + 1) + p_buf->offset + p_buf->len;
if (a2dp_ldac_encoder_cb.ldac_handle == NULL) {
- LOG_ERROR("%s: invalid LDAC handle", __func__);
+ log::error("invalid LDAC handle");
a2dp_ldac_encoder_cb.stats.media_read_total_dropped_packets++;
osi_free(p_buf);
return;
@@ -482,12 +482,11 @@
if (result != 0) {
int err_code =
ldacBT_get_error_code(a2dp_ldac_encoder_cb.ldac_handle);
- LOG_ERROR(
- "%s: LDAC encoding error: %d api_error = %d "
- "handle_error = %d block_error = %d error_code = 0x%x",
- __func__, result, LDACBT_API_ERR(err_code),
- LDACBT_HANDLE_ERR(err_code), LDACBT_BLOCK_ERR(err_code),
- err_code);
+ log::error(
+ "LDAC encoding error: {} api_error = {} handle_error = {} "
+ "block_error = {} error_code = 0x{:x}",
+ result, LDACBT_API_ERR(err_code), LDACBT_HANDLE_ERR(err_code),
+ LDACBT_BLOCK_ERR(err_code), err_code);
a2dp_ldac_encoder_cb.stats.media_read_total_dropped_packets++;
osi_free(p_buf);
return;
@@ -497,7 +496,7 @@
nb_frame--;
p_buf->layer_specific += out_frames; // added a frame to the buffer
} else {
- LOG_WARN("%s: underflow %d", __func__, nb_frame);
+ log::warn("underflow {}", nb_frame);
a2dp_ldac_encoder_cb.ldac_feeding_state.counter +=
nb_frame * LDACBT_ENC_LSU *
a2dp_ldac_encoder_cb.feeding_params.channel_count *
@@ -566,7 +565,7 @@
if (mtu_size > peer_params.peer_mtu) {
mtu_size = peer_params.peer_mtu;
}
- LOG_VERBOSE("%s: original AVDTP MTU size: %d", __func__, mtu_size);
+ log::verbose("original AVDTP MTU size: {}", mtu_size);
return mtu_size;
}
diff --git a/system/stack/a2dp/a2dp_vendor_opus.cc b/system/stack/a2dp/a2dp_vendor_opus.cc
index 7c8c22a..5b9c8b8 100644
--- a/system/stack/a2dp/a2dp_vendor_opus.cc
+++ b/system/stack/a2dp/a2dp_vendor_opus.cc
@@ -26,6 +26,7 @@
#include "a2dp_vendor_opus.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <string.h>
#include "a2dp_vendor_opus_decoder.h"
@@ -35,6 +36,8 @@
#include "os/log.h"
#include "osi/include/osi.h"
+using namespace bluetooth;
+
// data type for the Opus Codec Information Element */
// NOTE: bits_per_sample and frameSize for Opus encoder initialization.
typedef struct {
@@ -129,7 +132,7 @@
const tA2DP_OPUS_CIE* p_ie,
uint8_t* p_result) {
if (p_ie == NULL || p_result == NULL) {
- LOG_ERROR("invalid information element");
+ log::error("invalid information element");
return A2DP_INVALID_PARAMS;
}
@@ -148,19 +151,19 @@
*p_result = 0;
*p_result |= (uint8_t)(p_ie->channelMode) & A2DP_OPUS_CHANNEL_MODE_MASK;
if ((*p_result & A2DP_OPUS_CHANNEL_MODE_MASK) == 0) {
- LOG_ERROR("channelmode 0x%X setting failed", (p_ie->channelMode));
+ log::error("channelmode 0x{:X} setting failed", (p_ie->channelMode));
return A2DP_INVALID_PARAMS;
}
*p_result |= ((uint8_t)(p_ie->future1) & A2DP_OPUS_FRAMESIZE_MASK);
if ((*p_result & A2DP_OPUS_FRAMESIZE_MASK) == 0) {
- LOG_ERROR("frameSize 0x%X setting failed", (p_ie->future1));
+ log::error("frameSize 0x{:X} setting failed", (p_ie->future1));
return A2DP_INVALID_PARAMS;
}
*p_result |= ((uint8_t)(p_ie->sampleRate) & A2DP_OPUS_SAMPLING_FREQ_MASK);
if ((*p_result & A2DP_OPUS_SAMPLING_FREQ_MASK) == 0) {
- LOG_ERROR("samplerate 0x%X setting failed", (p_ie->sampleRate));
+ log::error("samplerate 0x{:X} setting failed", (p_ie->sampleRate));
return A2DP_INVALID_PARAMS;
}
@@ -183,14 +186,14 @@
tA2DP_CODEC_TYPE codec_type;
if (p_ie == NULL || p_codec_info == NULL) {
- LOG_ERROR("unable to parse information element");
+ log::error("unable to parse information element");
return A2DP_INVALID_PARAMS;
}
// Check the codec capability length
losc = *p_codec_info++;
if (losc != A2DP_OPUS_CODEC_LEN) {
- LOG_ERROR("invalid codec ie length %d", losc);
+ log::error("invalid codec ie length {}", losc);
return A2DP_WRONG_CODEC;
}
@@ -199,7 +202,7 @@
/* Check the Media Type and Media Codec Type */
if (media_type != AVDT_MEDIA_TYPE_AUDIO ||
codec_type != A2DP_MEDIA_CT_NON_A2DP) {
- LOG_ERROR("invalid codec");
+ log::error("invalid codec");
return A2DP_WRONG_CODEC;
}
@@ -214,7 +217,7 @@
p_codec_info += 2;
if (p_ie->vendorId != A2DP_OPUS_VENDOR_ID ||
p_ie->codecId != A2DP_OPUS_CODEC_ID) {
- LOG_ERROR("wrong vendor or codec id");
+ log::error("wrong vendor or codec id");
return A2DP_WRONG_CODEC;
}
@@ -227,11 +230,11 @@
// NOTE: The checks here are very liberal. We should be using more
// pedantic checks specific to the SRC or SNK as specified in the spec.
if (A2DP_BitsSet(p_ie->sampleRate) == A2DP_SET_ZERO_BIT) {
- LOG_ERROR("invalid sample rate 0x%X", p_ie->sampleRate);
+ log::error("invalid sample rate 0x{:X}", p_ie->sampleRate);
return A2DP_BAD_SAMP_FREQ;
}
if (A2DP_BitsSet(p_ie->channelMode) == A2DP_SET_ZERO_BIT) {
- LOG_ERROR("invalid channel mode");
+ log::error("invalid channel mode");
return A2DP_BAD_CH_MODE;
}
@@ -239,11 +242,11 @@
}
if (A2DP_BitsSet(p_ie->sampleRate) != A2DP_SET_ONE_BIT) {
- LOG_ERROR("invalid sampling frequency 0x%X", p_ie->sampleRate);
+ log::error("invalid sampling frequency 0x{:X}", p_ie->sampleRate);
return A2DP_BAD_SAMP_FREQ;
}
if (A2DP_BitsSet(p_ie->channelMode) != A2DP_SET_ONE_BIT) {
- LOG_ERROR("invalid channel mode.");
+ log::error("invalid channel mode.");
return A2DP_BAD_CH_MODE;
}
@@ -328,18 +331,18 @@
/* parse configuration */
status = A2DP_ParseInfoOpus(&cfg_cie, p_codec_info, is_capability);
if (status != A2DP_SUCCESS) {
- LOG_ERROR("parsing failed %d", status);
+ log::error("parsing failed {}", status);
return status;
}
/* verify that each parameter is in range */
- LOG_VERBOSE("SAMPLING FREQ peer: 0x%x, capability 0x%x", cfg_cie.sampleRate,
- p_cap->sampleRate);
- LOG_VERBOSE("CH_MODE peer: 0x%x, capability 0x%x", cfg_cie.channelMode,
- p_cap->channelMode);
- LOG_VERBOSE("FRAMESIZE peer: 0x%x, capability 0x%x", cfg_cie.future1,
- p_cap->future1);
+ log::verbose("SAMPLING FREQ peer: 0x{:x}, capability 0x{:x}",
+ cfg_cie.sampleRate, p_cap->sampleRate);
+ log::verbose("CH_MODE peer: 0x{:x}, capability 0x{:x}", cfg_cie.channelMode,
+ p_cap->channelMode);
+ log::verbose("FRAMESIZE peer: 0x{:x}, capability 0x{:x}", cfg_cie.future1,
+ p_cap->future1);
/* sampling frequency */
if ((cfg_cie.sampleRate & p_cap->sampleRate) == 0) return A2DP_NS_SAMP_FREQ;
@@ -371,12 +374,12 @@
tA2DP_STATUS a2dp_status =
A2DP_ParseInfoOpus(&Opus_cie_a, p_codec_info_a, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("cannot decode codec information: %d", a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
a2dp_status = A2DP_ParseInfoOpus(&Opus_cie_b, p_codec_info_b, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("cannot decode codec information: %d", a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
@@ -392,12 +395,12 @@
tA2DP_STATUS a2dp_status =
A2DP_ParseInfoOpus(&Opus_cie_a, p_codec_info_a, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("cannot decode codec information: %d", a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
a2dp_status = A2DP_ParseInfoOpus(&Opus_cie_b, p_codec_info_b, true);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("cannot decode codec information: %d", a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return false;
}
@@ -431,7 +434,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoOpus(&Opus_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("cannot decode codec information: %d", a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -449,7 +452,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoOpus(&Opus_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("cannot decode codec information: %d", a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -462,7 +465,7 @@
return 32;
case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE:
default:
- LOG_ERROR("Invalid bit depth setting");
+ log::error("Invalid bit depth setting");
return -1;
}
}
@@ -473,7 +476,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoOpus(&Opus_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("cannot decode codec information: %d", a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -484,7 +487,7 @@
case A2DP_OPUS_CHANNEL_MODE_DUAL_MONO:
return 2;
default:
- LOG_ERROR("Invalid channel setting");
+ log::error("Invalid channel setting");
}
return -1;
@@ -496,7 +499,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoOpus(&Opus_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("cannot decode codec information: %d", a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -516,7 +519,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoOpus(&Opus_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("cannot decode codec information: %d", a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
@@ -537,7 +540,7 @@
// Check whether the codec info contains valid data
tA2DP_STATUS a2dp_status = A2DP_ParseInfoOpus(&Opus_cie, p_codec_info, false);
if (a2dp_status != A2DP_SUCCESS) {
- LOG_ERROR("cannot decode codec information: %d", a2dp_status);
+ log::error("cannot decode codec information: {}", a2dp_status);
return -1;
}
int samplerate = A2DP_VendorGetTrackSampleRateOpus(p_codec_info);
@@ -899,9 +902,8 @@
btav_a2dp_codec_config_t device_codec_config_ = getCodecConfig();
- LOG_INFO(
- "AudioManager stream config %d sample rate %d bit depth %d channel "
- "mode",
+ log::info(
+ "AudioManager stream config {} sample rate {} bit depth {} channel mode",
device_codec_config_.sample_rate, device_codec_config_.bits_per_sample,
device_codec_config_.channel_mode);
@@ -924,7 +926,7 @@
tA2DP_STATUS status =
A2DP_ParseInfoOpus(&peer_info_cie, p_peer_codec_info, is_capability);
if (status != A2DP_SUCCESS) {
- LOG_ERROR("can't parse peer's capabilities: error = %d", status);
+ log::error("can't parse peer's capabilities: error = {}", status);
goto fail;
}
@@ -996,9 +998,8 @@
}
} while (false);
if (codec_config_.sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) {
- LOG_ERROR(
- "cannot match sample frequency: local caps = 0x%x "
- "peer info = 0x%x",
+ log::error(
+ "cannot match sample frequency: local caps = 0x{:x} peer info = 0x{:x}",
p_a2dp_opus_caps->sampleRate, peer_info_cie.sampleRate);
goto fail;
}
@@ -1071,9 +1072,9 @@
}
} while (false);
if (codec_config_.bits_per_sample == BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) {
- LOG_ERROR(
- "cannot match bits per sample: default = 0x%x "
- "user preference = 0x%x",
+ log::error(
+ "cannot match bits per sample: default = 0x{:x} user preference = "
+ "0x{:x}",
a2dp_opus_default_config.bits_per_sample,
codec_user_config_.bits_per_sample);
goto fail;
@@ -1146,9 +1147,8 @@
}
} while (false);
if (codec_config_.channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE) {
- LOG_ERROR(
- "cannot match channel mode: local caps = 0x%x "
- "peer info = 0x%x",
+ log::error(
+ "cannot match channel mode: local caps = 0x{:x} peer info = 0x{:x}",
p_a2dp_opus_caps->channelMode, peer_info_cie.channelMode);
goto fail;
}
@@ -1187,16 +1187,15 @@
result_config_cie.future3 = 0x00;
if (codec_config_.codec_specific_1 == BTAV_A2DP_CODEC_FRAME_SIZE_NONE) {
- LOG_ERROR(
- "cannot match frame size: local caps = 0x%x "
- "peer info = 0x%x",
+ log::error(
+ "cannot match frame size: local caps = 0x{:x} peer info = 0x{:x}",
p_a2dp_opus_caps->future1, peer_info_cie.future1);
goto fail;
}
if (A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &result_config_cie,
p_result_codec_config) != A2DP_SUCCESS) {
- LOG_ERROR("failed to BuildInfoOpus for result_config_cie");
+ log::error("failed to BuildInfoOpus for result_config_cie");
goto fail;
}
@@ -1262,7 +1261,7 @@
tA2DP_STATUS status =
A2DP_ParseInfoOpus(&peer_info_cie, p_peer_codec_capabilities, true);
if (status != A2DP_SUCCESS) {
- LOG_ERROR("can't parse peer's capabilities: error = %d", status);
+ log::error("can't parse peer's capabilities: error = {}", status);
goto fail;
}
@@ -1288,7 +1287,7 @@
BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO;
}
- LOG_INFO("BuildInfoOpus for peer info cie for ota caps");
+ log::info("BuildInfoOpus for peer info cie for ota caps");
status = A2DP_BuildInfoOpus(AVDT_MEDIA_TYPE_AUDIO, &peer_info_cie,
ota_codec_peer_capability_);
CHECK(status == A2DP_SUCCESS);
diff --git a/system/stack/a2dp/a2dp_vendor_opus_decoder.cc b/system/stack/a2dp/a2dp_vendor_opus_decoder.cc
index d36112b..ad3fbe1 100644
--- a/system/stack/a2dp/a2dp_vendor_opus_decoder.cc
+++ b/system/stack/a2dp/a2dp_vendor_opus_decoder.cc
@@ -19,11 +19,14 @@
#include "a2dp_vendor_opus_decoder.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <opus.h>
#include "a2dp_vendor_opus.h"
+#include "os/log.h"
#include "osi/include/allocator.h"
-#include "osi/include/log.h"
+
+using namespace bluetooth;
typedef struct {
OpusDecoder* opus_handle = nullptr;
@@ -60,7 +63,7 @@
a2dp_opus_decoder_cb.opus_handle =
static_cast<OpusDecoder*>(osi_malloc(size));
if (a2dp_opus_decoder_cb.opus_handle == nullptr) {
- LOG_ERROR("failed to allocate opus decoder handle");
+ log::error("failed to allocate opus decoder handle");
return false;
}
err_val = opus_decoder_init(a2dp_opus_decoder_cb.opus_handle,
@@ -75,10 +78,10 @@
memset(a2dp_opus_decoder_cb.decode_buf, 0, A2DP_OPUS_DECODE_BUFFER_LENGTH);
a2dp_opus_decoder_cb.decode_callback = decode_callback;
- LOG_INFO("decoder init success");
+ log::info("decoder init success");
return true;
} else {
- LOG_ERROR("failed to initialize Opus Decoder");
+ log::error("failed to initialize Opus Decoder");
a2dp_opus_decoder_cb.has_opus_handle = false;
return false;
}
@@ -96,12 +99,12 @@
uint32_t frameLen = 0;
if (p_buf == nullptr) {
- LOG_ERROR("Dropping packet with nullptr");
+ log::error("Dropping packet with nullptr");
return false;
}
if (p_buf->len == 0) {
- LOG_ERROR("Empty packet");
+ log::error("Empty packet");
return false;
}
@@ -117,10 +120,10 @@
A2DP_OPUS_CODEC_DEFAULT_SAMPLERATE);
uint32_t num_frames = pBuffer[0] & 0xf;
- LOG_ERROR("numframes %d framesize %d framelen %d bufferSize %d", num_frames,
- frameSize, frameLen, bufferSize);
- LOG_ERROR("numChannels %d numFrames %d offset %d", numChannels, numFrames,
- p_buf->offset);
+ log::error("numframes {} framesize {} framelen {} bufferSize {}", num_frames,
+ frameSize, frameLen, bufferSize);
+ log::error("numChannels {} numFrames {} offset {}", numChannels, numFrames,
+ p_buf->offset);
for (uint32_t frame = 0; frame < numFrames; ++frame) {
{
@@ -132,15 +135,15 @@
A2DP_OPUS_DECODE_BUFFER_LENGTH, 0 /* flags */);
if (ret_val < OPUS_OK) {
- LOG_ERROR("Opus DecodeFrame failed %d, applying concealment", ret_val);
+ log::error("Opus DecodeFrame failed {}, applying concealment", ret_val);
ret_val = opus_decode(a2dp_opus_decoder_cb.opus_handle, NULL, 0,
a2dp_opus_decoder_cb.decode_buf,
A2DP_OPUS_DECODE_BUFFER_LENGTH, 0 /* flags */);
}
if (ret_val < OPUS_OK) {
- LOG_ERROR("Opus DecodeFrame retry failed with %d, dropping packet",
- ret_val);
+ log::error("Opus DecodeFrame retry failed with {}, dropping packet",
+ ret_val);
return false;
}
@@ -163,7 +166,7 @@
err_val =
opus_decoder_ctl(a2dp_opus_decoder_cb.opus_handle, OPUS_RESET_STATE);
if (err_val != OPUS_OK) {
- LOG_ERROR("failed to reset decoder");
+ log::error("failed to reset decoder");
}
}
return;
diff --git a/system/stack/a2dp/a2dp_vendor_opus_encoder.cc b/system/stack/a2dp/a2dp_vendor_opus_encoder.cc
index 0be0737..e8b59d0 100644
--- a/system/stack/a2dp/a2dp_vendor_opus_encoder.cc
+++ b/system/stack/a2dp/a2dp_vendor_opus_encoder.cc
@@ -18,6 +18,7 @@
#include "a2dp_vendor_opus_encoder.h"
+#include <bluetooth/log.h>
#include <dlfcn.h>
#include <opus.h>
#include <stdio.h>
@@ -32,6 +33,8 @@
#include "osi/include/osi.h"
#include "stack/include/bt_hdr.h"
+using namespace bluetooth;
+
typedef struct {
uint32_t sample_rate;
uint16_t bitrate;
@@ -138,7 +141,7 @@
a2dp_opus_encoder_cb.opus_handle =
static_cast<OpusEncoder*>(osi_malloc(size));
if (a2dp_opus_encoder_cb.opus_handle == nullptr) {
- LOG_ERROR("failed to allocate opus encoder handle");
+ log::error("failed to allocate opus encoder handle");
return;
}
@@ -147,9 +150,9 @@
A2DP_OPUS_CODEC_OUTPUT_CHS, OPUS_APPLICATION_AUDIO);
if (error_val != OPUS_OK) {
- LOG_ERROR(
- "failed to init opus encoder (handle size %d, sampling rate %d, "
- "output chs %d, error %d)",
+ log::error(
+ "failed to init opus encoder (handle size {}, sampling rate {}, output "
+ "chs {}, error {})",
size, A2DP_OPUS_CODEC_DEFAULT_SAMPLERATE, A2DP_OPUS_CODEC_OUTPUT_CHS,
error_val);
osi_free(a2dp_opus_encoder_cb.opus_handle);
@@ -169,10 +172,8 @@
const tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params, bool* p_restart_input,
bool* p_restart_output, bool* p_config_updated) {
if (a2dp_opus_encoder_cb.peer_mtu == 0) {
- LOG_ERROR(
- "Cannot update the codec encoder for %s: "
- "invalid peer MTU",
- name().c_str());
+ log::error("Cannot update the codec encoder for {}: invalid peer MTU",
+ name().c_str());
return false;
}
@@ -197,16 +198,14 @@
if (!a2dp_opus_encoder_cb.has_opus_handle ||
a2dp_opus_encoder_cb.opus_handle == NULL) {
- LOG_ERROR("Cannot get Opus encoder handle");
+ log::error("Cannot get Opus encoder handle");
return false;
}
CHECK(a2dp_opus_encoder_cb.opus_handle != nullptr);
if (!a2dp_codec_config->copyOutOtaCodecConfig(codec_info)) {
- LOG_ERROR(
- "Cannot update the codec encoder for %s: "
- "invalid codec config",
- a2dp_codec_config->name().c_str());
+ log::error("Cannot update the codec encoder for {}: invalid codec config",
+ a2dp_codec_config->name().c_str());
return false;
}
const uint8_t* p_codec_info = codec_info;
@@ -220,9 +219,9 @@
a2dp_codec_config->getAudioBitsPerSample();
p_feeding_params->channel_count =
A2DP_VendorGetTrackChannelCountOpus(p_codec_info);
- LOG_INFO("sample_rate=%u bits_per_sample=%u channel_count=%u",
- p_feeding_params->sample_rate, p_feeding_params->bits_per_sample,
- p_feeding_params->channel_count);
+ log::info("sample_rate={} bits_per_sample={} channel_count={}",
+ p_feeding_params->sample_rate, p_feeding_params->bits_per_sample,
+ p_feeding_params->channel_count);
// The codec parameters
p_encoder_params->sample_rate =
@@ -245,12 +244,12 @@
// Set the bitrate quality mode index
if (codec_config.codec_specific_3 != 0) {
p_encoder_params->quality_mode_index = codec_config.codec_specific_3 % 10;
- LOG_INFO("setting bitrate quality mode to %d",
- p_encoder_params->quality_mode_index);
+ log::info("setting bitrate quality mode to {}",
+ p_encoder_params->quality_mode_index);
} else {
p_encoder_params->quality_mode_index = 5;
- LOG_INFO("setting bitrate quality mode to default %d",
- p_encoder_params->quality_mode_index);
+ log::info("setting bitrate quality mode to default {}",
+ p_encoder_params->quality_mode_index);
}
error = opus_encoder_ctl(
@@ -258,19 +257,19 @@
OPUS_SET_COMPLEXITY(p_encoder_params->quality_mode_index));
if (error != OPUS_OK) {
- LOG_ERROR("failed to set encoder bitrate quality setting");
+ log::error("failed to set encoder bitrate quality setting");
return false;
}
p_encoder_params->pcm_wlength =
a2dp_opus_encoder_cb.feeding_params.bits_per_sample >> 3;
- LOG_INFO("setting bitrate to %d", p_encoder_params->bitrate);
+ log::info("setting bitrate to {}", p_encoder_params->bitrate);
error = opus_encoder_ctl(a2dp_opus_encoder_cb.opus_handle,
OPUS_SET_BITRATE(p_encoder_params->bitrate));
if (error != OPUS_OK) {
- LOG_ERROR("failed to set encoder bitrate");
+ log::error("failed to set encoder bitrate");
return false;
}
@@ -392,7 +391,7 @@
packet = (unsigned char*)(p_buf + 1) + p_buf->offset + p_buf->len;
if (a2dp_opus_encoder_cb.opus_handle == NULL) {
- LOG_ERROR("invalid OPUS handle");
+ log::error("invalid OPUS handle");
a2dp_opus_encoder_cb.stats.media_read_total_dropped_packets++;
osi_free(p_buf);
return;
@@ -404,7 +403,7 @@
packet, (BT_DEFAULT_BUFFER_SIZE - p_buf->offset));
if (written <= 0) {
- LOG_ERROR("OPUS encoding error");
+ log::error("OPUS encoding error");
a2dp_opus_encoder_cb.stats.media_read_total_dropped_packets++;
osi_free(p_buf);
return;
@@ -415,7 +414,7 @@
nb_frame--;
p_buf->layer_specific += out_frames; // added a frame to the buffer
} else {
- LOG_WARN("Opus src buffer underflow %d", nb_frame);
+ log::warn("Opus src buffer underflow {}", nb_frame);
a2dp_opus_encoder_cb.opus_feeding_state.counter +=
nb_frame * opus_frame_size *
a2dp_opus_encoder_cb.feeding_params.channel_count *
diff --git a/system/stack/acl/ble_acl.cc b/system/stack/acl/ble_acl.cc
index 44b72f5..051526e 100644
--- a/system/stack/acl/ble_acl.cc
+++ b/system/stack/acl/ble_acl.cc
@@ -16,6 +16,8 @@
#define LOG_TAG "acl"
+#include <bluetooth/log.h>
+
#include <cstdint>
#include "common/init_flags.h"
@@ -31,6 +33,8 @@
#include "stack/include/l2cap_hci_link_interface.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
extern tBTM_CB btm_cb;
void btm_ble_increment_link_topology_mask(uint8_t link_role);
@@ -63,7 +67,7 @@
address_with_type.type, conn_interval, conn_latency,
conn_timeout)) {
btm_sec_disconnect(handle, HCI_ERR_PEER_USER, "stack::acl::ble_acl fail");
- LOG_WARN("Unable to complete l2cap connection");
+ log::warn("Unable to complete l2cap connection");
return false;
}
@@ -82,7 +86,7 @@
if (!acl_ble_common_connection(address_with_type, handle, role, match,
conn_interval, conn_latency, conn_timeout,
can_read_discoverable_characteristics)) {
- LOG_WARN("Unable to create enhanced ble acl connection");
+ log::warn("Unable to create enhanced ble acl connection");
return;
}
@@ -145,10 +149,10 @@
connection_manager::on_connection_timed_out_from_shim(
resolved_address_with_type.bda);
}
- LOG_WARN("LE connection fail peer:%s bd_addr:%s hci_status:%s",
- ADDRESS_TO_LOGGABLE_CSTR(address_with_type),
- ADDRESS_TO_LOGGABLE_CSTR(resolved_address_with_type.bda),
- hci_status_code_text(status).c_str());
+ log::warn("LE connection fail peer:{} bd_addr:{} hci_status:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(address_with_type),
+ ADDRESS_TO_LOGGABLE_CSTR(resolved_address_with_type.bda),
+ hci_status_code_text(status).c_str());
} else {
btm_cb.ble_ctr_cb.inq_var.adv_mode = BTM_BLE_ADV_DISABLE;
}
@@ -176,9 +180,9 @@
uint16_t max_tx_time,
uint16_t max_rx_octets,
uint16_t max_rx_time) {
- LOG_DEBUG(
- "Data length change event received handle:0x%04x max_tx_octets:%hu "
- "max_tx_time:%hu max_rx_octets:%hu max_rx_time:%hu",
+ log::debug(
+ "Data length change event received handle:0x{:04x} max_tx_octets:{} "
+ "max_tx_time:{} max_rx_octets:{} max_rx_time:{}",
handle, max_tx_octets, max_tx_time, max_rx_octets, max_rx_time);
l2cble_process_data_length_change_event(handle, max_tx_octets, max_rx_octets);
}
diff --git a/system/stack/acl/btm_acl.cc b/system/stack/acl/btm_acl.cc
index 32cd7f6..9403b64 100644
--- a/system/stack/acl/btm_acl.cc
+++ b/system/stack/acl/btm_acl.cc
@@ -34,7 +34,7 @@
#include "main/shim/entry.h"
#define LOG_TAG "btm_acl"
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include <cstdint>
@@ -88,6 +88,7 @@
"bluetooth.core.acl.link_supervision_timeout"
#endif
+using namespace bluetooth;
using bluetooth::legacy::hci::GetInterface;
void BTM_update_version_info(const RawAddress& bd_addr,
@@ -152,7 +153,7 @@
static bool IsEprAvailable(const tACL_CONN& p_acl) {
if (!p_acl.peer_lmp_feature_valid[0]) {
- LOG_WARN("Checking incomplete feature page read");
+ log::warn("Checking incomplete feature page read");
return false;
}
return HCI_ATOMIC_ENCRYPT_SUPPORTED(p_acl.peer_lmp_feature_pages[0]) &&
@@ -171,7 +172,7 @@
namespace {
void NotifyAclLinkUp(tACL_CONN& p_acl) {
if (p_acl.link_up_issued) {
- LOG_INFO("Already notified BTA layer that the link is up");
+ log::info("Already notified BTA layer that the link is up");
return;
}
p_acl.link_up_issued = true;
@@ -202,9 +203,9 @@
static void disconnect_acl(tACL_CONN& p_acl, tHCI_STATUS reason,
std::string comment) {
- LOG_INFO("Disconnecting peer:%s reason:%s comment:%s",
- ADDRESS_TO_LOGGABLE_CSTR(p_acl.remote_addr),
- hci_error_code_text(reason).c_str(), comment.c_str());
+ log::info("Disconnecting peer:{} reason:{} comment:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_acl.remote_addr),
+ hci_error_code_text(reason).c_str(), comment.c_str());
p_acl.disconnect_reason = reason;
return bluetooth::shim::ACL_Disconnect(
@@ -221,22 +222,23 @@
void hci_btm_set_link_supervision_timeout(tACL_CONN& link, uint16_t timeout) {
if (link.link_role != HCI_ROLE_CENTRAL) {
/* Only send if current role is Central; 2.0 spec requires this */
- LOG_WARN("Can only set link supervision timeout if central role:%s",
- RoleText(link.link_role).c_str());
+ log::warn("Can only set link supervision timeout if central role:{}",
+ RoleText(link.link_role).c_str());
return;
}
if (!bluetooth::shim::
controller_is_write_link_supervision_timeout_supported()) {
- LOG_WARN(
- "UNSUPPORTED by controller write link supervision timeout:%.2fms "
- "bd_addr:%s",
+ log::warn(
+ "UNSUPPORTED by controller write link supervision timeout:{:.2f}ms "
+ "bd_addr:{}",
supervision_timeout_to_seconds(timeout),
ADDRESS_TO_LOGGABLE_CSTR(link.RemoteAddress()));
return;
}
- LOG_DEBUG("Setting link supervision timeout:%.2fs peer:%s",
- double(timeout) * 0.01, ADDRESS_TO_LOGGABLE_CSTR(link.RemoteAddress()));
+ log::debug("Setting link supervision timeout:{:.2f}s peer:{}",
+ double(timeout) * 0.01,
+ ADDRESS_TO_LOGGABLE_CSTR(link.RemoteAddress()));
link.link_super_tout = timeout;
btsnd_hcic_write_link_super_tout(link.Handle(), timeout);
}
@@ -327,8 +329,8 @@
if (!p_acl->in_use) continue;
if (p_acl->remote_addr == rpa) {
- LOG_INFO("consolidate %s -> %s", ADDRESS_TO_LOGGABLE_CSTR(rpa),
- ADDRESS_TO_LOGGABLE_CSTR(identity_addr));
+ log::info("consolidate {} -> {}", ADDRESS_TO_LOGGABLE_CSTR(rpa),
+ ADDRESS_TO_LOGGABLE_CSTR(identity_addr));
p_acl->remote_addr = identity_addr;
return;
}
@@ -379,15 +381,15 @@
uint8_t status;
if (len < 4) {
- LOG_WARN("Malformatted packet, not containing enough data");
+ log::warn("Malformatted packet, not containing enough data");
return;
}
STREAM_TO_UINT8(status, data);
if (status != HCI_SUCCESS) {
- LOG_WARN("Peer SCA Command complete failed:%s",
- hci_error_code_text(static_cast<tHCI_STATUS>(status)).c_str());
+ log::warn("Peer SCA Command complete failed:{}",
+ hci_error_code_text(static_cast<tHCI_STATUS>(status)).c_str());
return;
}
@@ -396,7 +398,7 @@
tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(handle);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return;
}
p_acl->sca = sca;
@@ -422,9 +424,9 @@
if (transport == BT_TRANSPORT_BR_EDR) {
btm_set_link_policy(p_acl, btm_cb.acl_cb_.DefaultLinkPolicy());
}
- LOG_WARN(
- "Unable to create duplicate acl when one already exists handle:%hu"
- " role:%s transport:%s",
+ log::warn(
+ "Unable to create duplicate acl when one already exists handle:{} "
+ "role:{} transport:{}",
hci_handle, RoleText(link_role).c_str(),
bt_transport_text(transport).c_str());
return;
@@ -432,7 +434,7 @@
p_acl = internal_.acl_allocate_connection();
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return;
}
@@ -446,10 +448,10 @@
p_acl->switch_role_failed_attempts = 0;
p_acl->reset_switch_role();
- LOG_DEBUG(
- "Created new ACL connection peer:%s role:%s handle:0x%04x transport:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bda), RoleText(p_acl->link_role).c_str(), hci_handle,
- bt_transport_text(transport).c_str());
+ log::debug(
+ "Created new ACL connection peer:{} role:{} handle:0x{:04x} transport:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bda), RoleText(p_acl->link_role).c_str(),
+ hci_handle, bt_transport_text(transport).c_str());
if (p_acl->is_transport_br_edr()) {
BTM_PM_OnConnected(hci_handle, bda);
@@ -497,7 +499,7 @@
void btm_acl_removed(uint16_t handle) {
tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(handle);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return;
}
p_acl->in_use = false;
@@ -538,7 +540,7 @@
tACL_CONN* p_acl =
internal_.btm_bda_to_acl(remote_bd_addr, BT_TRANSPORT_BR_EDR);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return BTM_UNKNOWN_ADDR;
}
*p_role = p_acl->link_role;
@@ -564,45 +566,45 @@
******************************************************************************/
tBTM_STATUS BTM_SwitchRoleToCentral(const RawAddress& remote_bd_addr) {
if (!controller_get_interface()->SupportsRoleSwitch()) {
- LOG_INFO("Local controller does not support role switching");
+ log::info("Local controller does not support role switching");
return BTM_MODE_UNSUPPORTED;
}
tACL_CONN* p_acl =
internal_.btm_bda_to_acl(remote_bd_addr, BT_TRANSPORT_BR_EDR);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return BTM_UNKNOWN_ADDR;
}
if (p_acl->link_role == HCI_ROLE_CENTRAL) {
- LOG_INFO("Requested role is already in effect");
+ log::info("Requested role is already in effect");
return BTM_SUCCESS;
}
if (interop_match_addr(INTEROP_DISABLE_ROLE_SWITCH, &remote_bd_addr)) {
- LOG_INFO("Remote device is on list preventing role switch");
+ log::info("Remote device is on list preventing role switch");
return BTM_DEV_RESTRICT_LISTED;
}
if (BTM_IsScoActiveByBdaddr(remote_bd_addr)) {
- LOG_INFO("An active SCO to device prevents role switch at this time");
+ log::info("An active SCO to device prevents role switch at this time");
return BTM_NO_RESOURCES;
}
if (!p_acl->is_switch_role_idle()) {
- LOG_INFO("Role switch is already progress");
+ log::info("Role switch is already progress");
return BTM_BUSY;
}
if (interop_match_addr(INTEROP_DYNAMIC_ROLE_SWITCH, &remote_bd_addr)) {
- LOG_DEBUG("Device restrict listed under INTEROP_DYNAMIC_ROLE_SWITCH");
+ log::debug("Device restrict listed under INTEROP_DYNAMIC_ROLE_SWITCH");
return BTM_DEV_RESTRICT_LISTED;
}
tBTM_PM_MODE pwr_mode;
if (!BTM_ReadPowerMode(p_acl->remote_addr, &pwr_mode)) {
- LOG_WARN(
+ log::warn(
"Unable to find device to read current power mode prior to role "
"switch");
return BTM_UNKNOWN_ADDR;
@@ -610,7 +612,7 @@
if (pwr_mode == BTM_PM_MD_PARK || pwr_mode == BTM_PM_MD_SNIFF) {
if (!BTM_SetLinkPolicyActiveMode(p_acl->remote_addr)) {
- LOG_WARN("Unable to set link policy active before attempting switch");
+ log::warn("Unable to set link policy active before attempting switch");
return BTM_WRONG_MODE;
}
p_acl->set_switch_role_changing();
@@ -645,7 +647,7 @@
uint8_t encr_enable) {
tACL_CONN* p = internal_.acl_get_connection_from_handle(handle);
if (p == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return;
}
@@ -653,11 +655,10 @@
* encrypted connection, drop the connection */
if (bluetooth::os::ParameterProvider::IsCommonCriteriaMode()) {
if (p->is_encrypted && !encr_enable) {
- LOG(ERROR)
- << __func__
- << " attempting to decrypt encrypted connection, disconnecting. "
- "handle: "
- << loghex(handle);
+ log::error(
+ "attempting to decrypt encrypted connection, disconnecting. "
+ "handle: {}",
+ loghex(handle));
acl_disconnect_from_handle(handle, HCI_ERR_HOST_REJECT_SECURITY,
"stack::btu::btu_hcif::read_drop_encryption "
@@ -705,20 +706,20 @@
if ((*settings & HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH) &&
(!controller->SupportsRoleSwitch())) {
*settings &= (~HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH);
- LOG_INFO("Role switch not supported (settings: 0x%04x)", *settings);
+ log::info("Role switch not supported (settings: 0x{:04x})", *settings);
}
if ((*settings & HCI_ENABLE_HOLD_MODE) && (!controller->SupportsHoldMode())) {
*settings &= (~HCI_ENABLE_HOLD_MODE);
- LOG_INFO("hold not supported (settings: 0x%04x)", *settings);
+ log::info("hold not supported (settings: 0x{:04x})", *settings);
}
if ((*settings & HCI_ENABLE_SNIFF_MODE) &&
(!controller->SupportsSniffMode())) {
*settings &= (~HCI_ENABLE_SNIFF_MODE);
- LOG_INFO("sniff not supported (settings: 0x%04x)", *settings);
+ log::info("sniff not supported (settings: 0x{:04x})", *settings);
}
if ((*settings & HCI_ENABLE_PARK_MODE) && (!controller->SupportsParkMode())) {
*settings &= (~HCI_ENABLE_PARK_MODE);
- LOG_INFO("park not supported (settings: 0x%04x)", *settings);
+ log::info("park not supported (settings: 0x{:04x})", *settings);
}
}
@@ -737,7 +738,7 @@
uint16_t flag) {
auto conn = internal_.btm_bda_to_acl(peer_addr, BT_TRANSPORT_BR_EDR);
if (!conn) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return;
}
btm_set_link_policy(conn, conn->link_policy | flag);
@@ -747,7 +748,7 @@
uint16_t flag) {
auto conn = internal_.btm_bda_to_acl(peer_addr, BT_TRANSPORT_BR_EDR);
if (!conn) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return;
}
btm_set_link_policy(conn, conn->link_policy & ~flag);
@@ -756,7 +757,7 @@
bool BTM_is_sniff_allowed_for(const RawAddress& peer_addr) {
auto conn = internal_.btm_bda_to_acl(peer_addr, BT_TRANSPORT_BR_EDR);
if (!conn) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return false;
}
return conn->link_policy & HCI_ENABLE_SNIFF_MODE;
@@ -821,7 +822,7 @@
uint8_t status, uint16_t handle) {
tACL_CONN* p_acl_cb = internal_.acl_get_connection_from_handle(handle);
if (p_acl_cb == nullptr) {
- LOG_WARN("Received remote version complete for unknown device");
+ log::warn("Received remote version complete for unknown device");
return;
}
@@ -840,9 +841,9 @@
*/
break;
default:
- LOG_ERROR("Unable to determine transport:%s device:%s",
- bt_transport_text(p_acl_cb->transport).c_str(),
- ADDRESS_TO_LOGGABLE_CSTR(p_acl_cb->remote_addr));
+ log::error("Unable to determine transport:{} device:{}",
+ bt_transport_text(p_acl_cb->transport).c_str(),
+ ADDRESS_TO_LOGGABLE_CSTR(p_acl_cb->remote_addr));
}
// save remote versions to iot conf file
@@ -855,7 +856,7 @@
uint16_t lmp_subversion) {
tACL_CONN* p_acl_cb = internal_.acl_get_connection_from_handle(handle);
if (p_acl_cb == nullptr) {
- LOG_WARN("Received remote version complete for unknown acl");
+ log::warn("Received remote version complete for unknown acl");
return;
}
p_acl_cb->remote_version_received = true;
@@ -898,9 +899,7 @@
uint8_t max_page_number) {
CHECK(p_acl_cb != nullptr);
if (!p_acl_cb->peer_lmp_feature_valid[max_page_number]) {
- LOG_WARN(
- "Checking remote features but remote feature read is "
- "incomplete");
+ log::warn("Checking remote features but remote feature read is incomplete");
}
bool ssp_supported =
@@ -948,7 +947,7 @@
uint16_t handle;
if (evt_len < HCI_EXT_FEATURES_SUCCESS_EVT_LEN) {
- LOG_WARN("Remote extended feature length too short. length=%d", evt_len);
+ log::warn("Remote extended feature length too short. length={}", evt_len);
return;
}
@@ -958,17 +957,17 @@
STREAM_TO_UINT8(max_page, p);
if (max_page > HCI_EXT_FEATURES_PAGE_MAX) {
- LOG_WARN("Too many max pages read page=%d unknown", max_page);
+ log::warn("Too many max pages read page={} unknown", max_page);
return;
}
if (page_num > HCI_EXT_FEATURES_PAGE_MAX) {
- LOG_WARN("Too many received pages num_page=%d invalid", page_num);
+ log::warn("Too many received pages num_page={} invalid", page_num);
return;
}
if (page_num > max_page) {
- LOG_WARN("num_page=%d, max_page=%d invalid", page_num, max_page);
+ log::warn("num_page={}, max_page={} invalid", page_num, max_page);
}
btm_read_remote_ext_features_complete(handle, page_num, max_page, p);
@@ -980,7 +979,7 @@
/* Validate parameters */
auto* p_acl_cb = internal_.acl_get_connection_from_handle(handle);
if (p_acl_cb == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return;
}
@@ -1000,13 +999,13 @@
* we have space to keep this page data - read this page */
if ((page_num < max_page) && (page_num < HCI_EXT_FEATURES_PAGE_MAX)) {
page_num++;
- LOG_DEBUG("BTM reads next remote extended features page (%d)", page_num);
+ log::debug("BTM reads next remote extended features page ({})", page_num);
btm_read_remote_ext_features(handle, page_num);
return;
}
/* Reading of remote feature pages is complete */
- LOG_DEBUG("BTM reached last remote extended features page (%d)", page_num);
+ log::debug("BTM reached last remote extended features page ({})", page_num);
/* Process the pages */
btm_process_remote_ext_features(p_acl_cb, max_page);
@@ -1026,11 +1025,11 @@
*
******************************************************************************/
void btm_read_remote_ext_features_failed(uint8_t status, uint16_t handle) {
- LOG_WARN("status 0x%02x for handle %d", status, handle);
+ log::warn("status 0x{:02x} for handle {}", status, handle);
tACL_CONN* p_acl_cb = internal_.acl_get_connection_from_handle(handle);
if (p_acl_cb == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return;
}
@@ -1063,9 +1062,10 @@
btm_cb.acl_cb_.DefaultPacketTypes();
if (!internal_.change_connection_packet_types(*p_acl,
default_packet_type_mask)) {
- LOG_ERROR("Unable to change connection packet type types:%04x address:%s",
- default_packet_type_mask,
- ADDRESS_TO_LOGGABLE_CSTR(p_acl->RemoteAddress()));
+ log::error(
+ "Unable to change connection packet type types:{:04x} address:{}",
+ default_packet_type_mask,
+ ADDRESS_TO_LOGGABLE_CSTR(p_acl->RemoteAddress()));
}
btm_set_link_policy(p_acl, btm_cb.acl_cb_.DefaultLinkPolicy());
}
@@ -1076,7 +1076,7 @@
tBT_TRANSPORT transport) {
tACL_CONN* p_acl = internal_.btm_bda_to_acl(bda, transport);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return;
}
internal_.btm_establish_continue(p_acl);
@@ -1097,7 +1097,7 @@
const tACL_CONN* p_acl =
internal_.btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return BTM_UNKNOWN_ADDR;
}
*p_timeout = p_acl->link_super_tout;
@@ -1117,7 +1117,7 @@
uint16_t timeout) {
tACL_CONN* p_acl = internal_.btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return BTM_UNKNOWN_ADDR;
}
@@ -1125,23 +1125,25 @@
if (p_acl->link_role == HCI_ROLE_CENTRAL) {
if (!bluetooth::shim::
controller_is_write_link_supervision_timeout_supported()) {
- LOG_WARN(
- "UNSUPPORTED by controller write link supervision timeout:%.2fms "
- "bd_addr:%s",
- supervision_timeout_to_seconds(timeout), ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
+ log::warn(
+ "UNSUPPORTED by controller write link supervision timeout:{:.2f}ms "
+ "bd_addr:{}",
+ supervision_timeout_to_seconds(timeout),
+ ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
return BTM_MODE_UNSUPPORTED;
}
p_acl->link_super_tout = timeout;
btsnd_hcic_write_link_super_tout(p_acl->hci_handle, timeout);
- LOG_DEBUG("Set supervision timeout:%.2fms bd_addr:%s",
- supervision_timeout_to_seconds(timeout),
- ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
+ log::debug("Set supervision timeout:{:.2f}ms bd_addr:{}",
+ supervision_timeout_to_seconds(timeout),
+ ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
return BTM_CMD_STARTED;
} else {
- LOG_WARN(
- "Role is peripheral so unable to set supervision timeout:%.2fms "
- "bd_addr:%s",
- supervision_timeout_to_seconds(timeout), ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
+ log::warn(
+ "Role is peripheral so unable to set supervision timeout:{:.2f}ms "
+ "bd_addr:{}",
+ supervision_timeout_to_seconds(timeout),
+ ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
return BTM_SUCCESS;
}
}
@@ -1155,7 +1157,7 @@
tBT_TRANSPORT transport) {
tACL_CONN* p_acl = internal_.btm_bda_to_acl(remote_bda, transport);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return false;
}
return p_acl->hci_handle != HCI_INVALID_HANDLE;
@@ -1240,17 +1242,15 @@
******************************************************************************/
bool BTM_IsPhy2mSupported(const RawAddress& remote_bda, tBT_TRANSPORT transport) {
tACL_CONN* p;
- LOG_VERBOSE("BTM_IsPhy2mSupported");
+ log::verbose("BTM_IsPhy2mSupported");
p = internal_.btm_bda_to_acl(remote_bda, transport);
if (p == (tACL_CONN*)NULL) {
- LOG_VERBOSE("BTM_IsPhy2mSupported: no connection");
+ log::verbose("BTM_IsPhy2mSupported: no connection");
return false;
}
if (!p->peer_le_features_valid) {
- LOG_WARN(
- "Checking remote features but remote feature read is "
- "incomplete");
+ log::warn("Checking remote features but remote feature read is incomplete");
}
return HCI_LE_2M_PHY_SUPPORTED(p->peer_le_features);
}
@@ -1267,7 +1267,7 @@
tACL_CONN* p;
p = internal_.btm_bda_to_acl(remote_bda, transport);
if (p == (tACL_CONN*)NULL) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return;
}
@@ -1290,7 +1290,7 @@
if (p != (tACL_CONN*)NULL) {
return (p->sca);
}
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
/* If here, no BD Addr found */
return (0xFF);
@@ -1315,7 +1315,7 @@
tACL_CONN* p = internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_BR_EDR);
if (!p) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return;
}
if (hci_status == HCI_SUCCESS) {
@@ -1336,9 +1336,9 @@
(!interop_match_addr(INTEROP_DYNAMIC_ROLE_SWITCH, &bd_addr))) {
p->switch_role_failed_attempts++;
if (p->switch_role_failed_attempts == BTM_MAX_SW_ROLE_FAILED_ATTEMPTS) {
- LOG_WARN(
- "Device %s rejectlisted for role switching - "
- "multiple role switch failed attempts: %u",
+ log::warn(
+ "Device {} rejectlisted for role switching - multiple role switch "
+ "failed attempts: {}",
ADDRESS_TO_LOGGABLE_CSTR(bd_addr), p->switch_role_failed_attempts);
interop_database_add(INTEROP_DYNAMIC_ROLE_SWITCH, &bd_addr, 3);
}
@@ -1389,14 +1389,15 @@
// If we get a role change before connection complete, we cache the new
// role here and then propagate it when ACL Link is created.
acl_cache_role(bd_addr, new_role, /*overwrite_cache=*/true);
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return;
}
tBTM_ROLE_SWITCH_CMPL* p_switch_role = &btm_cb.acl_cb_.switch_role_ref_data;
- LOG_DEBUG("Role change event received peer:%s hci_status:%s new_role:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), hci_error_code_text(hci_status).c_str(),
- RoleText(new_role).c_str());
+ log::debug("Role change event received peer:{} hci_status:{} new_role:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ hci_error_code_text(hci_status).c_str(),
+ RoleText(new_role).c_str());
p_switch_role->hci_status = hci_status;
if (hci_status == HCI_SUCCESS) {
@@ -1490,22 +1491,23 @@
packet_type_mask &= peer_packet_types.acl.supported;
packet_type_mask |= peer_packet_types.acl.unsupported;
} else {
- LOG_INFO(
+ log::info(
"Unable to include remote supported packet types as read feature "
"incomplete");
- LOG_INFO("TIP: Maybe wait until read feature complete beforehand");
+ log::info("TIP: Maybe wait until read feature complete beforehand");
}
if (packet_type_mask == 0) {
- LOG_WARN("Unable to send controller illegal change packet mask:0x%04x",
- packet_type_mask);
+ log::warn("Unable to send controller illegal change packet mask:0x{:04x}",
+ packet_type_mask);
return false;
}
link.pkt_types_mask = packet_type_mask;
GetInterface().ChangeConnectionPacketType(link.Handle(), link.pkt_types_mask);
- LOG_DEBUG("Started change connection packet type:0x%04x address:%s",
- link.pkt_types_mask, ADDRESS_TO_LOGGABLE_CSTR(link.RemoteAddress()));
+ log::debug("Started change connection packet type:0x{:04x} address:{}",
+ link.pkt_types_mask,
+ ADDRESS_TO_LOGGABLE_CSTR(link.RemoteAddress()));
return true;
}
@@ -1513,13 +1515,14 @@
uint16_t pkt_types) {
tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_BR_EDR);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return;
}
if (!internal_.change_connection_packet_types(*p_acl, pkt_types)) {
- LOG_ERROR("Unable to change connection packet type types:%04x address:%s",
- pkt_types, ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::error(
+ "Unable to change connection packet type types:{:04x} address:{}",
+ pkt_types, ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
}
}
@@ -1604,13 +1607,13 @@
if (p_acl == nullptr) {
p_acl = internal_.btm_bda_to_acl(addr, BT_TRANSPORT_LE);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return false;
}
}
if (!p_acl->remote_version_info.valid) {
- LOG_WARN("Remote version information is invalid");
+ log::warn("Remote version information is invalid");
return false;
}
@@ -1634,7 +1637,7 @@
uint8_t* BTM_ReadRemoteFeatures(const RawAddress& addr) {
tACL_CONN* p = internal_.btm_bda_to_acl(addr, BT_TRANSPORT_BR_EDR);
if (p == NULL) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return (NULL);
}
@@ -1679,7 +1682,7 @@
btsnd_hcic_read_rssi(p->hci_handle);
return (BTM_CMD_STARTED);
}
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
/* If here, no BD Addr found */
return (BTM_UNKNOWN_ADDR);
@@ -1719,7 +1722,7 @@
btsnd_hcic_read_failed_contact_counter(p->hci_handle);
return (BTM_CMD_STARTED);
}
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
/* If here, no BD Addr found */
return (BTM_UNKNOWN_ADDR);
@@ -1743,7 +1746,7 @@
#define BTM_READ_RSSI_TYPE_CUR 0x00
#define BTM_READ_RSSI_TYPE_MAX 0X01
- VLOG(2) << __func__ << ": RemBdAddr: " << ADDRESS_TO_LOGGABLE_STR(remote_bda);
+ log::verbose("RemBdAddr: {}", ADDRESS_TO_LOGGABLE_STR(remote_bda));
/* If someone already waiting on the version, do not allow another */
if (btm_cb.devcb.p_tx_power_cmpl_cb) return (BTM_BUSY);
@@ -1765,7 +1768,7 @@
return (BTM_CMD_STARTED);
}
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
/* If here, no BD Addr found */
return (BTM_UNKNOWN_ADDR);
@@ -1836,10 +1839,10 @@
STREAM_TO_UINT8(result.tx_power, p);
result.rem_bda = btm_cb.devcb.read_tx_pwr_addr;
}
- LOG_DEBUG("Transmit power complete: tx_power:%d hci status:%s",
- result.tx_power,
- hci_error_code_text(static_cast<tHCI_STATUS>(result.hci_status))
- .c_str());
+ log::debug(
+ "Transmit power complete: tx_power:{} hci status:{}", result.tx_power,
+ hci_error_code_text(static_cast<tHCI_STATUS>(result.hci_status))
+ .c_str());
} else {
result.status = BTM_ERR_PROCESSING;
}
@@ -1850,7 +1853,7 @@
return;
err_out:
- LOG_ERROR("Bogus event packet, too short");
+ log::error("Bogus event packet, too short");
}
/*******************************************************************************
@@ -1905,9 +1908,7 @@
STREAM_TO_UINT16(handle, p);
STREAM_TO_UINT8(result.rssi, p);
- LOG_DEBUG("Read rrsi complete rssi:%hhd hci status:%s", result.rssi,
- hci_error_code_text(static_cast<tHCI_STATUS>(result.hci_status))
- .c_str());
+ log::debug("Read rrsi complete rssi:%hhd hci status:{}", result.rssi);
tACL_CONN* p_acl_cb = internal_.acl_get_connection_from_handle(handle);
if (p_acl_cb != nullptr) {
@@ -1921,7 +1922,7 @@
return;
err_out:
- LOG_ERROR("Bogus event packet, too short");
+ log::error("Bogus event packet, too short");
}
/*******************************************************************************
@@ -1970,8 +1971,8 @@
STREAM_TO_UINT16(handle, p);
STREAM_TO_UINT16(result.failed_contact_counter, p);
- LOG_DEBUG(
- "Failed contact counter complete: counter %u, hci status:%s",
+ log::debug(
+ "Failed contact counter complete: counter {}, hci status:{}",
result.failed_contact_counter,
hci_status_code_text(to_hci_status_code(result.hci_status)).c_str());
@@ -2016,8 +2017,8 @@
STREAM_TO_UINT16(handle, p);
STREAM_TO_UINT16(result.automatic_flush_timeout, p);
- LOG_DEBUG(
- "Read automatic flush timeout complete timeout:%hu hci_status:%s",
+ log::debug(
+ "Read automatic flush timeout complete timeout:{} hci_status:{}",
result.automatic_flush_timeout,
hci_error_code_text(static_cast<tHCI_STATUS>(result.hci_status))
.c_str());
@@ -2082,10 +2083,11 @@
STREAM_TO_UINT16(handle, p);
STREAM_TO_UINT8(result.link_quality, p);
- LOG_DEBUG("BTM Link Quality Complete: Link Quality %d, hci status:%s",
- result.link_quality,
- hci_error_code_text(static_cast<tHCI_STATUS>(result.hci_status))
- .c_str());
+ log::debug(
+ "BTM Link Quality Complete: Link Quality {}, hci status:{}",
+ result.link_quality,
+ hci_error_code_text(static_cast<tHCI_STATUS>(result.hci_status))
+ .c_str());
tACL_CONN* p_acl_cb = internal_.acl_get_connection_from_handle(handle);
if (p_acl_cb != nullptr) {
@@ -2101,7 +2103,7 @@
return;
err_out:
- LOG_ERROR("Bogus Link Quality event packet, size: %d", evt_len);
+ log::error("Bogus Link Quality event packet, size: {}", evt_len);
}
/*******************************************************************************
@@ -2117,21 +2119,23 @@
tBTM_STATUS btm_remove_acl(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, transport);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return BTM_UNKNOWN_ADDR;
}
if (p_acl->Handle() == HCI_INVALID_HANDLE) {
- LOG_WARN("Cannot remove unknown acl bd_addr:%s transport:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), bt_transport_text(transport).c_str());
+ log::warn("Cannot remove unknown acl bd_addr:{} transport:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ bt_transport_text(transport).c_str());
return BTM_UNKNOWN_ADDR;
}
if (p_acl->rs_disc_pending == BTM_SEC_RS_PENDING) {
- LOG_DEBUG(
- "Delay disconnect until role switch is complete bd_addr:%s "
- "transport:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), bt_transport_text(transport).c_str());
+ log::debug(
+ "Delay disconnect until role switch is complete bd_addr:{} "
+ "transport:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ bt_transport_text(transport).c_str());
p_acl->rs_disc_pending = BTM_SEC_DISC_PENDING;
return BTM_SUCCESS;
}
@@ -2144,7 +2148,7 @@
void btm_cont_rswitch_from_handle(uint16_t hci_handle) {
tACL_CONN* p = internal_.acl_get_connection_from_handle(hci_handle);
if (p == nullptr) {
- LOG_WARN("Role switch received but with no active ACL");
+ log::warn("Role switch received but with no active ACL");
return;
}
@@ -2192,7 +2196,7 @@
const RawAddress& rpa) {
tACL_CONN* p_acl = internal_.btm_bda_to_acl(bda, BT_TRANSPORT_LE);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return false;
}
@@ -2210,7 +2214,7 @@
p_acl->active_remote_addr = rpa;
}
- LOG_DEBUG("active_remote_addr_type: %d ", p_acl->active_remote_addr_type);
+ log::debug("active_remote_addr_type: {} ", p_acl->active_remote_addr_type);
return true;
}
@@ -2218,13 +2222,11 @@
const RawAddress& remote_bda) {
tACL_CONN* p_acl = internal_.btm_bda_to_acl(remote_bda, BT_TRANSPORT_LE);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return false;
}
if (!p_acl->peer_le_features_valid) {
- LOG_WARN(
- "Checking remote features but remote feature read is "
- "incomplete");
+ log::warn("Checking remote features but remote feature read is incomplete");
}
return HCI_LE_CONN_PARAM_REQ_SUPPORTED(p_acl->peer_le_features);
}
@@ -2232,13 +2234,11 @@
bool acl_peer_supports_sniff_subrating(const RawAddress& remote_bda) {
tACL_CONN* p_acl = internal_.btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return false;
}
if (!p_acl->peer_lmp_feature_valid[0]) {
- LOG_WARN(
- "Checking remote features but remote feature read is "
- "incomplete");
+ log::warn("Checking remote features but remote feature read is incomplete");
}
return HCI_SNIFF_SUB_RATE_SUPPORTED(p_acl->peer_lmp_feature_pages[0]);
}
@@ -2246,13 +2246,11 @@
bool acl_peer_supports_ble_connection_subrating(const RawAddress& remote_bda) {
tACL_CONN* p_acl = internal_.btm_bda_to_acl(remote_bda, BT_TRANSPORT_LE);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return false;
}
if (!p_acl->peer_le_features_valid) {
- LOG_WARN(
- "Checking remote features but remote feature read is "
- "incomplete");
+ log::warn("Checking remote features but remote feature read is incomplete");
}
return HCI_LE_CONN_SUBRATING_SUPPORT(p_acl->peer_le_features);
}
@@ -2261,13 +2259,11 @@
const RawAddress& remote_bda) {
tACL_CONN* p_acl = internal_.btm_bda_to_acl(remote_bda, BT_TRANSPORT_LE);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return false;
}
if (!p_acl->peer_le_features_valid) {
- LOG_WARN(
- "Checking remote features but remote feature read is "
- "incomplete");
+ log::warn("Checking remote features but remote feature read is incomplete");
}
return HCI_LE_CONN_SUBRATING_HOST_SUPPORT(p_acl->peer_le_features);
}
@@ -2287,8 +2283,8 @@
tBLE_ADDR_TYPE* p_addr_type, bool ota_address) {
tBTM_SEC_DEV_REC* p_sec_rec = btm_find_dev(remote_bda);
if (p_sec_rec == nullptr) {
- LOG_WARN("No matching known device %s in record",
- ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
+ log::warn("No matching known device {} in record",
+ ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
return;
}
@@ -2324,7 +2320,7 @@
tBT_TRANSPORT transport) {
tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, transport);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return false;
}
return p_acl->is_switch_role_idle();
@@ -2353,8 +2349,8 @@
bool ota_address) {
tBTM_SEC_DEV_REC* p_sec_rec = btm_find_dev(pseudo_addr);
if (p_sec_rec == nullptr) {
- LOG_WARN("No matching known device %s in record",
- ADDRESS_TO_LOGGABLE_CSTR(pseudo_addr));
+ log::warn("No matching known device {} in record",
+ ADDRESS_TO_LOGGABLE_CSTR(pseudo_addr));
return false;
}
@@ -2377,9 +2373,7 @@
return false;
}
if (!p_acl->peer_le_features_valid) {
- LOG_WARN(
- "Checking remote features but remote feature read is "
- "incomplete");
+ log::warn("Checking remote features but remote feature read is incomplete");
}
return HCI_LE_DATA_LEN_EXT_SUPPORTED(p_acl->peer_le_features);
}
@@ -2390,9 +2384,7 @@
return false;
}
if (!p_acl->peer_le_features_valid) {
- LOG_WARN(
- "Checking remote features but remote feature read is "
- "incomplete");
+ log::warn("Checking remote features but remote feature read is incomplete");
}
return HCI_LE_2M_PHY_SUPPORTED(p_acl->peer_le_features);
}
@@ -2403,9 +2395,7 @@
return false;
}
if (!p_acl->peer_le_features_valid) {
- LOG_WARN(
- "Checking remote features but remote feature read is "
- "incomplete");
+ log::warn("Checking remote features but remote feature read is incomplete");
return false;
}
return HCI_LE_CODED_PHY_SUPPORTED(p_acl->peer_le_features);
@@ -2436,7 +2426,7 @@
}
STREAM_TO_ARRAY(p_acl->peer_le_features, p, BD_FEATURES_LEN);
p_acl->peer_le_features_valid = true;
- LOG_DEBUG("Completed le feature read request");
+ log::debug("Completed le feature read request");
/* save LE remote supported features to iot conf file */
std::string key = IOT_CONF_KEY_RT_SUPP_FEATURES "_" + std::to_string(0);
@@ -2463,7 +2453,7 @@
tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(handle);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return;
}
@@ -2510,8 +2500,8 @@
void btm_acl_disconnected(tHCI_STATUS status, uint16_t handle,
tHCI_REASON reason) {
if (status != HCI_SUCCESS) {
- LOG_WARN("Received disconnect with error:%s",
- hci_error_code_text(status).c_str());
+ log::warn("Received disconnect with error:{}",
+ hci_error_code_text(status).c_str());
}
power_telemetry::GetInstance().LogLinkDetails(handle, RawAddress::kEmpty,
false, true);
@@ -2543,7 +2533,7 @@
/* Some device may request a connection before we are done with the HCI_Reset
* sequence */
if (!controller_get_interface()->get_is_ready()) {
- LOG_VERBOSE("Security Manager: connect request when device not ready");
+ log::verbose("Security Manager: connect request when device not ready");
btsnd_hcic_reject_conn(bda, HCI_ERR_HOST_REJECT_DEVICE);
return;
}
@@ -2581,9 +2571,9 @@
void acl_disconnect_after_role_switch(uint16_t conn_handle, tHCI_STATUS reason,
std::string comment) {
if (!is_disconnect_reason_valid(reason)) {
- LOG_WARN(
- "Controller will not accept invalid reason parameter:%s"
- " instead sending:%s",
+ log::warn(
+ "Controller will not accept invalid reason parameter:{} instead "
+ "sending:{}",
hci_error_code_text(reason).c_str(),
hci_error_code_text(HCI_ERR_PEER_USER).c_str());
reason = HCI_ERR_PEER_USER;
@@ -2591,7 +2581,7 @@
tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(conn_handle);
if (p_acl == nullptr) {
- LOG_ERROR("Sending disconnect for unknown acl:%hu PLEASE FIX", conn_handle);
+ log::error("Sending disconnect for unknown acl:{} PLEASE FIX", conn_handle);
GetInterface().Disconnect(conn_handle, reason);
return;
}
@@ -2599,14 +2589,13 @@
/* If a role switch is in progress, delay the HCI Disconnect to avoid
* controller problem */
if (p_acl->rs_disc_pending == BTM_SEC_RS_PENDING) {
- LOG_DEBUG(
+ log::debug(
"Role switch in progress - Set DISC Pending flag in "
- "btm_sec_send_hci_disconnect "
- "to delay disconnect");
+ "btm_sec_send_hci_disconnect to delay disconnect");
p_acl->rs_disc_pending = BTM_SEC_DISC_PENDING;
} else {
- LOG_DEBUG("Sending acl disconnect reason:%s [%hu]",
- hci_error_code_text(reason).c_str(), reason);
+ log::debug("Sending acl disconnect reason:{} [{}]",
+ hci_error_code_text(reason).c_str(), reason);
disconnect_acl(*p_acl, reason, comment);
}
}
@@ -2614,8 +2603,8 @@
void acl_send_data_packet_br_edr(const RawAddress& bd_addr, BT_HDR* p_buf) {
tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_BR_EDR);
if (p_acl == nullptr) {
- LOG_WARN("Acl br_edr data write for unknown device:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::warn("Acl br_edr data write for unknown device:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
osi_free(p_buf);
return;
}
@@ -2626,8 +2615,8 @@
void acl_send_data_packet_ble(const RawAddress& bd_addr, BT_HDR* p_buf) {
tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_LE);
if (p_acl == nullptr) {
- LOG_WARN("Acl le data write for unknown device:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::warn("Acl le data write for unknown device:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
osi_free(p_buf);
return;
}
@@ -2639,12 +2628,12 @@
uint16_t flush_timeout_in_ticks) {
tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, BT_TRANSPORT_BR_EDR);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return;
}
if (p_acl->flush_timeout_in_ticks == flush_timeout_in_ticks) {
- LOG_INFO(
- "Ignoring since cached value is same as requested flush_timeout:%hd",
+ log::info(
+ "Ignoring since cached value is same as requested flush_timeout:{}",
flush_timeout_in_ticks);
return;
}
@@ -2662,14 +2651,14 @@
find_in_device_record(bd_addr, &address_with_type);
- LOG_DEBUG("Creating le direct connection to:%s type:%s (initial type: %s)",
- ADDRESS_TO_LOGGABLE_CSTR(address_with_type),
- AddressTypeText(address_with_type.type).c_str(),
- AddressTypeText(addr_type).c_str());
+ log::debug("Creating le direct connection to:{} type:{} (initial type: {})",
+ ADDRESS_TO_LOGGABLE_CSTR(address_with_type),
+ AddressTypeText(address_with_type.type).c_str(),
+ AddressTypeText(addr_type).c_str());
if (address_with_type.type == BLE_ADDR_ANONYMOUS) {
- LOG_WARN(
- "Creating le direct connection to:%s, address type 'anonymous' is "
+ log::warn(
+ "Creating le direct connection to:{}, address type 'anonymous' is "
"invalid",
ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
return false;
@@ -2708,8 +2697,8 @@
STREAM_TO_UINT16(acl_header.hci_len, p);
if (acl_header.hci_len < L2CAP_PKT_OVERHEAD ||
acl_header.hci_len != p_msg->len - sizeof(acl_header)) {
- LOG_WARN("Received mismatched hci header length:%u data_len:%zu",
- acl_header.hci_len, p_msg->len - sizeof(acl_header));
+ log::warn("Received mismatched hci header length:{} data_len:{}",
+ acl_header.hci_len, p_msg->len - sizeof(acl_header));
osi_free(p_msg);
return;
}
@@ -2725,7 +2714,7 @@
void acl_process_supported_features(uint16_t handle, uint64_t features) {
tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(handle);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return;
}
const uint8_t current_page_number = 0;
@@ -2734,9 +2723,9 @@
(uint8_t*)&features, sizeof(uint64_t));
p_acl->peer_lmp_feature_valid[current_page_number] = true;
- LOG_DEBUG(
- "Copied supported feature pages handle:%hu current_page_number:%hhu "
- "features:%s",
+ log::debug(
+ "Copied supported feature pages handle:{} current_page_number:{} "
+ "features:{}",
handle, current_page_number,
bd_features_text(p_acl->peer_lmp_feature_pages[current_page_number])
.c_str());
@@ -2744,9 +2733,9 @@
if ((HCI_LMP_EXTENDED_SUPPORTED(p_acl->peer_lmp_feature_pages[0])) &&
(bluetooth::shim::GetController()->IsSupported(
bluetooth::hci::OpCode::READ_REMOTE_EXTENDED_FEATURES))) {
- LOG_DEBUG("Waiting for remote extended feature response to arrive");
+ log::debug("Waiting for remote extended feature response to arrive");
} else {
- LOG_DEBUG("No more remote features outstanding so notify upper layer");
+ log::debug("No more remote features outstanding so notify upper layer");
NotifyAclFeaturesReadComplete(*p_acl, current_page_number);
}
}
@@ -2754,21 +2743,21 @@
void acl_process_extended_features(uint16_t handle, uint8_t current_page_number,
uint8_t max_page_number, uint64_t features) {
if (current_page_number > HCI_EXT_FEATURES_PAGE_MAX) {
- LOG_WARN("Unable to process current_page_number:%hhu", current_page_number);
+ log::warn("Unable to process current_page_number:{}", current_page_number);
return;
}
tACL_CONN* p_acl = internal_.acl_get_connection_from_handle(handle);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return;
}
memcpy(p_acl->peer_lmp_feature_pages[current_page_number],
(uint8_t*)&features, sizeof(uint64_t));
p_acl->peer_lmp_feature_valid[current_page_number] = true;
- LOG_DEBUG(
- "Copied extended feature pages handle:%hu current_page_number:%hhu "
- "max_page_number:%hhu features:%s",
+ log::debug(
+ "Copied extended feature pages handle:{} current_page_number:{} "
+ "max_page_number:{} features:{}",
handle, current_page_number, max_page_number,
bd_features_text(p_acl->peer_lmp_feature_pages[current_page_number])
.c_str());
@@ -2779,17 +2768,17 @@
}
void ACL_RegisterClient(struct acl_client_callback_s* callbacks) {
- LOG_DEBUG("UNIMPLEMENTED");
+ log::debug("UNIMPLEMENTED");
}
void ACL_UnregisterClient(struct acl_client_callback_s* callbacks) {
- LOG_DEBUG("UNIMPLEMENTED");
+ log::debug("UNIMPLEMENTED");
}
tACL_CONN* btm_acl_for_bda(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
tACL_CONN* p_acl = internal_.btm_bda_to_acl(bd_addr, transport);
if (p_acl == nullptr) {
- LOG_WARN("Unable to find active acl");
+ log::warn("Unable to find active acl");
return nullptr;
}
return p_acl;
diff --git a/system/stack/acl/btm_pm.cc b/system/stack/acl/btm_pm.cc
index 77bacb8..caf6520 100644
--- a/system/stack/acl/btm_pm.cc
+++ b/system/stack/acl/btm_pm.cc
@@ -31,6 +31,7 @@
#define LOG_TAG "bt_btm_pm"
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <cstdint>
#include <unordered_map>
@@ -48,6 +49,8 @@
#include "stack/include/btm_status.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
void l2c_OnHciModeChangeSendPendingPackets(RawAddress remote);
void btm_sco_chk_pend_unpark(tHCI_STATUS status, uint16_t handle);
void btm_cont_rswitch_from_handle(uint16_t hci_handle);
@@ -149,8 +152,8 @@
void BTM_PM_OnConnected(uint16_t handle, const RawAddress& remote_bda) {
if (pm_mode_db.find(handle) != pm_mode_db.end()) {
- LOG_ERROR("Overwriting power mode db entry handle:%hu peer:%s", handle,
- ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
+ log::error("Overwriting power mode db entry handle:{} peer:{}", handle,
+ ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
}
pm_mode_db[handle] = {};
pm_mode_db[handle].Init(remote_bda, handle);
@@ -158,7 +161,7 @@
void BTM_PM_OnDisconnected(uint16_t handle) {
if (pm_mode_db.find(handle) == pm_mode_db.end()) {
- LOG_ERROR("Erasing unknown power mode db entry handle:%hu", handle);
+ log::error("Erasing unknown power mode db entry handle:{}", handle);
}
pm_mode_db.erase(handle);
if (handle == pm_pend_link) {
@@ -184,28 +187,28 @@
}
if (!p_mode) {
- LOG_ERROR("pm_id: %u, p_mode is null for %s", unsigned(pm_id),
- ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
+ log::error("pm_id: {}, p_mode is null for {}", unsigned(pm_id),
+ ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
return BTM_ILLEGAL_VALUE;
}
// per ACL link
auto* p_cb = btm_pm_get_power_manager_from_address(remote_bda);
if (p_cb == nullptr) {
- LOG_WARN("Unable to find power manager for peer: %s",
- ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
+ log::warn("Unable to find power manager for peer: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
return BTM_UNKNOWN_ADDR;
}
uint16_t handle = p_cb->handle_;
tBTM_PM_MODE mode = p_mode->mode;
if (!is_legal_power_mode(mode)) {
- LOG_ERROR("Unable to set illegal power mode value:0x%02x", mode);
+ log::error("Unable to set illegal power mode value:0x{:02x}", mode);
return BTM_ILLEGAL_VALUE;
}
if (p_mode->mode & BTM_PM_MD_FORCE) {
- LOG_INFO("Attempting to force into this power mode");
+ log::info("Attempting to force into this power mode");
/* take out the force bit */
mode &= (~BTM_PM_MD_FORCE);
}
@@ -216,8 +219,8 @@
(mode == BTM_PM_MD_SNIFF && !controller->SupportsSniffMode()) ||
(mode == BTM_PM_MD_PARK && !controller->SupportsParkMode()) ||
interop_match_addr(INTEROP_DISABLE_SNIFF, &remote_bda)) {
- LOG_ERROR("pm_id %u mode %u is not supported for %s", pm_id, mode,
- ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
+ log::error("pm_id {} mode {} is not supported for {}", pm_id, mode,
+ ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
return BTM_MODE_UNSUPPORTED;
}
}
@@ -230,9 +233,9 @@
(p_mode->min <= p_cb->interval)) ||
((p_mode->mode & BTM_PM_MD_FORCE) == 0 &&
(p_mode->max >= p_cb->interval))) {
- LOG_DEBUG(
- "Device is already in requested mode %d, interval: %d, max: %d, min: "
- "%d",
+ log::debug(
+ "Device is already in requested mode {}, interval: {}, max: {}, min: "
+ "{}",
p_mode->mode, p_cb->interval, p_mode->max, p_mode->min);
return BTM_SUCCESS;
}
@@ -250,23 +253,24 @@
/* if mode == hold or pending, return */
if ((p_cb->state == BTM_PM_STS_HOLD) || (p_cb->state == BTM_PM_STS_PENDING) ||
(pm_pend_link != 0)) {
- LOG_INFO(
- "Current power mode is hold or pending status or pending links"
- " state:%s[%hhu] pm_pending_link:%hu",
+ log::info(
+ "Current power mode is hold or pending status or pending links "
+ "state:{}[{}] pm_pending_link:{}",
power_mode_state_text(p_cb->state).c_str(), p_cb->state, pm_pend_link);
/* command pending */
if (handle != pm_pend_link) {
p_cb->state |= BTM_PM_STORED_MASK;
- LOG_INFO("Setting stored bitmask for peer:%s",
- ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
+ log::info("Setting stored bitmask for peer:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
}
return BTM_CMD_STORED;
}
- LOG_INFO(
- "Setting power mode for peer:%s current_mode:%s[%hhu] new_mode:%s[%hhu]",
- ADDRESS_TO_LOGGABLE_CSTR(remote_bda), power_mode_state_text(p_cb->state).c_str(),
- p_cb->state, power_mode_text(p_mode->mode).c_str(), p_mode->mode);
+ log::info(
+ "Setting power mode for peer:{} current_mode:{}[{}] new_mode:{}[{}]",
+ ADDRESS_TO_LOGGABLE_CSTR(remote_bda),
+ power_mode_state_text(p_cb->state).c_str(), p_cb->state,
+ power_mode_text(p_mode->mode).c_str(), p_mode->mode);
return btm_pm_snd_md_req(p_cb->handle_, pm_id, p_cb->handle_, p_mode);
}
@@ -287,12 +291,12 @@
bool BTM_ReadPowerMode(const RawAddress& remote_bda, tBTM_PM_MODE* p_mode) {
if (p_mode == nullptr) {
- LOG_ERROR("power mode is nullptr");
+ log::error("power mode is nullptr");
return false;
}
tBTM_PM_MCB* p_mcb = btm_pm_get_power_manager_from_address(remote_bda);
if (p_mcb == nullptr) {
- LOG_WARN("Unknown device:%s", ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
+ log::warn("Unknown device:{}", ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
return false;
}
*p_mode = static_cast<tBTM_PM_MODE>(p_mcb->state);
@@ -321,29 +325,28 @@
uint16_t min_rmt_to, uint16_t min_loc_to) {
tBTM_PM_MCB* p_cb = btm_pm_get_power_manager_from_address(remote_bda);
if (p_cb == nullptr) {
- LOG_WARN("Unable to find power manager for peer:%s",
- ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
+ log::warn("Unable to find power manager for peer:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
return BTM_UNKNOWN_ADDR;
}
const controller_t* controller = controller_get_interface();
if (!controller->SupportsSniffSubrating()) {
- LOG_INFO("No controller support for sniff subrating");
+ log::info("No controller support for sniff subrating");
return BTM_SUCCESS;
}
if (p_cb->state == BTM_PM_ST_ACTIVE || p_cb->state == BTM_PM_ST_SNIFF) {
- LOG_INFO(
- "Set sniff subrating state:%s[%d] max_latency:0x%04x "
- "min_remote_timeout:0x%04x"
- " min_local_timeout:0x%04x",
+ log::info(
+ "Set sniff subrating state:{}[{}] max_latency:0x{:04x} "
+ "min_remote_timeout:0x{:04x} min_local_timeout:0x{:04x}",
power_mode_state_text(p_cb->state).c_str(), p_cb->state, max_lat,
min_rmt_to, min_loc_to);
send_sniff_subrating(p_cb->handle_, remote_bda, max_lat, min_rmt_to,
min_loc_to);
return BTM_SUCCESS;
}
- LOG_INFO("pm_mode_db state: %d", p_cb->state);
+ log::info("pm_mode_db state: {}", p_cb->state);
p_cb->max_lat = max_lat;
p_cb->min_rmt_to = min_rmt_to;
p_cb->min_loc_to = min_loc_to;
@@ -378,7 +381,7 @@
pm_mode_db.clear();
pm_pend_id = 0;
memset(&pm_reg_db, 0, sizeof(pm_reg_db));
- LOG_INFO("reset pm");
+ log::info("reset pm");
}
/*******************************************************************************
@@ -523,37 +526,36 @@
mode = btm_pm_get_set_mode(pm_id, p_cb, p_mode, &md_res);
md_res.mode = mode;
- LOG_DEBUG("Found controller in mode:%s", power_mode_text(mode).c_str());
+ log::debug("Found controller in mode:{}", power_mode_text(mode).c_str());
if (p_cb->state == mode) {
- LOG_INFO(
- "Link already in requested mode pm_id:%hhu link_ind:%d mode:%s[%hhu]",
- pm_id, link_ind, power_mode_text(mode).c_str(), mode);
+ log::info("Link already in requested mode pm_id:{} link_ind:{} mode:{}[{}]",
+ pm_id, link_ind, power_mode_text(mode).c_str(), mode);
/* already in the resulting mode */
if ((mode == BTM_PM_MD_ACTIVE) ||
((md_res.max >= p_cb->interval) && (md_res.min <= p_cb->interval))) {
- LOG_DEBUG("Storing command");
+ log::debug("Storing command");
return BTM_CMD_STORED;
}
- LOG_DEBUG("Need to wake then sleep");
+ log::debug("Need to wake then sleep");
chg_ind = true;
}
p_cb->chg_ind = chg_ind;
/* cannot go directly from current mode to resulting mode. */
if (mode != BTM_PM_MD_ACTIVE && p_cb->state != BTM_PM_MD_ACTIVE) {
- LOG_DEBUG("Power mode change delay required");
+ log::debug("Power mode change delay required");
p_cb->chg_ind = true; /* needs to wake, then sleep */
}
if (p_cb->chg_ind) {
- LOG_DEBUG("Need to wake first");
+ log::debug("Need to wake first");
md_res.mode = BTM_PM_MD_ACTIVE;
} else if (BTM_PM_MD_SNIFF == md_res.mode && p_cb->max_lat) {
const controller_t* controller = controller_get_interface();
if (controller->SupportsSniffSubrating()) {
- LOG_DEBUG("Sending sniff subrating to controller");
+ log::debug("Sending sniff subrating to controller");
send_sniff_subrating(handle, p_cb->bda_, p_cb->max_lat, p_cb->min_rmt_to,
p_cb->min_loc_to);
}
@@ -565,9 +567,9 @@
/* send the appropriate HCI command */
pm_pend_id = pm_id;
- LOG_INFO("Switching from %s[0x%02x] to %s[0x%02x]",
- power_mode_state_text(p_cb->state).c_str(), p_cb->state,
- power_mode_state_text(md_res.mode).c_str(), md_res.mode);
+ log::info("Switching from {}[0x{:02x}] to {}[0x{:02x}]",
+ power_mode_state_text(p_cb->state).c_str(), p_cb->state,
+ power_mode_state_text(md_res.mode).c_str(), md_res.mode);
BTM_LogHistory(kBtmLogTag, p_cb->bda_, "Power mode change",
base::StringPrintf(
"%s[0x%02x] ==> %s[0x%02x]",
@@ -613,7 +615,7 @@
if (pm_pend_link == 0) {
/* the command was not sent */
- LOG_ERROR("pm_pending_link maxed out");
+ log::error("pm_pending_link maxed out");
return (BTM_NO_RESOURCES);
}
@@ -624,8 +626,8 @@
for (auto& entry : pm_mode_db) {
if (entry.second.state & BTM_PM_STORED_MASK) {
entry.second.state &= ~BTM_PM_STORED_MASK;
- LOG_INFO("Found another link requiring power mode change:%s",
- ADDRESS_TO_LOGGABLE_CSTR(entry.second.bda_));
+ log::info("Found another link requiring power mode change:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(entry.second.bda_));
btm_pm_snd_md_req(entry.second.handle_, BTM_PM_SET_ONLY_ID,
entry.second.handle_, NULL);
return;
@@ -647,15 +649,15 @@
******************************************************************************/
void btm_pm_proc_cmd_status(tHCI_STATUS status) {
if (pm_pend_link == 0) {
- LOG_ERROR(
+ log::error(
"There are no links pending power mode changes; try to find other "
"pending changes");
btm_pm_continue_pending_mode_changes();
return;
}
if (pm_mode_db.count(pm_pend_link) == 0) {
- LOG_ERROR(
- "Got PM change status for disconnected link %d; forgot to clean up "
+ log::error(
+ "Got PM change status for disconnected link {}; forgot to clean up "
"pm_pend_link?",
pm_pend_link);
btm_pm_continue_pending_mode_changes();
@@ -675,13 +677,13 @@
/* notify the caller is appropriate */
if ((pm_pend_id != BTM_PM_SET_ONLY_ID) && (pm_reg_db.mask & BTM_PM_REG_SET)) {
const RawAddress bd_addr = pm_mode_db[pm_pend_link].bda_;
- LOG_DEBUG("Notifying callback that link power mode is complete peer:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::debug("Notifying callback that link power mode is complete peer:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
(*pm_reg_db.cback)(bd_addr, pm_status, 0, status);
}
- LOG_INFO("Clearing pending power mode link state:%s",
- power_mode_state_text(p_cb->state).c_str());
+ log::info("Clearing pending power mode link state:{}",
+ power_mode_state_text(p_cb->state).c_str());
pm_pend_link = 0;
btm_pm_continue_pending_mode_changes();
@@ -710,7 +712,7 @@
/* update control block */
if (pm_mode_db.count(hci_handle) == 0) {
- LOG_WARN("Unable to find active acl for handle %d", hci_handle);
+ log::warn("Unable to find active acl for handle {}", hci_handle);
return;
}
tBTM_PM_MCB* p_cb = &pm_mode_db[hci_handle];
@@ -719,9 +721,9 @@
p_cb->state = mode;
p_cb->interval = interval;
- LOG_INFO("Power mode switched from %s[%hhu] to %s[%hhu]",
- power_mode_state_text(old_state).c_str(), old_state,
- power_mode_state_text(p_cb->state).c_str(), p_cb->state);
+ log::info("Power mode switched from {}[{}] to {}[{}]",
+ power_mode_state_text(old_state).c_str(), old_state,
+ power_mode_state_text(p_cb->state).c_str(), p_cb->state);
if ((p_cb->state == BTM_PM_ST_ACTIVE) || (p_cb->state == BTM_PM_ST_SNIFF)) {
l2c_OnHciModeChangeSendPendingPackets(p_cb->bda_);
@@ -772,7 +774,7 @@
void process_ssr_event(tHCI_STATUS status, uint16_t handle,
UNUSED_ATTR uint16_t max_tx_lat, uint16_t max_rx_lat) {
if (pm_mode_db.count(handle) == 0) {
- LOG_WARN("Received sniff subrating event with no active ACL");
+ log::warn("Received sniff subrating event with no active ACL");
return;
}
tBTM_PM_MCB* p_cb = &pm_mode_db[handle];
@@ -780,10 +782,10 @@
bool use_ssr = true;
if (p_cb->interval == max_rx_lat) {
- LOG_DEBUG("Sniff subrating unsupported so dropping to legacy sniff mode");
+ log::debug("Sniff subrating unsupported so dropping to legacy sniff mode");
use_ssr = false;
} else {
- LOG_DEBUG("Sniff subrating enabled");
+ log::debug("Sniff subrating enabled");
}
int cnt = 0;
@@ -791,9 +793,9 @@
(*pm_reg_db.cback)(bd_addr, BTM_PM_STS_SSR, (use_ssr) ? 1 : 0, status);
cnt++;
}
- LOG_DEBUG(
- "Notified sniff subrating registered clients cnt:%d peer:%s use_ssr:%s "
- "status:%s",
+ log::debug(
+ "Notified sniff subrating registered clients cnt:{} peer:{} use_ssr:{} "
+ "status:{}",
cnt, ADDRESS_TO_LOGGABLE_CSTR(bd_addr), logbool(use_ssr).c_str(),
hci_error_code_text(status).c_str());
}
@@ -842,7 +844,7 @@
/* Check BLE states */
if (!btm_cb.ble_ctr_cb.is_connection_state_idle()) {
- LOG_VERBOSE("%s - BLE state is not idle", __func__);
+ log::verbose("- BLE state is not idle");
return true;
}
@@ -851,24 +853,18 @@
/*******************************************************************************
*
- * Function btm_pm_device_in_scan_state
+ * Function BTM_PM_DeviceInScanState
*
- * Description This function is called to check if in paging, inquiry or
- * connecting mode
+ * Description This function is called to check if in inquiry
*
- * Returns true, if in paging, inquiry or connecting mode
+ * Returns true, if in inquiry
*
******************************************************************************/
-static bool btm_pm_device_in_scan_state(void) {
- /* Scan state-paging, inquiry, and trying to connect */
-
- /* Check for paging */
- // TODO: Get this information from connection manager?
-
+bool BTM_PM_DeviceInScanState(void) {
/* Check for inquiry */
if ((btm_cb.btm_inq_vars.inq_active &
(BTM_BR_INQ_ACTIVE_MASK | BTM_BLE_INQ_ACTIVE_MASK)) != 0) {
- LOG_VERBOSE("btm_pm_device_in_scan_state- Inq active");
+ log::verbose("BTM_PM_DeviceInScanState- Inq active");
return true;
}
@@ -888,12 +884,65 @@
tBTM_CONTRL_STATE BTM_PM_ReadControllerState(void) {
if (btm_pm_device_in_active_or_sniff_mode())
return BTM_CONTRL_ACTIVE;
- else if (btm_pm_device_in_scan_state())
+ else if (BTM_PM_DeviceInScanState())
return BTM_CONTRL_SCAN;
else
return BTM_CONTRL_IDLE;
}
+/*******************************************************************************
+ *
+ * Function BTM_PM_ReadSniffLinkCount
+ *
+ * Description Return the number of BT connection in sniff mode
+ *
+ * Returns Number of BT connection in sniff mode
+ *
+ ******************************************************************************/
+uint8_t BTM_PM_ReadSniffLinkCount(void) {
+ uint8_t count = 0;
+ for (auto& entry : pm_mode_db) {
+ if (entry.second.state == HCI_MODE_SNIFF) {
+ ++count;
+ }
+ }
+ return count;
+}
+
+/*******************************************************************************
+ *
+ * Function BTM_PM_ReadBleLinkCount
+ *
+ * Description Return the number of BLE connection
+ *
+ * Returns Number of BLE connection
+ *
+ ******************************************************************************/
+uint8_t BTM_PM_ReadBleLinkCount(void) {
+ return btm_cb.ble_ctr_cb.link_count[HCI_ROLE_CENTRAL] +
+ btm_cb.ble_ctr_cb.link_count[HCI_ROLE_PERIPHERAL];
+}
+
+/*******************************************************************************
+ *
+ * Function BTM_PM_ReadBleScanDutyCycle
+ *
+ * Description Returns BLE scan duty cycle which is (window * 100) /
+ *interval
+ *
+ * Returns BLE scan duty cycle
+ *
+ ******************************************************************************/
+uint32_t BTM_PM_ReadBleScanDutyCycle(void) {
+ if (!btm_cb.ble_ctr_cb.is_ble_scan_active()) {
+ return 0;
+ }
+ uint32_t scan_window = btm_cb.ble_ctr_cb.inq_var.scan_window;
+ uint32_t scan_interval = btm_cb.ble_ctr_cb.inq_var.scan_interval;
+ log::debug("LE scan_window:{} scan interval:{}", scan_window, scan_interval);
+ return (scan_window * 100) / scan_interval;
+}
+
void btm_pm_on_mode_change(tHCI_STATUS status, uint16_t handle,
tHCI_MODE current_mode, uint16_t interval) {
btm_sco_chk_pend_unpark(status, handle);
diff --git a/system/stack/arbiter/acl_arbiter.cc b/system/stack/arbiter/acl_arbiter.cc
index f1321c1..c80f98a 100644
--- a/system/stack/arbiter/acl_arbiter.cc
+++ b/system/stack/arbiter/acl_arbiter.cc
@@ -17,10 +17,10 @@
#include "stack/arbiter/acl_arbiter.h"
#include <base/functional/bind.h>
+#include <bluetooth/log.h>
#include <iterator>
-#include "os/log.h"
#include "osi/include/allocator.h"
#include "stack/gatt/gatt_int.h"
#include "stack/include/l2c_api.h"
@@ -80,18 +80,18 @@
class RustGattAclArbiter : public AclArbiter {
public:
virtual void OnLeConnect(uint8_t tcb_idx, uint16_t advertiser_id) override {
- LOG_INFO("Notifying Rust of LE connection");
+ log::info("Notifying Rust of LE connection");
callbacks_.on_le_connect(tcb_idx, advertiser_id);
}
virtual void OnLeDisconnect(uint8_t tcb_idx) override {
- LOG_INFO("Notifying Rust of LE disconnection");
+ log::info("Notifying Rust of LE disconnection");
callbacks_.on_le_disconnect(tcb_idx);
}
virtual InterceptAction InterceptAttPacket(uint8_t tcb_idx,
const BT_HDR* packet) override {
- LOG_DEBUG("Intercepting ATT packet and forwarding to Rust");
+ log::debug("Intercepting ATT packet and forwarding to Rust");
uint8_t* packet_start = (uint8_t*)(packet + 1) + packet->offset;
uint8_t* packet_end = packet_start + packet->len;
@@ -102,17 +102,17 @@
}
virtual void OnOutgoingMtuReq(uint8_t tcb_idx) override {
- LOG_DEBUG("Notifying Rust of outgoing MTU request");
+ log::debug("Notifying Rust of outgoing MTU request");
callbacks_.on_outgoing_mtu_req(tcb_idx);
}
virtual void OnIncomingMtuResp(uint8_t tcb_idx, size_t mtu) {
- LOG_DEBUG("Notifying Rust of incoming MTU response %zu", mtu);
+ log::debug("Notifying Rust of incoming MTU response {}", mtu);
callbacks_.on_incoming_mtu_resp(tcb_idx, mtu);
}
virtual void OnIncomingMtuReq(uint8_t tcb_idx, size_t mtu) {
- LOG_DEBUG("Notifying Rust of incoming MTU request %zu", mtu);
+ log::debug("Notifying Rust of incoming MTU request {}", mtu);
callbacks_.on_incoming_mtu_req(tcb_idx, mtu);
}
@@ -122,7 +122,7 @@
BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + buffer.size() +
L2CAP_MIN_OFFSET);
if (p_buf == nullptr) {
- LOG_ALWAYS_FATAL("OOM when sending packet");
+ log::fatal("OOM when sending packet");
}
auto p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
std::copy(buffer.begin(), buffer.end(), p);
@@ -130,7 +130,7 @@
p_buf->len = buffer.size();
L2CA_SendFixedChnlData(L2CAP_ATT_CID, p_tcb->peer_bda, p_buf);
} else {
- LOG_ERROR("Dropping packet since connection no longer exists");
+ log::error("Dropping packet since connection no longer exists");
}
}
@@ -148,7 +148,7 @@
::rust::Fn<void(uint8_t tcb_idx)> on_outgoing_mtu_req,
::rust::Fn<void(uint8_t tcb_idx, size_t mtu)> on_incoming_mtu_resp,
::rust::Fn<void(uint8_t tcb_idx, size_t mtu)> on_incoming_mtu_req) {
- LOG_INFO("Received callbacks from Rust, registering in Arbiter");
+ log::info("Received callbacks from Rust, registering in Arbiter");
callbacks_ = {on_le_connect, on_le_disconnect, intercept_packet,
on_outgoing_mtu_req, on_incoming_mtu_resp, on_incoming_mtu_req};
}
diff --git a/system/stack/avct/avct_api.cc b/system/stack/avct/avct_api.cc
index 8be7cc8..f50f592 100644
--- a/system/stack/avct/avct_api.cc
+++ b/system/stack/avct/avct_api.cc
@@ -24,6 +24,7 @@
#include "avct_api.h"
+#include <bluetooth/log.h>
#include <string.h>
#include "avct_int.h"
@@ -31,11 +32,12 @@
#include "internal_include/bt_target.h"
#include "l2c_api.h"
#include "l2cdefs.h"
-#include "os/log.h"
#include "osi/include/allocator.h"
#include "stack/include/bt_hdr.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
/* Control block for AVCT */
tAVCT_CB avct_cb;
@@ -54,7 +56,7 @@
*
******************************************************************************/
void AVCT_Register() {
- LOG_VERBOSE("AVCT_Register");
+ log::verbose("AVCT_Register");
/* initialize AVCTP data structures */
memset(&avct_cb, 0, sizeof(tAVCT_CB));
@@ -87,7 +89,7 @@
*
******************************************************************************/
void AVCT_Deregister(void) {
- LOG_VERBOSE("AVCT_Deregister");
+ log::verbose("AVCT_Deregister");
/* deregister PSM with L2CAP */
L2CA_Deregister(AVCT_PSM);
@@ -116,7 +118,7 @@
tAVCT_CCB* p_ccb;
tAVCT_LCB* p_lcb;
- LOG_VERBOSE("AVCT_CreateConn: %d, control:%d", p_cc->role, p_cc->control);
+ log::verbose("AVCT_CreateConn: {}, control:{}", p_cc->role, p_cc->control);
/* Allocate ccb; if no ccbs, return failure */
p_ccb = avct_ccb_alloc(p_cc);
@@ -147,7 +149,7 @@
if (result == AVCT_SUCCESS) {
/* bind lcb to ccb */
p_ccb->p_lcb = p_lcb;
- LOG_VERBOSE("ch_state: %d", p_lcb->ch_state);
+ log::verbose("ch_state: {}", p_lcb->ch_state);
tAVCT_LCB_EVT avct_lcb_evt;
avct_lcb_evt.p_ccb = p_ccb;
avct_lcb_event(p_lcb, AVCT_LCB_UL_BIND_EVT, &avct_lcb_evt);
@@ -174,7 +176,7 @@
uint16_t result = AVCT_SUCCESS;
tAVCT_CCB* p_ccb;
- LOG_VERBOSE("AVCT_RemoveConn");
+ log::verbose("AVCT_RemoveConn");
/* map handle to ccb */
p_ccb = avct_ccb_by_idx(handle);
@@ -217,7 +219,7 @@
tAVCT_BCB* p_bcb;
int index;
- LOG_VERBOSE("AVCT_CreateBrowse: %d", role);
+ log::verbose("AVCT_CreateBrowse: {}", role);
/* map handle to ccb */
p_ccb = avct_ccb_by_idx(handle);
@@ -251,7 +253,7 @@
/* bind bcb to ccb */
p_ccb->p_bcb = p_bcb;
p_bcb->peer_addr = p_ccb->p_lcb->peer_addr;
- LOG_VERBOSE("ch_state: %d", p_bcb->ch_state);
+ log::verbose("ch_state: {}", p_bcb->ch_state);
tAVCT_LCB_EVT avct_lcb_evt;
avct_lcb_evt.p_ccb = p_ccb;
avct_bcb_event(p_bcb, AVCT_LCB_UL_BIND_EVT, &avct_lcb_evt);
@@ -278,7 +280,7 @@
uint16_t result = AVCT_SUCCESS;
tAVCT_CCB* p_ccb;
- LOG_VERBOSE("AVCT_RemoveBrowse");
+ log::verbose("AVCT_RemoveBrowse");
/* map handle to ccb */
p_ccb = avct_ccb_by_idx(handle);
@@ -369,14 +371,13 @@
tAVCT_CCB* p_ccb;
tAVCT_UL_MSG ul_msg;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
/* verify p_msg parameter */
if (p_msg == NULL) {
return AVCT_NO_RESOURCES;
}
- LOG_VERBOSE("%s len: %d layer_specific: %d", __func__, p_msg->len,
- p_msg->layer_specific);
+ log::verbose("len: {} layer_specific: {}", p_msg->len, p_msg->layer_specific);
/* map handle to ccb */
p_ccb = avct_ccb_by_idx(handle);
diff --git a/system/stack/avct/avct_bcb_act.cc b/system/stack/avct/avct_bcb_act.cc
index 6a27097..a2264b8 100644
--- a/system/stack/avct/avct_bcb_act.cc
+++ b/system/stack/avct/avct_bcb_act.cc
@@ -28,19 +28,21 @@
#define LOG_TAG "bluetooth"
#include <android_bluetooth_sysprop.h>
+#include <bluetooth/log.h>
#include <string.h>
#include "avct_api.h"
#include "avct_int.h"
#include "bta/include/bta_sec_api.h"
#include "internal_include/bt_target.h"
-#include "os/log.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"
+using namespace bluetooth;
+
/* action function list */
const tAVCT_BCB_ACTION avct_bcb_action[] = {
avct_bcb_chnl_open, /* AVCT_LCB_CHNL_OPEN */
@@ -88,7 +90,7 @@
/* must be single packet - can not fragment */
if (pkt_type != AVCT_PKT_TYPE_SINGLE) {
osi_free_and_reset((void**)&p_buf);
- LOG_WARN("Pkt type=%d - fragmentation not allowed. drop it", pkt_type);
+ log::warn("Pkt type={} - fragmentation not allowed. drop it", pkt_type);
}
return p_buf;
}
@@ -422,8 +424,8 @@
(p_data->ul_msg.cr << 8) + p_data->ul_msg.label;
/* the channel is closed, opening or closing - open it again */
- LOG_VERBOSE("ch_state: %d, allocated:%d->%d", p_bcb->ch_state,
- p_bcb->allocated, p_data->ul_msg.p_ccb->p_lcb->allocated);
+ log::verbose("ch_state: {}, allocated:{}->{}", p_bcb->ch_state,
+ p_bcb->allocated, p_data->ul_msg.p_ccb->p_lcb->allocated);
p_bcb->allocated = p_data->ul_msg.p_ccb->p_lcb->allocated;
avct_bcb_event(p_bcb, AVCT_LCB_UL_BIND_EVT,
(tAVCT_LCB_EVT*)p_data->ul_msg.p_ccb);
@@ -452,8 +454,8 @@
/* initialize packet type and other stuff */
if (curr_msg_len > (p_bcb->peer_mtu - AVCT_HDR_LEN_SINGLE)) {
- LOG_ERROR("%s msg len (%d) exceeds peer mtu(%d-%d)!!", __func__,
- curr_msg_len, p_bcb->peer_mtu, AVCT_HDR_LEN_SINGLE);
+ log::error("msg len ({}) exceeds peer mtu({}-{})!!", curr_msg_len,
+ p_bcb->peer_mtu, AVCT_HDR_LEN_SINGLE);
osi_free_and_reset((void**)&p_data->ul_msg.p_buf);
return;
}
@@ -510,7 +512,7 @@
tAVCT_LCB* p_lcb = avct_lcb_by_bcb(p_bcb);
if ((p_data == NULL) || (p_data->p_buf == NULL)) {
- LOG_WARN("%s p_data is NULL, returning!", __func__);
+ log::warn("p_data is NULL, returning!");
return;
}
@@ -527,8 +529,8 @@
}
if (p_data->p_buf->len < AVCT_HDR_LEN_SINGLE) {
- LOG_WARN("Invalid AVCTP packet length %d: must be at least %d",
- p_data->p_buf->len, AVCT_HDR_LEN_SINGLE);
+ log::warn("Invalid AVCTP packet length {}: must be at least {}",
+ p_data->p_buf->len, AVCT_HDR_LEN_SINGLE);
osi_free_and_reset((void**)&p_data->p_buf);
return;
}
@@ -542,7 +544,7 @@
/* check for invalid cr_ipid */
if (cr_ipid == AVCT_CR_IPID_INVALID) {
- LOG_WARN("Invalid cr_ipid %d", cr_ipid);
+ log::warn("Invalid cr_ipid {}", cr_ipid);
osi_free_and_reset((void**)&p_data->p_buf);
return;
}
@@ -566,7 +568,7 @@
}
/* PID not found; drop message */
- LOG_WARN("No ccb for PID=%x", pid);
+ log::warn("No ccb for PID={:x}", pid);
osi_free_and_reset((void**)&p_data->p_buf);
/* if command send reject */
@@ -595,13 +597,13 @@
void avct_bcb_dealloc(tAVCT_BCB* p_bcb, UNUSED_ATTR tAVCT_LCB_EVT* p_data) {
tAVCT_CCB* p_ccb = &avct_cb.ccb[0];
- LOG_VERBOSE("%s %d", __func__, p_bcb->allocated);
+ log::verbose("{}", p_bcb->allocated);
for (int idx = 0; idx < AVCT_NUM_CONN; idx++, p_ccb++) {
/* if ccb allocated and */
if ((p_ccb->allocated) && (p_ccb->p_bcb == p_bcb)) {
p_ccb->p_bcb = NULL;
- LOG_VERBOSE("%s used by ccb: %d", __func__, idx);
+ log::verbose("used by ccb: {}", idx);
break;
}
}
@@ -699,6 +701,6 @@
}
/* out of lcbs */
- LOG_WARN("No bcb for lcid %x", lcid);
+ log::warn("No bcb for lcid {:x}", lcid);
return NULL;
}
diff --git a/system/stack/avct/avct_ccb.cc b/system/stack/avct/avct_ccb.cc
index 7f916c6..c31df28 100644
--- a/system/stack/avct/avct_ccb.cc
+++ b/system/stack/avct/avct_ccb.cc
@@ -25,14 +25,16 @@
#define LOG_TAG "avctp"
+#include <bluetooth/log.h>
#include <string.h>
#include "avct_api.h"
#include "avct_int.h"
#include "internal_include/bt_target.h"
-#include "os/log.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
/*******************************************************************************
*
* Function avct_ccb_alloc
@@ -51,7 +53,7 @@
if (!p_ccb->allocated) {
p_ccb->allocated = AVCT_ALOC_LCB;
memcpy(&p_ccb->cc, p_cc, sizeof(tAVCT_CC));
- LOG_VERBOSE("avct_ccb_alloc %d", i);
+ log::verbose("avct_ccb_alloc {}", i);
break;
}
}
@@ -59,7 +61,7 @@
if (i == AVCT_NUM_CONN) {
/* out of ccbs */
p_ccb = NULL;
- LOG_WARN("Out of ccbs");
+ log::warn("Out of ccbs");
}
return p_ccb;
}
@@ -79,7 +81,7 @@
const RawAddress* bd_addr) {
tAVCT_CTRL_CBACK* p_cback = p_ccb->cc.p_ctrl_cback;
- LOG_VERBOSE("avct_ccb_dealloc %d", avct_ccb_to_idx(p_ccb));
+ log::verbose("avct_ccb_dealloc {}", avct_ccb_to_idx(p_ccb));
if (p_ccb->p_bcb == NULL) {
memset(p_ccb, 0, sizeof(tAVCT_CCB));
@@ -131,11 +133,11 @@
/* verify ccb is allocated */
if (!p_ccb->allocated) {
p_ccb = NULL;
- LOG_WARN("ccb %d not allocated", idx);
+ log::warn("ccb {} not allocated", idx);
}
} else {
p_ccb = NULL;
- LOG_WARN("No ccb for idx %d", idx);
+ log::warn("No ccb for idx {}", idx);
}
return p_ccb;
}
diff --git a/system/stack/avct/avct_l2c.cc b/system/stack/avct/avct_l2c.cc
index b8b65fe..3287785 100644
--- a/system/stack/avct/avct_l2c.cc
+++ b/system/stack/avct/avct_l2c.cc
@@ -24,19 +24,20 @@
#define LOG_TAG "avctp"
#include <android_bluetooth_sysprop.h>
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include "avct_api.h"
#include "avct_int.h"
#include "internal_include/bt_target.h"
#include "l2c_api.h"
#include "l2cdefs.h"
-#include "os/log.h"
#include "osi/include/allocator.h"
#include "osi/include/osi.h"
#include "stack/include/bt_hdr.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
/* callback function declarations */
void avct_l2c_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid,
uint16_t psm, uint8_t id);
@@ -84,7 +85,7 @@
for (i = 0; i < AVCT_NUM_CONN; i++, p_ccb++) {
if (p_ccb->allocated && (p_ccb->p_lcb == p_lcb)) {
- LOG_VERBOSE("avct_l2c_is_ct control:x%x", p_ccb->cc.control);
+ log::verbose("avct_l2c_is_ct control:x{:x}", p_ccb->cc.control);
if (p_ccb->cc.control & AVCT_PASSIVE) {
is_passive = true;
break;
@@ -128,14 +129,14 @@
/* TG role only - accept the connection from CT. move the channel ID to
* the conflict list */
p_lcb->conflict_lcid = p_lcb->ch_lcid;
- LOG_VERBOSE("avct_l2c_connect_ind_cback conflict_lcid:0x%x",
- p_lcb->conflict_lcid);
+ log::verbose("avct_l2c_connect_ind_cback conflict_lcid:0x{:x}",
+ p_lcb->conflict_lcid);
}
}
if (p_lcb) {
- LOG_VERBOSE("avct_l2c_connect_ind_cback: 0x%x, res: %d, ch_state: %d", lcid,
- result, p_lcb->ch_state);
+ log::verbose("avct_l2c_connect_ind_cback: 0x{:x}, res: {}, ch_state: {}",
+ lcid, result, p_lcb->ch_state);
}
/* If we reject the connection, send DisconnectReq */
@@ -151,9 +152,10 @@
if (p_ccb && p_ccb->allocated && (p_ccb->p_lcb == NULL) &&
(p_ccb->cc.role == AVCT_ACP)) {
p_ccb->p_lcb = p_lcb;
- LOG_VERBOSE(
- "ACP bind %d ccb to lcb, alloc %d, lcb %p, role %d, pid 0x%x", i,
- p_ccb->allocated, p_ccb->p_lcb, p_ccb->cc.role, p_ccb->cc.pid);
+ log::verbose(
+ "ACP bind {} ccb to lcb, alloc {}, lcb {}, role {}, pid 0x{:x}",
+ i, p_ccb->allocated, fmt::ptr(p_ccb->p_lcb), p_ccb->cc.role,
+ p_ccb->cc.pid);
}
}
}
@@ -164,15 +166,15 @@
p_lcb->ch_state = AVCT_CH_CFG;
}
- if (p_lcb) LOG_VERBOSE("ch_state cni: %d ", p_lcb->ch_state);
+ if (p_lcb) log::verbose("ch_state cni: {} ", p_lcb->ch_state);
}
static void avct_on_l2cap_error(uint16_t lcid, uint16_t result) {
tAVCT_LCB* p_lcb = avct_lcb_by_lcid(lcid);
if (p_lcb == nullptr) return;
if (p_lcb->ch_state == AVCT_CH_CONN) {
- LOG_VERBOSE("avct_l2c_connect_cfm_cback conflict_lcid:0x%x",
- p_lcb->conflict_lcid);
+ log::verbose("avct_l2c_connect_cfm_cback conflict_lcid:0x{:x}",
+ p_lcb->conflict_lcid);
if (p_lcb->conflict_lcid == lcid) {
p_lcb->conflict_lcid = 0;
} else {
@@ -181,8 +183,8 @@
avct_lcb_event(p_lcb, AVCT_LCB_LL_CLOSE_EVT, &avct_lcb_evt);
}
} else if (p_lcb->ch_state == AVCT_CH_CFG) {
- LOG_VERBOSE("ERROR avct_l2c_config_cfm_cback L2CA_DisconnectReq %d ",
- p_lcb->ch_state);
+ log::verbose("ERROR avct_l2c_config_cfm_cback L2CA_DisconnectReq {} ",
+ p_lcb->ch_state);
/* store result value */
p_lcb->ch_result = result;
@@ -207,9 +209,9 @@
/* look up lcb for this channel */
p_lcb = avct_lcb_by_lcid(lcid);
if (p_lcb != NULL) {
- LOG_VERBOSE(
- "avct_l2c_connect_cfm_cback lcid:0x%x result: %d ch_state: %d, "
- "conflict_lcid:0x%x",
+ log::verbose(
+ "avct_l2c_connect_cfm_cback lcid:0x{:x} result: {} ch_state: {}, "
+ "conflict_lcid:0x{:x}",
lcid, result, p_lcb->ch_state, p_lcb->conflict_lcid);
/* if in correct state */
if (p_lcb->ch_state == AVCT_CH_CONN) {
@@ -220,12 +222,13 @@
}
/* else failure */
else {
- LOG(ERROR) << __func__ << ": invoked with non OK status";
+ log::error("invoked with non OK status");
}
} else if (p_lcb->conflict_lcid == lcid) {
/* we must be in AVCT_CH_CFG state for the ch_lcid channel */
- LOG_VERBOSE("avct_l2c_connect_cfm_cback ch_state: %d, conflict_lcid:0x%x",
- p_lcb->ch_state, p_lcb->conflict_lcid);
+ log::verbose(
+ "avct_l2c_connect_cfm_cback ch_state: {}, conflict_lcid:0x{:x}",
+ p_lcb->ch_state, p_lcb->conflict_lcid);
if (result == L2CAP_CONN_OK) {
/* just in case the peer also accepts our connection - Send L2CAP
* disconnect req */
@@ -233,7 +236,7 @@
}
p_lcb->conflict_lcid = 0;
}
- LOG_VERBOSE("ch_state cnc: %d ", p_lcb->ch_state);
+ log::verbose("ch_state cnc: {} ", p_lcb->ch_state);
}
}
@@ -256,14 +259,14 @@
/* look up lcb for this channel */
p_lcb = avct_lcb_by_lcid(lcid);
if (p_lcb != NULL) {
- LOG_VERBOSE("avct_l2c_config_cfm_cback: 0x%x, ch_state: %d,", lcid,
- p_lcb->ch_state);
+ log::verbose("avct_l2c_config_cfm_cback: 0x{:x}, ch_state: {},", lcid,
+ p_lcb->ch_state);
/* if in correct state */
if (p_lcb->ch_state == AVCT_CH_CFG) {
p_lcb->ch_state = AVCT_CH_OPEN;
avct_lcb_event(p_lcb, AVCT_LCB_LL_OPEN_EVT, NULL);
}
- LOG_VERBOSE("ch_state cfc: %d ", p_lcb->ch_state);
+ log::verbose("ch_state cfc: {} ", p_lcb->ch_state);
}
}
@@ -283,8 +286,8 @@
/* look up lcb for this channel */
p_lcb = avct_lcb_by_lcid(lcid);
if (p_lcb != NULL) {
- LOG_VERBOSE("avct_l2c_config_ind_cback: 0x%x, ch_state: %d", lcid,
- p_lcb->ch_state);
+ log::verbose("avct_l2c_config_ind_cback: 0x{:x}, ch_state: {}", lcid,
+ p_lcb->ch_state);
/* store the mtu in tbl */
if (p_cfg->mtu_present) {
p_lcb->peer_mtu = p_cfg->mtu;
@@ -311,12 +314,12 @@
/* look up lcb for this channel */
p_lcb = avct_lcb_by_lcid(lcid);
if (p_lcb != NULL) {
- LOG_VERBOSE("avct_l2c_disconnect_ind_cback: 0x%x, ch_state: %d", lcid,
- p_lcb->ch_state);
+ log::verbose("avct_l2c_disconnect_ind_cback: 0x{:x}, ch_state: {}", lcid,
+ p_lcb->ch_state);
tAVCT_LCB_EVT avct_lcb_evt;
avct_lcb_evt.result = result;
avct_lcb_event(p_lcb, AVCT_LCB_LL_CLOSE_EVT, &avct_lcb_evt);
- LOG_VERBOSE("ch_state di: %d ", p_lcb->ch_state);
+ log::verbose("ch_state di: {} ", p_lcb->ch_state);
}
}
@@ -329,8 +332,8 @@
/* look up lcb for this channel */
p_lcb = avct_lcb_by_lcid(lcid);
if (p_lcb != NULL) {
- LOG_VERBOSE("avct_l2c_disconnect_cfm_cback: 0x%x, ch_state: %d, res: %d",
- lcid, p_lcb->ch_state, result);
+ log::verbose("avct_l2c_disconnect_cfm_cback: 0x{:x}, ch_state: {}, res: {}",
+ lcid, p_lcb->ch_state, result);
/* result value may be previously stored */
res = (p_lcb->ch_result != 0) ? p_lcb->ch_result : result;
p_lcb->ch_result = 0;
@@ -338,7 +341,7 @@
tAVCT_LCB_EVT avct_lcb_evt;
avct_lcb_evt.result = res;
avct_lcb_event(p_lcb, AVCT_LCB_LL_CLOSE_EVT, &avct_lcb_evt);
- LOG_VERBOSE("ch_state dc: %d ", p_lcb->ch_state);
+ log::verbose("ch_state dc: {} ", p_lcb->ch_state);
}
}
@@ -355,7 +358,7 @@
void avct_l2c_congestion_ind_cback(uint16_t lcid, bool is_congested) {
tAVCT_LCB* p_lcb;
- LOG_VERBOSE("avct_l2c_congestion_ind_cback: 0x%x", lcid);
+ log::verbose("avct_l2c_congestion_ind_cback: 0x{:x}", lcid);
/* look up lcb for this channel */
p_lcb = avct_lcb_by_lcid(lcid);
if (p_lcb != NULL) {
@@ -378,14 +381,14 @@
void avct_l2c_data_ind_cback(uint16_t lcid, BT_HDR* p_buf) {
tAVCT_LCB* p_lcb;
- LOG_VERBOSE("avct_l2c_data_ind_cback: 0x%x", lcid);
+ log::verbose("avct_l2c_data_ind_cback: 0x{:x}", lcid);
/* look up lcb for this channel */
p_lcb = avct_lcb_by_lcid(lcid);
if (p_lcb != NULL) {
avct_lcb_event(p_lcb, AVCT_LCB_LL_MSG_EVT, (tAVCT_LCB_EVT*)&p_buf);
} else /* prevent buffer leak */
{
- LOG_WARN("ERROR -> avct_l2c_data_ind_cback drop buffer");
+ log::warn("ERROR -> avct_l2c_data_ind_cback drop buffer");
osi_free(p_buf);
}
}
diff --git a/system/stack/avct/avct_l2c_br.cc b/system/stack/avct/avct_l2c_br.cc
index d52b06a..86bb97f 100644
--- a/system/stack/avct/avct_l2c_br.cc
+++ b/system/stack/avct/avct_l2c_br.cc
@@ -26,19 +26,20 @@
#define LOG_TAG "avctp"
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include "avct_api.h"
#include "avct_int.h"
#include "internal_include/bt_target.h"
#include "l2c_api.h"
#include "l2cdefs.h"
-#include "os/log.h"
#include "osi/include/allocator.h"
#include "osi/include/osi.h"
#include "stack/include/bt_hdr.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
/* callback function declarations */
void avct_l2c_br_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid,
uint16_t psm, uint8_t id);
@@ -86,8 +87,8 @@
for (i = 0; i < AVCT_NUM_CONN; i++, p_ccb++) {
if (p_ccb->allocated && (p_ccb->p_lcb == p_lcb)) {
- LOG_VERBOSE("Is bcb associated ccb control passive :0x%x",
- p_ccb->cc.control);
+ log::verbose("Is bcb associated ccb control passive :0x{:x}",
+ p_ccb->cc.control);
if (p_ccb->cc.control & AVCT_PASSIVE) {
is_passive = true;
break;
@@ -135,7 +136,7 @@
/* add channel ID to conflict ID */
p_bcb->conflict_lcid = p_bcb->ch_lcid;
result = L2CAP_CONN_OK;
- LOG_VERBOSE("Detected conflict_lcid:0x%x", p_bcb->conflict_lcid);
+ log::verbose("Detected conflict_lcid:0x{:x}", p_bcb->conflict_lcid);
}
}
}
@@ -146,7 +147,7 @@
/* If we reject the connection, send DisconnectReq */
if (result != L2CAP_CONN_OK) {
- LOG_VERBOSE("Connection rejected to lcid:0x%x", lcid);
+ log::verbose("Connection rejected to lcid:0x{:x}", lcid);
L2CA_DisconnectReq(lcid);
}
@@ -165,7 +166,7 @@
if (p_bcb == nullptr) return;
if (p_bcb->ch_state == AVCT_CH_CONN && p_bcb->conflict_lcid == lcid) {
- LOG_VERBOSE("Reset conflict_lcid:0x%x", p_bcb->conflict_lcid);
+ log::verbose("Reset conflict_lcid:0x{:x}", p_bcb->conflict_lcid);
p_bcb->conflict_lcid = 0;
return;
}
@@ -204,14 +205,14 @@
}
/* else failure */
else {
- LOG_ERROR("Invoked with non OK status");
+ log::error("Invoked with non OK status");
}
} else if (p_bcb->conflict_lcid == lcid) {
/* we must be in AVCT_CH_CFG state for the ch_lcid channel */
if (result == L2CAP_CONN_OK) {
/* just in case the peer also accepts our connection - Send L2CAP
* disconnect req */
- LOG_VERBOSE("Disconnect conflict_lcid:0x%x", p_bcb->conflict_lcid);
+ log::verbose("Disconnect conflict_lcid:0x{:x}", p_bcb->conflict_lcid);
L2CA_DisconnectReq(lcid);
}
p_bcb->conflict_lcid = 0;
@@ -270,7 +271,7 @@
p_lcb->peer_mtu = max_mtu;
}
- LOG_VERBOSE("%s peer_mtu:%d use:%d", __func__, p_lcb->peer_mtu, max_mtu);
+ log::verbose("peer_mtu:{} use:{}", p_lcb->peer_mtu, max_mtu);
}
/*******************************************************************************
diff --git a/system/stack/avct/avct_lcb.cc b/system/stack/avct/avct_lcb.cc
index 6a3aebd..f7d4c58 100644
--- a/system/stack/avct/avct_lcb.cc
+++ b/system/stack/avct/avct_lcb.cc
@@ -25,7 +25,7 @@
#define LOG_TAG "avctp"
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include <string.h>
#include "avct_api.h"
@@ -37,6 +37,8 @@
#include "osi/include/osi.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
/*****************************************************************************
* state machine constants and types
****************************************************************************/
@@ -170,8 +172,8 @@
uint8_t action;
int i;
- LOG_VERBOSE("LCB lcb=%d event=%s state=%s", p_lcb->allocated,
- avct_lcb_evt_str[event], avct_lcb_st_str[p_lcb->state]);
+ log::verbose("LCB lcb={} event={} state={}", p_lcb->allocated,
+ avct_lcb_evt_str[event], avct_lcb_st_str[p_lcb->state]);
/* look up the state table for the current state */
state_table = avct_lcb_st_tbl[p_lcb->state];
@@ -209,8 +211,8 @@
uint8_t action;
int i;
- LOG_VERBOSE("BCB lcb=%d event=%s state=%s", p_bcb->allocated,
- avct_lcb_evt_str[event], avct_lcb_st_str[p_bcb->state]);
+ log::verbose("BCB lcb={} event={} state={}", p_bcb->allocated,
+ avct_lcb_evt_str[event], avct_lcb_st_str[p_bcb->state]);
/* look up the state table for the current state */
state_table = avct_lcb_st_tbl[p_bcb->state];
@@ -254,7 +256,7 @@
/* if no lcb found */
p_lcb = NULL;
- VLOG(1) << "No lcb for addr " << ADDRESS_TO_LOGGABLE_STR(bd_addr);
+ log::verbose("No lcb for addr {}", ADDRESS_TO_LOGGABLE_STR(bd_addr));
}
return p_lcb;
}
@@ -277,7 +279,7 @@
if (!p_lcb->allocated) {
p_lcb->allocated = (uint8_t)(i + 1);
p_lcb->peer_addr = bd_addr;
- LOG_VERBOSE("avct_lcb_alloc %d", p_lcb->allocated);
+ log::verbose("avct_lcb_alloc {}", p_lcb->allocated);
p_lcb->tx_q = fixed_queue_new(SIZE_MAX);
p_lcb->peer_mtu = L2CAP_LE_MIN_MTU;
break;
@@ -287,7 +289,7 @@
if (i == AVCT_NUM_LINKS) {
/* out of lcbs */
p_lcb = NULL;
- LOG_WARN("Out of lcbs");
+ log::warn("Out of lcbs");
}
return p_lcb;
}
@@ -303,21 +305,21 @@
*
******************************************************************************/
void avct_lcb_dealloc(tAVCT_LCB* p_lcb, UNUSED_ATTR tAVCT_LCB_EVT* p_data) {
- LOG_VERBOSE("%s allocated: %d", __func__, p_lcb->allocated);
+ log::verbose("allocated: {}", p_lcb->allocated);
// Check if the LCB is still referenced
tAVCT_CCB* p_ccb = &avct_cb.ccb[0];
for (size_t i = 0; i < AVCT_NUM_CONN; i++, p_ccb++) {
if (p_ccb->allocated && p_ccb->p_lcb == p_lcb) {
- LOG_VERBOSE("%s LCB in use; lcb index: %zu", __func__, i);
+ log::verbose("LCB in use; lcb index: {}", i);
return;
}
}
// If not, de-allocate now...
- LOG_VERBOSE("%s Freeing LCB", __func__);
+ log::verbose("Freeing LCB");
osi_free(p_lcb->p_rx_msg);
fixed_queue_free(p_lcb->tx_q, NULL);
memset(p_lcb, 0, sizeof(tAVCT_LCB));
@@ -347,7 +349,7 @@
if (i == AVCT_NUM_LINKS) {
/* out of lcbs */
p_lcb = NULL;
- LOG_WARN("No lcb for lcid %x", lcid);
+ log::warn("No lcb for lcid {:x}", lcid);
}
return p_lcb;
@@ -389,10 +391,11 @@
tAVCT_CCB* p_ccb = &avct_cb.ccb[0];
int i;
- LOG_WARN("avct_lcb_last_ccb");
+ log::warn("avct_lcb_last_ccb");
for (i = 0; i < AVCT_NUM_CONN; i++, p_ccb++) {
- LOG_WARN("%x: aloc:%d, lcb:0x%p/0x%p, ccb:0x%p/0x%p", i, p_ccb->allocated,
- p_ccb->p_lcb, p_lcb, p_ccb, p_ccb_last);
+ log::warn("{:x}: aloc:{}, lcb:0x{}/0x{}, ccb:0x{}/0x{}", i,
+ p_ccb->allocated, fmt::ptr(p_ccb->p_lcb), fmt::ptr(p_lcb),
+ fmt::ptr(p_ccb), fmt::ptr(p_ccb_last));
if (p_ccb->allocated && (p_ccb->p_lcb == p_lcb) && (p_ccb != p_ccb_last)) {
return false;
}
diff --git a/system/stack/avct/avct_lcb_act.cc b/system/stack/avct/avct_lcb_act.cc
index 36d641c..2aa38d5 100644
--- a/system/stack/avct/avct_lcb_act.cc
+++ b/system/stack/avct/avct_lcb_act.cc
@@ -22,6 +22,7 @@
*
******************************************************************************/
#include <android_bluetooth_sysprop.h>
+#include <bluetooth/log.h>
#include <string.h>
#include "avct_api.h"
@@ -29,13 +30,14 @@
#include "bta/include/bta_sec_api.h"
#include "device/include/device_iot_config.h"
#include "internal_include/bt_target.h"
-#include "os/log.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"
+using namespace bluetooth;
+
/* packet header length lookup table */
const uint8_t avct_lcb_pkt_type_len[] = {AVCT_HDR_LEN_SINGLE,
AVCT_HDR_LEN_START, AVCT_HDR_LEN_CONT,
@@ -71,13 +73,13 @@
if (p_buf->len < avct_lcb_pkt_type_len[pkt_type] ||
(sizeof(BT_HDR) + p_buf->offset + p_buf->len) > BT_DEFAULT_BUFFER_SIZE) {
osi_free(p_buf);
- LOG_WARN("Bad length during reassembly");
+ log::warn("Bad length during reassembly");
p_ret = NULL;
}
/* single packet */
else if (pkt_type == AVCT_PKT_TYPE_SINGLE) {
/* if reassembly in progress drop message and process new single */
- if (p_lcb->p_rx_msg != NULL) LOG_WARN("Got single during reassembly");
+ if (p_lcb->p_rx_msg != NULL) log::warn("Got single during reassembly");
osi_free_and_reset((void**)&p_lcb->p_rx_msg);
@@ -86,7 +88,7 @@
/* start packet */
else if (pkt_type == AVCT_PKT_TYPE_START) {
/* if reassembly in progress drop message and process new start */
- if (p_lcb->p_rx_msg != NULL) LOG_WARN("Got start during reassembly");
+ if (p_lcb->p_rx_msg != NULL) log::warn("Got start during reassembly");
osi_free_and_reset((void**)&p_lcb->p_rx_msg);
@@ -125,7 +127,7 @@
/* if no reassembly in progress drop message */
if (p_lcb->p_rx_msg == NULL) {
osi_free(p_buf);
- LOG_WARN("Pkt type=%d out of order", pkt_type);
+ log::warn("Pkt type={} out of order", pkt_type);
p_ret = NULL;
} else {
/* get size of buffer holding assembled message */
@@ -142,7 +144,7 @@
/* verify length */
if ((p_lcb->p_rx_msg->offset + p_buf->len) > buf_len) {
/* won't fit; free everything */
- LOG_WARN("%s: Fragmented message too big!", __func__);
+ log::warn("Fragmented message too big!");
osi_free_and_reset((void**)&p_lcb->p_rx_msg);
osi_free(p_buf);
p_ret = NULL;
@@ -230,7 +232,7 @@
for (i = 0; i < AVCT_NUM_CONN; i++, p_ccb++) {
if (p_ccb->allocated && (p_ccb->p_lcb == p_lcb) &&
p_ccb->cc.role == AVCT_INT) {
- LOG_VERBOSE("%s, find int handle %d", __func__, i);
+ log::verbose("find int handle {}", i);
is_originater = true;
}
}
@@ -240,9 +242,9 @@
/* if ccb allocated and */
/** M: to avoid avctp collision, make sure the collision can be checked @{
*/
- LOG_VERBOSE("%s, %d ccb to lcb, alloc %d, lcb %p, role %d, pid 0x%x",
- __func__, i, p_ccb->allocated, p_ccb->p_lcb, p_ccb->cc.role,
- p_ccb->cc.pid);
+ log::verbose("{} ccb to lcb, alloc {}, lcb {}, role {}, pid 0x{:x}", i,
+ p_ccb->allocated, fmt::ptr(p_ccb->p_lcb), p_ccb->cc.role,
+ p_ccb->cc.pid);
if (p_ccb->allocated && (p_ccb->p_lcb == p_lcb)) {
/* if bound to this lcb send connect confirm event */
if (p_ccb->cc.role == AVCT_INT) {
@@ -260,7 +262,7 @@
avct_lcb_has_pid(p_lcb, p_ccb->cc.pid)) {
/* bind ccb to lcb and send connect ind event */
if (is_originater) {
- LOG_ERROR("%s, int exist, unbind acp handle:%d", __func__, i);
+ log::error("int exist, unbind acp handle:{}", i);
p_ccb->p_lcb = NULL;
} else {
bind = true;
@@ -427,11 +429,11 @@
void avct_lcb_chk_disc(tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) {
avct_close_bcb(p_lcb, p_data);
if (avct_lcb_last_ccb(p_lcb, p_data->p_ccb)) {
- LOG_INFO("Closing last avct channel to device");
+ log::info("Closing last avct channel to device");
p_data->p_ccb->ch_close = true;
avct_lcb_event(p_lcb, AVCT_LCB_INT_CLOSE_EVT, p_data);
} else {
- LOG_INFO("Closing avct channel with active remaining channels");
+ log::info("Closing avct channel with active remaining channels");
avct_lcb_unbind_disc(p_lcb, p_data);
}
}
@@ -515,7 +517,7 @@
*
******************************************************************************/
void avct_lcb_discard_msg(UNUSED_ATTR tAVCT_LCB* p_lcb, tAVCT_LCB_EVT* p_data) {
- LOG_WARN("%s Dropping message", __func__);
+ log::warn("Dropping message");
osi_free_and_reset((void**)&p_data->ul_msg.p_buf);
}
@@ -613,7 +615,7 @@
pkt_type = AVCT_PKT_TYPE_END;
}
}
- LOG_VERBOSE("%s tx_q_count:%zu", __func__, fixed_queue_length(p_lcb->tx_q));
+ log::verbose("tx_q_count:{}", fixed_queue_length(p_lcb->tx_q));
return;
}
@@ -671,7 +673,7 @@
/* check for invalid cr_ipid */
if (cr_ipid == AVCT_CR_IPID_INVALID) {
- LOG_WARN("Invalid cr_ipid %d", cr_ipid);
+ log::warn("Invalid cr_ipid {}", cr_ipid);
osi_free_and_reset((void**)&p_data->p_buf);
return;
}
@@ -695,7 +697,7 @@
}
/* PID not found; drop message */
- LOG_WARN("No ccb for PID=%x", pid);
+ log::warn("No ccb for PID={:x}", pid);
osi_free_and_reset((void**)&p_data->p_buf);
/* if command send reject */
diff --git a/system/stack/avdt/avdt_ad.cc b/system/stack/avdt/avdt_ad.cc
index 22a6c50..378d6d4 100644
--- a/system/stack/avdt/avdt_ad.cc
+++ b/system/stack/avdt/avdt_ad.cc
@@ -22,7 +22,7 @@
*
******************************************************************************/
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include <string.h>
#include "avdt_api.h"
@@ -35,21 +35,21 @@
#include "stack/include/bt_hdr.h"
#include "stack/include/btm_sec_api_types.h"
+using namespace bluetooth;
+
AvdtpScb* AvdtpAdaptationLayer::LookupAvdtpScb(
const AvdtpTransportChannel& tc) {
if (tc.ccb_idx >= AVDT_NUM_LINKS) {
- LOG_ERROR("%s: AvdtpScb entry not found: invalid ccb_idx:%d", __func__,
- tc.ccb_idx);
+ log::error("AvdtpScb entry not found: invalid ccb_idx:{}", tc.ccb_idx);
return nullptr;
}
if (tc.tcid >= AVDT_NUM_RT_TBL) {
- LOG_ERROR("%s: AvdtpScb entry not found: invalid tcid:%d", __func__,
- tc.tcid);
+ log::error("AvdtpScb entry not found: invalid tcid:{}", tc.tcid);
return nullptr;
}
const AvdtpRoutingEntry& re = rt_tbl[tc.ccb_idx][tc.tcid];
- LOG_VERBOSE("%s: ccb_idx:%d tcid:%d scb_hdl:%d", __func__, tc.ccb_idx,
- tc.tcid, re.scb_hdl);
+ log::verbose("ccb_idx:{} tcid:{} scb_hdl:{}", tc.ccb_idx, tc.tcid,
+ re.scb_hdl);
return avdt_scb_by_hdl(re.scb_hdl);
}
@@ -74,7 +74,7 @@
// There are AVDT_CHAN_NUM_TYPES channel types per SEP. Here we compute
// the type index (TCID) from the SEP index and the type itself.
uint8_t tcid = (scb_idx * (AVDT_CHAN_NUM_TYPES - 1)) + type;
- LOG_VERBOSE("%s: type:%d, tcid: %d", __func__, type, tcid);
+ log::verbose("type:{}, tcid: {}", type, tcid);
return tcid;
}
@@ -101,7 +101,7 @@
*/
type = ((tcid + AVDT_CHAN_NUM_TYPES - 2) % (AVDT_CHAN_NUM_TYPES - 1)) + 1;
}
- LOG_VERBOSE("tcid: %d, type: %d", tcid, type);
+ log::verbose("tcid: {}, type: {}", tcid, type);
return type;
}
@@ -275,7 +275,7 @@
*
******************************************************************************/
uint8_t avdt_ad_tc_tbl_to_idx(AvdtpTransportChannel* p_tbl) {
- LOG_VERBOSE("avdt_ad_tc_tbl_to_idx: %ld", (long)(p_tbl - avdtp_cb.ad.tc_tbl));
+ log::verbose("avdt_ad_tc_tbl_to_idx: {}", (long)(p_tbl - avdtp_cb.ad.tc_tbl));
/* use array arithmetic to determine index */
return (uint8_t)(p_tbl - avdtp_cb.ad.tc_tbl);
}
@@ -305,8 +305,7 @@
p_tbl->cfg_flags = 0;
p_tbl->peer_mtu = L2CAP_DEFAULT_MTU;
- LOG_VERBOSE("%s: tcid: %d, old: %d", __func__, p_tbl->tcid,
- close.old_tc_state);
+ log::verbose("tcid: {}, old: {}", p_tbl->tcid, close.old_tc_state);
/* if signaling channel, notify ccb that channel open */
if (p_tbl->tcid == 0) {
p_ccb = avdt_ccb_by_idx(p_tbl->ccb_idx);
@@ -317,8 +316,8 @@
/* look up scb in stream routing table by ccb, tcid */
p_scb = avdtp_cb.ad.LookupAvdtpScb(*p_tbl);
if (p_scb == nullptr) {
- LOG_ERROR("%s: Cannot find AvdtScb entry: ccb_idx:%d tcid:%d", __func__,
- p_tbl->ccb_idx, p_tbl->tcid);
+ log::error("Cannot find AvdtScb entry: ccb_idx:{} tcid:{}", p_tbl->ccb_idx,
+ p_tbl->tcid);
return;
}
close.tcid = p_tbl->tcid;
@@ -346,9 +345,9 @@
tAVDT_OPEN open;
tAVDT_EVT_HDR evt;
- LOG_VERBOSE("%s: p_tbl:%p state:%d ccb_idx:%d tcid:%d scb_hdl:%d", __func__,
- p_tbl, p_tbl->state, p_tbl->ccb_idx, p_tbl->tcid,
- avdtp_cb.ad.rt_tbl[p_tbl->ccb_idx][p_tbl->tcid].scb_hdl);
+ log::verbose("p_tbl:{} state:{} ccb_idx:{} tcid:{} scb_hdl:{}",
+ fmt::ptr(p_tbl), p_tbl->state, p_tbl->ccb_idx, p_tbl->tcid,
+ avdtp_cb.ad.rt_tbl[p_tbl->ccb_idx][p_tbl->tcid].scb_hdl);
p_tbl->state = AVDT_AD_ST_OPEN;
@@ -374,8 +373,8 @@
/* look up scb in stream routing table by ccb, tcid */
p_scb = avdtp_cb.ad.LookupAvdtpScb(*p_tbl);
if (p_scb == nullptr) {
- LOG_ERROR("%s: Cannot find AvdtScb entry: ccb_idx:%d tcid:%d", __func__,
- p_tbl->ccb_idx, p_tbl->tcid);
+ log::error("Cannot find AvdtScb entry: ccb_idx:{} tcid:{}", p_tbl->ccb_idx,
+ p_tbl->tcid);
return;
}
/* put lcid in event data */
@@ -417,8 +416,8 @@
/* look up scb in stream routing table by ccb, tcid */
p_scb = avdtp_cb.ad.LookupAvdtpScb(*p_tbl);
if (p_scb == nullptr) {
- LOG_ERROR("%s: Cannot find AvdtScb entry: ccb_idx:%d tcid:%d", __func__,
- p_tbl->ccb_idx, p_tbl->tcid);
+ log::error("Cannot find AvdtScb entry: ccb_idx:{} tcid:{}", p_tbl->ccb_idx,
+ p_tbl->tcid);
return;
}
tAVDT_SCB_EVT avdt_scb_evt;
@@ -454,10 +453,10 @@
/* if media or other channel, send event to scb */
p_scb = avdtp_cb.ad.LookupAvdtpScb(*p_tbl);
if (p_scb == nullptr) {
- LOG_ERROR("%s: Cannot find AvdtScb entry: ccb_idx:%d tcid:%d", __func__,
- p_tbl->ccb_idx, p_tbl->tcid);
+ log::error("Cannot find AvdtScb entry: ccb_idx:{} tcid:{}", p_tbl->ccb_idx,
+ p_tbl->tcid);
osi_free(p_buf);
- LOG_ERROR("%s: buffer freed", __func__);
+ log::error("buffer freed");
return;
}
avdt_scb_event(p_scb, AVDT_SCB_TC_DATA_EVT, (tAVDT_SCB_EVT*)&p_buf);
@@ -513,13 +512,13 @@
p_tbl = avdt_ad_tc_tbl_alloc(p_ccb);
if (p_tbl == NULL) {
- LOG_ERROR("avdt_ad_open_req: Cannot allocate p_tbl");
+ log::error("avdt_ad_open_req: Cannot allocate p_tbl");
return;
}
p_tbl->tcid = avdt_ad_type_to_tcid(type, p_scb);
- LOG_VERBOSE("avdt_ad_open_req: type: %d, role: %d, tcid:%d", type, role,
- p_tbl->tcid);
+ log::verbose("avdt_ad_open_req: type: {}, role: {}, tcid:{}", type, role,
+ p_tbl->tcid);
if (type == AVDT_CHAN_SIG) {
/* if signaling, get mtu from registration control block */
@@ -531,8 +530,8 @@
/* also set scb_hdl in rt_tbl */
avdtp_cb.ad.rt_tbl[avdt_ccb_to_idx(p_ccb)][p_tbl->tcid].scb_hdl =
avdt_scb_to_hdl(p_scb);
- LOG_VERBOSE("avdtp_cb.ad.rt_tbl[%d][%d].scb_hdl = %d",
- avdt_ccb_to_idx(p_ccb), p_tbl->tcid, avdt_scb_to_hdl(p_scb));
+ log::verbose("avdtp_cb.ad.rt_tbl[{}][{}].scb_hdl = {}",
+ avdt_ccb_to_idx(p_ccb), p_tbl->tcid, avdt_scb_to_hdl(p_scb));
}
/* if we're acceptor, we're done; just sit back and listen */
@@ -549,12 +548,12 @@
if (lcid != 0) {
/* if connect req ok, store tcid in lcid table */
avdtp_cb.ad.lcid_tbl[lcid] = avdt_ad_tc_tbl_to_idx(p_tbl);
- LOG_VERBOSE("avdtp_cb.ad.lcid_tbl[%d] = %d", (lcid),
- avdt_ad_tc_tbl_to_idx(p_tbl));
+ log::verbose("avdtp_cb.ad.lcid_tbl[{}] = {}", (lcid),
+ avdt_ad_tc_tbl_to_idx(p_tbl));
avdtp_cb.ad.rt_tbl[avdt_ccb_to_idx(p_ccb)][p_tbl->tcid].lcid = lcid;
- LOG_VERBOSE("avdtp_cb.ad.rt_tbl[%d][%d].lcid = 0x%x",
- avdt_ccb_to_idx(p_ccb), p_tbl->tcid, lcid);
+ log::verbose("avdtp_cb.ad.rt_tbl[{}][{}].lcid = 0x{:x}",
+ avdt_ccb_to_idx(p_ccb), p_tbl->tcid, lcid);
} else {
/* if connect req failed, call avdt_ad_tc_close_ind() */
avdt_ad_tc_close_ind(p_tbl);
@@ -579,7 +578,7 @@
AvdtpTransportChannel* p_tbl;
p_tbl = avdt_ad_tc_tbl_by_type(type, p_ccb, p_scb);
- LOG_VERBOSE("avdt_ad_close_req state: %d", p_tbl->state);
+ log::verbose("avdt_ad_close_req state: {}", p_tbl->state);
switch (p_tbl->state) {
case AVDT_AD_ST_UNUSED:
diff --git a/system/stack/avdt/avdt_api.cc b/system/stack/avdt/avdt_api.cc
index 60518de..923641e 100644
--- a/system/stack/avdt/avdt_api.cc
+++ b/system/stack/avdt/avdt_api.cc
@@ -25,6 +25,7 @@
#include "avdt_api.h"
+#include <bluetooth/log.h>
#include <string.h>
#include "avdt_int.h"
@@ -37,6 +38,8 @@
#include "stack/include/bt_hdr.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
/* Control block for AVDTP */
AvdtpCb avdtp_cb;
@@ -126,14 +129,13 @@
}
void AVDT_AbortReq(uint8_t handle) {
- LOG_WARN("%s: avdt_handle=%d", __func__, handle);
+ log::warn("avdt_handle={}", handle);
AvdtpScb* p_scb = avdt_scb_by_hdl(handle);
if (p_scb != NULL) {
avdt_scb_event(p_scb, AVDT_SCB_API_ABORT_REQ_EVT, NULL);
} else {
- LOG_ERROR("%s Improper avdp_handle=%d, can not abort the stream", __func__,
- handle);
+ log::error("Improper avdp_handle={}, can not abort the stream", handle);
}
}
@@ -160,21 +162,23 @@
if (((avdtp_stream_config.cfg.psc_mask & (~AVDT_PSC)) != 0) ||
(avdtp_stream_config.p_avdt_ctrl_cback == NULL)) {
result = AVDT_BAD_PARAMS;
- LOG_ERROR("Invalid AVDT stream endpoint parameters peer_id=%d scb_index=%d",
- peer_id, avdtp_stream_config.scb_index);
+ 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 {
p_scb = avdt_scb_alloc(peer_id, avdtp_stream_config);
if (p_scb == NULL) {
- LOG_ERROR("Unable to create AVDT stream endpoint peer_id=%d scb_index=%d",
- peer_id, avdtp_stream_config.scb_index);
+ log::error(
+ "Unable to create AVDT stream endpoint peer_id={} scb_index={}",
+ peer_id, avdtp_stream_config.scb_index);
result = AVDT_NO_RESOURCES;
} else {
*p_handle = avdt_scb_to_hdl(p_scb);
- LOG_DEBUG("Created stream endpoint peer_id=%d handle=%hhu", peer_id,
- *p_handle);
+ log::debug("Created stream endpoint peer_id={} handle={}", peer_id,
+ *p_handle);
}
}
return static_cast<uint16_t>(result);
@@ -198,7 +202,7 @@
uint16_t result = AVDT_SUCCESS;
AvdtpScb* p_scb;
- LOG_VERBOSE("%s: avdt_handle=%d", __func__, handle);
+ log::verbose("avdt_handle={}", handle);
/* look up scb */
p_scb = avdt_scb_by_hdl(handle);
@@ -210,7 +214,7 @@
}
if (result != AVDT_SUCCESS) {
- LOG_ERROR("%s: result=%d avdt_handle=%d", __func__, result, handle);
+ log::error("result={} avdt_handle={}", result, handle);
}
return result;
@@ -249,7 +253,7 @@
uint16_t result = AVDT_SUCCESS;
tAVDT_CCB_EVT evt;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
/* find channel control block for this bd addr; if none, allocate one */
p_ccb = avdt_ccb_by_bd(bd_addr);
@@ -276,8 +280,8 @@
}
if (result != AVDT_SUCCESS) {
- LOG_ERROR("%s: result=%d address=%s", __func__, result,
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::error("result={} address={}", result,
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
}
return result;
}
@@ -297,12 +301,12 @@
AvdtpCcb* p_ccb = NULL;
uint16_t result = AVDT_SUCCESS;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
/* verify SEID */
if ((p_evt->single.seid < AVDT_SEID_MIN) ||
(p_evt->single.seid > AVDT_SEID_MAX)) {
- LOG_ERROR("seid: %d", p_evt->single.seid);
+ log::error("seid: {}", p_evt->single.seid);
result = AVDT_BAD_PARAMS;
}
/* find channel control block for this bd addr; if none, allocate one */
@@ -329,8 +333,8 @@
}
if (result != AVDT_SUCCESS) {
- LOG_ERROR("%s: result=%d address=%s", __func__, result,
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::error("result={} address={}", result,
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
}
return result;
}
@@ -365,7 +369,7 @@
tAVDT_CCB_API_GETCAP getcap;
uint16_t result = AVDT_SUCCESS;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
getcap.single.seid = seid;
if (get_all_cap) {
@@ -378,8 +382,8 @@
result = avdt_get_cap_req(bd_addr, channel_index, &getcap);
if (result != AVDT_SUCCESS) {
- LOG_ERROR("%s: result=%d address=%s", __func__, result,
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::error("result={} address={}", result,
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
}
return result;
}
@@ -400,8 +404,7 @@
uint16_t result = AVDT_SUCCESS;
tAVDT_SCB_EVT evt;
- LOG_VERBOSE("%s: avdt_handle=%d seid=%d delay=%d", __func__, handle, seid,
- delay);
+ log::verbose("avdt_handle={} seid={} delay={}", handle, seid, delay);
/* map handle to scb */
p_scb = avdt_scb_by_hdl(handle);
@@ -416,8 +419,7 @@
}
if (result != AVDT_SUCCESS) {
- LOG_ERROR("%s: result=%d avdt_handle=%d seid=%d", __func__, result, handle,
- seid);
+ log::error("result={} avdt_handle={} seid={}", result, handle, seid);
}
return result;
}
@@ -444,8 +446,8 @@
uint16_t result = AVDT_SUCCESS;
tAVDT_SCB_EVT evt;
- LOG_VERBOSE("%s: address=%s avdt_handle=%d seid=%d", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), handle, seid);
+ log::verbose("address={} avdt_handle={} seid={}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr), handle, seid);
/* verify SEID */
if ((seid < AVDT_SEID_MIN) || (seid > AVDT_SEID_MAX)) {
@@ -472,8 +474,7 @@
/* send event to scb */
if (result == AVDT_SUCCESS) {
- LOG_VERBOSE("%s: codec: %s", __func__,
- A2DP_CodecInfoString(p_cfg->codec_info).c_str());
+ log::verbose("codec: {}", A2DP_CodecInfoString(p_cfg->codec_info).c_str());
evt.msg.config_cmd.hdr.seid = seid;
evt.msg.config_cmd.hdr.ccb_idx = avdt_ccb_to_idx(p_ccb);
@@ -481,8 +482,8 @@
evt.msg.config_cmd.p_cfg = p_cfg;
avdt_scb_event(p_scb, AVDT_SCB_API_SETCONFIG_REQ_EVT, &evt);
} else {
- LOG_ERROR("%s: result=%d address=%s avdt_handle=%d", __func__, result,
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), handle);
+ log::error("result={} address={} avdt_handle={}", result,
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr), handle);
}
return result;
@@ -507,8 +508,8 @@
uint16_t result = AVDT_SUCCESS;
uint8_t event_code;
- LOG_VERBOSE("%s: avdt_handle=%d label=%d error_code=0x%x category=%d",
- __func__, handle, label, error_code, category);
+ log::verbose("avdt_handle={} label={} error_code=0x{:x} category={}", handle,
+ label, error_code, category);
/* map handle to scb */
p_scb = avdt_scb_by_hdl(handle);
@@ -535,7 +536,7 @@
}
if (result != AVDT_SUCCESS) {
- LOG_ERROR("%s: result=%d avdt_handle=%d", __func__, result, handle);
+ log::error("result={} avdt_handle={}", result, handle);
}
return result;
}
@@ -561,7 +562,7 @@
uint16_t result = AVDT_SUCCESS;
int i;
- LOG_VERBOSE("%s: num_handles=%d", __func__, num_handles);
+ log::verbose("num_handles={}", num_handles);
if ((num_handles == 0) || (num_handles > AVDT_NUM_SEPS)) {
result = AVDT_BAD_PARAMS;
@@ -589,11 +590,10 @@
if (result != AVDT_SUCCESS) {
if ((num_handles == 0) || (num_handles > AVDT_NUM_SEPS)) {
- LOG_ERROR("%s: result=%d num_handles=%d invalid", __func__, result,
- num_handles);
+ log::error("result={} num_handles={} invalid", result, num_handles);
} else {
- LOG_ERROR("%s: result=%d avdt_handle=%d", __func__, result,
- (i < num_handles ? p_handles[i] : p_handles[num_handles - 1]));
+ log::error("result={} avdt_handle={}", result,
+ (i < num_handles ? p_handles[i] : p_handles[num_handles - 1]));
}
}
return result;
@@ -620,7 +620,7 @@
uint16_t result = AVDT_SUCCESS;
int i;
- LOG_VERBOSE("%s: num_handles=%d", __func__, num_handles);
+ log::verbose("num_handles={}", num_handles);
if ((num_handles == 0) || (num_handles > AVDT_NUM_SEPS)) {
result = AVDT_BAD_PARAMS;
@@ -648,11 +648,10 @@
if (result != AVDT_SUCCESS) {
if ((num_handles == 0) || (num_handles > AVDT_NUM_SEPS)) {
- LOG_ERROR("%s: result=%d num_handles=%d invalid", __func__, result,
- num_handles);
+ log::error("result={} num_handles={} invalid", result, num_handles);
} else {
- LOG_ERROR("%s: result=%d avdt_handle=%d", __func__, result,
- (i < num_handles ? p_handles[i] : p_handles[num_handles - 1]));
+ log::error("result={} avdt_handle={}", result,
+ (i < num_handles ? p_handles[i] : p_handles[num_handles - 1]));
}
}
return result;
@@ -676,7 +675,7 @@
AvdtpScb* p_scb;
uint16_t result = AVDT_SUCCESS;
- LOG_VERBOSE("%s: avdt_handle=%d", __func__, handle);
+ log::verbose("avdt_handle={}", handle);
/* map handle to scb */
p_scb = avdt_scb_by_hdl(handle);
@@ -689,7 +688,7 @@
}
if (result != AVDT_SUCCESS) {
- LOG_ERROR("%s: result=%d avdt_handle=%d", __func__, result, handle);
+ log::error("result={} avdt_handle={}", result, handle);
}
return result;
}
@@ -716,7 +715,7 @@
uint16_t result = AVDT_SUCCESS;
tAVDT_SCB_EVT evt;
- LOG_VERBOSE("%s: avdt_handle=%d", __func__, handle);
+ log::verbose("avdt_handle={}", handle);
/* map handle to scb */
p_scb = avdt_scb_by_hdl(handle);
@@ -732,7 +731,7 @@
}
if (result != AVDT_SUCCESS) {
- LOG_ERROR("%s: result=%d avdt_handle=%d", __func__, result, handle);
+ log::error("result={} avdt_handle={}", result, handle);
}
return result;
}
@@ -756,7 +755,7 @@
uint16_t result = AVDT_SUCCESS;
tAVDT_SCB_EVT evt;
- LOG_VERBOSE("%s: avdt_handle=%d len=%d", __func__, handle, len);
+ log::verbose("avdt_handle={} len={}", handle, len);
/* map handle to scb */
p_scb = avdt_scb_by_hdl(handle);
@@ -771,7 +770,7 @@
}
if (result != AVDT_SUCCESS) {
- LOG_ERROR("%s: result=%d avdt_handle=%d", __func__, result, handle);
+ log::error("result={} avdt_handle={}", result, handle);
}
return result;
}
@@ -796,8 +795,8 @@
uint16_t result = AVDT_SUCCESS;
tAVDT_SCB_EVT evt;
- LOG_VERBOSE("%s: avdt_handle=%d label=%d error_code=0x%x len=%d", __func__,
- handle, label, error_code, len);
+ log::verbose("avdt_handle={} label={} error_code=0x{:x} len={}", handle,
+ label, error_code, len);
/* map handle to scb */
p_scb = avdt_scb_by_hdl(handle);
@@ -814,7 +813,7 @@
}
if (result != AVDT_SUCCESS) {
- LOG_ERROR("%s: result=%d avdt_handle=%d", __func__, result, handle);
+ log::error("result={} avdt_handle={}", result, handle);
}
return result;
}
@@ -862,8 +861,8 @@
tAVDT_SCB_EVT evt;
uint16_t result = AVDT_SUCCESS;
- LOG_VERBOSE("%s: avdt_handle=%d timestamp=%d m_pt=0x%x opt=0x%x", __func__,
- handle, time_stamp, m_pt, opt);
+ log::verbose("avdt_handle={} timestamp={} m_pt=0x{:x} opt=0x{:x}", handle,
+ time_stamp, m_pt, opt);
/* map handle to scb */
p_scb = avdt_scb_by_hdl(handle);
@@ -877,7 +876,7 @@
avdt_scb_event(p_scb, AVDT_SCB_API_WRITE_REQ_EVT, &evt);
}
- LOG_VERBOSE("%s: result=%d avdt_handle=%d", __func__, result, handle);
+ log::verbose("result={} avdt_handle={}", result, handle);
return result;
}
@@ -902,8 +901,8 @@
uint16_t result = AVDT_SUCCESS;
tAVDT_CCB_EVT evt;
- LOG_WARN("%s: address=%s channel_index=%d", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), channel_index);
+ log::warn("address={} channel_index={}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ channel_index);
/* find channel control block for this bd addr; if none, allocate one */
p_ccb = avdt_ccb_by_bd(bd_addr);
@@ -914,7 +913,7 @@
result = AVDT_NO_RESOURCES;
}
} else if (!p_ccb->ll_opened) {
- LOG_WARN("AVDT_ConnectReq: CCB LL is in the middle of opening");
+ log::warn("AVDT_ConnectReq: CCB LL is in the middle of opening");
/* ccb was already allocated for the incoming signalling. */
result = AVDT_BUSY;
@@ -926,8 +925,7 @@
avdt_ccb_event(p_ccb, AVDT_CCB_API_CONNECT_REQ_EVT, &evt);
}
- LOG_WARN("%s: address=%s result=%d", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), result);
+ log::warn("address={} result={}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr), result);
return result;
}
@@ -953,12 +951,12 @@
/* find channel control block for this bd addr; if none, error */
p_ccb = avdt_ccb_by_bd(bd_addr);
if (p_ccb == NULL) {
- LOG_ERROR("Unable to find AVDT stream endpoint peer:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::error("Unable to find AVDT stream endpoint peer:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
result = AVDT_BAD_PARAMS;
} else {
- LOG_DEBUG("Sending disconnect request to ccb peer:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::debug("Sending disconnect request to ccb peer:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
evt.disconnect.p_cback = p_cback;
avdt_ccb_event(p_ccb, AVDT_CCB_API_DISCONNECT_REQ_EVT, &evt);
}
diff --git a/system/stack/avdt/avdt_ccb.cc b/system/stack/avdt/avdt_ccb.cc
index 2083b38..ca4d1c0 100644
--- a/system/stack/avdt/avdt_ccb.cc
+++ b/system/stack/avdt/avdt_ccb.cc
@@ -23,7 +23,7 @@
*
******************************************************************************/
-#include <base/logging.h> // VLOG
+#include <bluetooth/log.h>
#include <string.h>
#include "avdt_int.h"
@@ -31,6 +31,8 @@
#include "osi/include/osi.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
/*****************************************************************************
* state machine constants and types
****************************************************************************/
@@ -367,9 +369,9 @@
int i;
#if (AVDT_DEBUG == TRUE)
- LOG_VERBOSE("%s: CCB ccb=%d event=%s state=%s p_ccb=%p", __func__,
- avdt_ccb_to_idx(p_ccb), avdt_ccb_evt_str[event],
- avdt_ccb_st_str[p_ccb->state], p_ccb);
+ log::verbose("CCB ccb={} event={} state={} p_ccb={}", avdt_ccb_to_idx(p_ccb),
+ avdt_ccb_evt_str[event], avdt_ccb_st_str[p_ccb->state],
+ fmt::ptr(p_ccb));
#endif
/* look up the state table for the current state */
@@ -383,8 +385,8 @@
/* execute action functions */
for (i = 0; i < AVDT_CCB_ACTIONS; i++) {
action = state_table[event][i];
- LOG_VERBOSE("%s: event=%s state=%s action=%d", __func__,
- avdt_ccb_evt_str[event], avdt_ccb_st_str[p_ccb->state], action);
+ log::verbose("event={} state={} action={}", avdt_ccb_evt_str[event],
+ avdt_ccb_st_str[p_ccb->state], action);
if (action != AVDT_CCB_IGNORE) {
(*avdtp_cb.p_ccb_act[action])(p_ccb, p_data);
} else {
@@ -418,7 +420,7 @@
/* if no ccb found */
p_ccb = NULL;
- VLOG(1) << "No ccb for addr " << bd_addr;
+ log::verbose("No ccb for addr {}", ADDRESS_TO_LOGGABLE_STR(bd_addr));
}
return p_ccb;
}
@@ -439,13 +441,13 @@
for (int i = 0; i < AVDT_NUM_LINKS; i++, p_ccb++) {
if (!p_ccb->allocated) {
p_ccb->Allocate(bd_addr);
- LOG_VERBOSE("%s: allocated (index %d) for peer %s", __func__, i,
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::verbose("allocated (index {}) for peer {}", i,
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return p_ccb;
}
}
- LOG_WARN("%s: out of AvdtpCcb entries", __func__);
+ log::warn("out of AvdtpCcb entries");
return nullptr;
}
@@ -453,19 +455,20 @@
uint8_t channel_index) {
// Allocate the entry for the specified channel index
if (channel_index >= AVDT_NUM_LINKS) {
- LOG_ERROR("%s: peer %s invalid channel index %d (max %d)", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), channel_index, AVDT_NUM_LINKS);
+ log::error("peer {} invalid channel index {} (max {})",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr), channel_index,
+ AVDT_NUM_LINKS);
return nullptr;
}
AvdtpCcb* p_ccb = &avdtp_cb.ccb[channel_index];
if (p_ccb->allocated) {
- LOG_ERROR("%s: peer %s channel index %d already allocated", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), channel_index);
+ log::error("peer {} channel index {} already allocated",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr), channel_index);
return nullptr;
}
p_ccb->Allocate(bd_addr);
- LOG_VERBOSE("%s: allocated (index %d) peer=%s p_ccb=%p", __func__,
- channel_index, ADDRESS_TO_LOGGABLE_CSTR(p_ccb->peer_addr), p_ccb);
+ log::verbose("allocated (index {}) peer={} p_ccb={}", channel_index,
+ ADDRESS_TO_LOGGABLE_CSTR(p_ccb->peer_addr), fmt::ptr(p_ccb));
return p_ccb;
}
@@ -491,9 +494,9 @@
*
******************************************************************************/
void avdt_ccb_dealloc(AvdtpCcb* p_ccb, UNUSED_ATTR tAVDT_CCB_EVT* p_data) {
- LOG_VERBOSE("%s: deallocated (index %d) peer=%s p_ccb=%p", __func__,
- avdt_ccb_to_idx(p_ccb),
- ADDRESS_TO_LOGGABLE_CSTR(p_ccb->peer_addr), p_ccb);
+ log::verbose("deallocated (index {}) peer={} p_ccb={}",
+ avdt_ccb_to_idx(p_ccb),
+ ADDRESS_TO_LOGGABLE_CSTR(p_ccb->peer_addr), fmt::ptr(p_ccb));
p_ccb->ResetCcb();
}
@@ -530,7 +533,7 @@
p_ccb = &avdtp_cb.ccb[idx];
} else {
p_ccb = NULL;
- LOG_WARN("No ccb for idx %d", idx);
+ log::warn("No ccb for idx {}", idx);
}
return p_ccb;
}
diff --git a/system/stack/avdt/avdt_ccb_act.cc b/system/stack/avdt/avdt_ccb_act.cc
index 4cc1d16..85f25eb 100644
--- a/system/stack/avdt/avdt_ccb_act.cc
+++ b/system/stack/avdt/avdt_ccb_act.cc
@@ -23,6 +23,7 @@
*
******************************************************************************/
+#include <bluetooth/log.h>
#include <string.h>
#include "avdt_api.h"
@@ -34,6 +35,8 @@
#include "stack/include/bt_hdr.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
/*******************************************************************************
*
* Function avdt_ccb_clear_ccb
@@ -143,7 +146,7 @@
tAVDT_SEP_INFO sep_info[AVDT_NUM_SEPS];
AvdtpScb* p_scb = &(p_ccb->scb[0]);
- LOG_VERBOSE("%s: p_ccb index=%d", __func__, avdt_ccb_to_idx(p_ccb));
+ log::verbose("p_ccb index={}", avdt_ccb_to_idx(p_ccb));
p_data->msg.discover_rsp.p_sep_info = sep_info;
p_data->msg.discover_rsp.num_seps = 0;
@@ -491,7 +494,7 @@
tAVDT_MSG avdt_msg;
uint8_t seid_list[AVDT_NUM_SEPS];
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
/* make copy of our seid list */
memcpy(seid_list, p_data->msg.multi.seid_list, p_data->msg.multi.num_seps);
@@ -501,7 +504,7 @@
avdt_scb_verify(p_ccb, AVDT_VERIFY_OPEN, p_data->msg.multi.seid_list,
p_data->msg.multi.num_seps, &avdt_msg.hdr.err_code);
if (avdt_msg.hdr.err_param == 0) {
- LOG_VERBOSE("%s: AVDT_SIG_START", __func__);
+ log::verbose("AVDT_SIG_START");
/* set peer seid list in messsage */
avdt_scb_peer_seid_list(&p_data->msg.multi);
@@ -513,7 +516,7 @@
for (i = 0; i < p_data->msg.multi.num_seps; i++) {
p_scb = avdt_scb_by_hdl(seid_list[i]);
if (p_scb != NULL) {
- LOG_VERBOSE("%s: AVDT_SCB_MSG_START_REJ_EVT: i=%d", __func__, i);
+ log::verbose("AVDT_SCB_MSG_START_REJ_EVT: i={}", i);
tAVDT_SCB_EVT avdt_scb_evt;
avdt_scb_evt.msg.hdr = avdt_msg.hdr;
avdt_scb_event(p_scb, AVDT_SCB_MSG_START_REJ_EVT, &avdt_scb_evt);
@@ -958,8 +961,8 @@
******************************************************************************/
void avdt_ccb_set_disconn(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data) {
/*
- LOG_VERBOSE("avdt_ccb_set_disconn:conn:x%x, api:x%x",
- p_ccb->p_conn_cback, p_data->disconnect.p_cback);
+ log::verbose("avdt_ccb_set_disconn:conn:x{:x}, api:x{:x}",
+ p_ccb->p_conn_cback, p_data->disconnect.p_cback);
*/
/* save callback */
if (p_data->disconnect.p_cback)
@@ -998,8 +1001,7 @@
tAVDT_CTRL_CBACK* p_cback;
tAVDT_CTRL avdt_ctrl;
- LOG_VERBOSE("%s peer %s", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(p_ccb->peer_addr));
+ log::verbose("peer {}", ADDRESS_TO_LOGGABLE_CSTR(p_ccb->peer_addr));
/* clear any pending commands */
avdt_ccb_clear_cmds(p_ccb, NULL);
@@ -1034,9 +1036,9 @@
void avdt_ccb_ll_opened(AvdtpCcb* p_ccb, tAVDT_CCB_EVT* p_data) {
tAVDT_CTRL avdt_ctrl;
- LOG_VERBOSE("%s peer %s BtaAvScbIndex=%d p_ccb=%p", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(p_ccb->peer_addr),
- p_ccb->BtaAvScbIndex(), p_ccb);
+ log::verbose("peer {} BtaAvScbIndex={} p_ccb={}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_ccb->peer_addr),
+ p_ccb->BtaAvScbIndex(), fmt::ptr(p_ccb));
p_ccb->ll_opened = true;
if (!p_ccb->p_conn_cback) p_ccb->p_conn_cback = avdtp_cb.p_conn_cback;
diff --git a/system/stack/avdt/avdt_l2c.cc b/system/stack/avdt/avdt_l2c.cc
index 0ecbe07..06aadbf 100644
--- a/system/stack/avdt/avdt_l2c.cc
+++ b/system/stack/avdt/avdt_l2c.cc
@@ -22,7 +22,7 @@
*
******************************************************************************/
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include "avdt_int.h"
#include "bta/include/bta_av_api.h"
@@ -35,6 +35,8 @@
#include "stack/include/bt_hdr.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
/* callback function declarations */
void avdt_l2c_connect_ind_cback(const RawAddress& bd_addr, uint16_t lcid,
uint16_t psm, uint8_t id);
@@ -109,7 +111,7 @@
AvdtpCcb* p_ccb = NULL;
AvdtpTransportChannel* p_tbl;
- LOG_VERBOSE("avdt_sec_check_complete_orig res: %d", res);
+ log::verbose("avdt_sec_check_complete_orig res: {}", res);
if (bd_addr) p_ccb = avdt_ccb_by_bd(*bd_addr);
p_tbl = avdt_ad_tc_tbl_by_st(AVDT_CHAN_SIG, p_ccb, AVDT_AD_ST_SEC_INT);
if (p_tbl == NULL) return;
@@ -236,7 +238,7 @@
AvdtpTransportChannel* p_tbl;
AvdtpCcb* p_ccb;
- LOG_VERBOSE("avdt_l2c_connect_cfm_cback lcid: %d, result: %d", lcid, result);
+ log::verbose("avdt_l2c_connect_cfm_cback lcid: {}, result: {}", lcid, result);
/* look up info for this channel */
p_tbl = avdt_ad_tc_tbl_by_lcid(lcid);
if (p_tbl != NULL) {
@@ -276,7 +278,7 @@
/* failure; notify adaption that channel closed */
if (result != L2CAP_CONN_OK) {
- LOG(ERROR) << __func__ << ": invoked with non OK status";
+ log::error("invoked with non OK status");
}
}
}
@@ -298,7 +300,7 @@
AvdtpTransportChannel* p_tbl;
- LOG_VERBOSE("%s: lcid: %d", __func__, lcid);
+ log::verbose("lcid: {}", lcid);
/* look up info for this channel */
p_tbl = avdt_ad_tc_tbl_by_lcid(lcid);
@@ -325,7 +327,7 @@
void avdt_l2c_config_ind_cback(uint16_t lcid, tL2CAP_CFG_INFO* p_cfg) {
AvdtpTransportChannel* p_tbl;
- LOG_VERBOSE("%s: lcid: %d", __func__, lcid);
+ log::verbose("lcid: {}", lcid);
/* look up info for this channel */
p_tbl = avdt_ad_tc_tbl_by_lcid(lcid);
@@ -336,7 +338,7 @@
} else {
p_tbl->peer_mtu = L2CAP_DEFAULT_MTU;
}
- LOG_VERBOSE("%s: peer_mtu: %d, lcid: %d", __func__, p_tbl->peer_mtu, lcid);
+ log::verbose("peer_mtu: {}, lcid: {}", p_tbl->peer_mtu, lcid);
}
}
@@ -353,8 +355,8 @@
void avdt_l2c_disconnect_ind_cback(uint16_t lcid, bool ack_needed) {
AvdtpTransportChannel* p_tbl;
- LOG_VERBOSE("avdt_l2c_disconnect_ind_cback lcid: %d, ack_needed: %d", lcid,
- ack_needed);
+ log::verbose("avdt_l2c_disconnect_ind_cback lcid: {}, ack_needed: {}", lcid,
+ ack_needed);
/* look up info for this channel */
p_tbl = avdt_ad_tc_tbl_by_lcid(lcid);
if (p_tbl != NULL) {
@@ -366,7 +368,7 @@
L2CA_DisconnectReq(lcid);
AvdtpTransportChannel* p_tbl;
- LOG_VERBOSE("avdt_l2c_disconnect_cfm_cback lcid: %d", lcid);
+ log::verbose("avdt_l2c_disconnect_cfm_cback lcid: {}", lcid);
/* look up info for this channel */
p_tbl = avdt_ad_tc_tbl_by_lcid(lcid);
if (p_tbl != NULL) {
diff --git a/system/stack/avdt/avdt_msg.cc b/system/stack/avdt/avdt_msg.cc
index 29e5662..b998192 100644
--- a/system/stack/avdt/avdt_msg.cc
+++ b/system/stack/avdt/avdt_msg.cc
@@ -28,6 +28,7 @@
#define LOG_TAG "bluetooth"
+#include <bluetooth/log.h>
#include <string.h>
#include "avdt_api.h"
@@ -40,6 +41,8 @@
#include "stack/include/bt_hdr.h"
#include "stack/include/bt_types.h"
+using namespace bluetooth;
+
/*****************************************************************************
* constants
****************************************************************************/
@@ -531,7 +534,7 @@
uint8_t protect_offset = 0;
if (!p_cfg) {
- LOG_ERROR("not expecting this cfg");
+ log::error("not expecting this cfg");
return AVDT_ERR_BAD_STATE;
}
@@ -568,8 +571,8 @@
{
/* Skip unknown categories. */
p += elem_len;
- LOG_VERBOSE("skipping unknown service category=%d len: %d", elem,
- elem_len);
+ log::verbose("skipping unknown service category={} len: {}", elem,
+ elem_len);
continue;
}
}
@@ -582,8 +585,8 @@
/* add element to psc mask, but mask out codec or protect */
p_cfg->psc_mask |= (1 << elem);
- LOG_VERBOSE("elem=%d elem_len: %d psc_mask=0x%x", elem, elem_len,
- p_cfg->psc_mask);
+ log::verbose("elem={} elem_len: {} psc_mask=0x{:x}", elem, elem_len,
+ p_cfg->psc_mask);
/* parse individual information elements with additional parameters */
switch (elem) {
@@ -646,7 +649,7 @@
break;
case AVDT_CAT_DELAY_RPT:
- LOG_VERBOSE("%s: Remote device supports delay reporting", __func__);
+ log::verbose("Remote device supports delay reporting");
break;
default:
@@ -655,7 +658,8 @@
} /* switch */
} /* while ! err, !end*/
*p_elem = elem;
- LOG_VERBOSE("err=0x%x, elem:0x%x psc_mask=0x%x", err, elem, p_cfg->psc_mask);
+ log::verbose("err=0x{:x}, elem:0x{:x} psc_mask=0x{:x}", err, elem,
+ p_cfg->psc_mask);
return err;
}
@@ -789,8 +793,8 @@
/* verify no protocol service capabilities in parameters */
if (!err) {
- LOG_VERBOSE("avdt_msg_prs_reconfig_cmd psc_mask=0x%x/0x%x",
- p_msg->config_cmd.p_cfg->psc_mask, AVDT_MSG_PSC_MASK);
+ log::verbose("avdt_msg_prs_reconfig_cmd psc_mask=0x{:x}/0x{:x}",
+ p_msg->config_cmd.p_cfg->psc_mask, AVDT_MSG_PSC_MASK);
if ((p_msg->config_cmd.p_cfg->psc_mask != 0) ||
(p_msg->config_cmd.p_cfg->num_codec == 0 &&
p_msg->config_cmd.p_cfg->num_protect == 0)) {
@@ -1023,8 +1027,8 @@
/* verify len */
if (len != AVDT_LEN_DELAY_RPT) {
- LOG_WARN("avdt_msg_prs_delay_rpt expected len: %u got: %u",
- AVDT_LEN_DELAY_RPT, len);
+ log::warn("avdt_msg_prs_delay_rpt expected len: {} got: {}",
+ AVDT_LEN_DELAY_RPT, len);
err = AVDT_ERR_LENGTH;
} else {
/* get seid */
@@ -1034,8 +1038,8 @@
err = AVDT_ERR_SEID;
} else {
BE_STREAM_TO_UINT16(p_msg->delay_rpt_cmd.delay, p);
- LOG_VERBOSE("avdt_msg_prs_delay_rpt delay: %u",
- p_msg->delay_rpt_cmd.delay);
+ log::verbose("avdt_msg_prs_delay_rpt delay: {}",
+ p_msg->delay_rpt_cmd.delay);
}
}
return err;
@@ -1135,7 +1139,7 @@
label = AVDT_LAYERSPEC_LABEL(p_ccb->p_curr_msg->layer_specific);
msg = AVDT_LAYERSPEC_MSG(p_ccb->p_curr_msg->layer_specific);
sig = (uint8_t)p_ccb->p_curr_msg->event;
- LOG_VERBOSE("avdt_msg_send label:%d, msg:%d, sig:%d", label, msg, sig);
+ log::verbose("avdt_msg_send label:{}, msg:{}, sig:{}", label, msg, sig);
/* keep track of how much of msg we've sent */
curr_msg_len -= p_buf->len;
@@ -1218,13 +1222,13 @@
/* quick sanity check on length */
if (p_buf->len < avdt_msg_pkt_type_len[pkt_type]) {
osi_free(p_buf);
- LOG_WARN("Bad length during reassembly");
+ log::warn("Bad length during reassembly");
p_ret = NULL;
}
/* single packet */
else if (pkt_type == AVDT_PKT_TYPE_SINGLE) {
/* if reassembly in progress drop message and process new single */
- if (p_ccb->p_rx_msg != NULL) LOG_WARN("Got single during reassembly");
+ if (p_ccb->p_rx_msg != NULL) log::warn("Got single during reassembly");
osi_free_and_reset((void**)&p_ccb->p_rx_msg);
@@ -1233,7 +1237,7 @@
/* start packet */
else if (pkt_type == AVDT_PKT_TYPE_START) {
/* if reassembly in progress drop message and process new single */
- if (p_ccb->p_rx_msg != NULL) LOG_WARN("Got start during reassembly");
+ if (p_ccb->p_rx_msg != NULL) log::warn("Got start during reassembly");
osi_free_and_reset((void**)&p_ccb->p_rx_msg);
@@ -1272,7 +1276,7 @@
/* if no reassembly in progress drop message */
if (p_ccb->p_rx_msg == NULL) {
osi_free(p_buf);
- LOG_WARN("Pkt type=%d out of order", pkt_type);
+ log::warn("Pkt type={} out of order", pkt_type);
p_ret = NULL;
} else {
/* get size of buffer holding assembled message */
@@ -1289,7 +1293,7 @@
/* verify length */
if (((size_t) p_ccb->p_rx_msg->offset + (size_t) p_buf->len) > buf_len) {
/* won't fit; free everything */
- LOG_WARN("%s: Fragmented message too big!", __func__);
+ log::warn("Fragmented message too big!");
osi_free_and_reset((void**)&p_ccb->p_rx_msg);
osi_free(p_buf);
p_ret = NULL;
@@ -1448,7 +1452,7 @@
/* add the error code */
AVDT_MSG_BLD_ERR(p, p_params->hdr.err_code);
}
- LOG_VERBOSE("avdt_msg_send_rej");
+ log::verbose("avdt_msg_send_rej");
/* calculate length */
p_buf->len = (uint16_t)(p - p_start);
@@ -1494,7 +1498,7 @@
p_buf->event = sig_id;
AVDT_BLD_LAYERSPEC(p_buf->layer_specific, AVDT_MSG_TYPE_GRJ,
p_params->hdr.label);
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
/* queue message and trigger ccb to send it */
fixed_queue_enqueue(p_ccb->rsp_q, p_buf);
@@ -1542,14 +1546,14 @@
/* parse the message header */
AVDT_MSG_PRS_HDR(p, label, pkt_type, msg_type);
- LOG_VERBOSE("msg_type=%d, sig=%d", msg_type, sig);
+ log::verbose("msg_type={}, sig={}", msg_type, sig);
/* set up label and ccb_idx in message hdr */
msg.hdr.label = label;
msg.hdr.ccb_idx = avdt_ccb_to_idx(p_ccb);
/* verify msg type */
if (msg_type == AVDT_MSG_TYPE_GRJ) {
- LOG_WARN("Dropping msg msg_type=%d", msg_type);
+ log::warn("Dropping msg msg_type={}", msg_type);
ok = false;
}
/* check for general reject */
@@ -1568,7 +1572,7 @@
AVDT_MSG_PRS_SIG(p, sig);
msg.hdr.sig_id = sig;
if ((sig == 0) || (sig > AVDT_SIG_MAX)) {
- LOG_WARN("Dropping msg sig=%d msg_type:%d", sig, msg_type);
+ log::warn("Dropping msg sig={} msg_type:{}", sig, msg_type);
ok = false;
/* send a general reject */
@@ -1619,7 +1623,7 @@
/* if parsing failed */
if (err != 0) {
- LOG_WARN("Parsing failed sig=%d err=0x%x", sig, err);
+ log::warn("Parsing failed sig={} err=0x{:x}", sig, err);
/* if its a rsp or rej, drop it; if its a cmd, send a rej;
** note special case for abort; never send abort reject
@@ -1651,7 +1655,7 @@
handle_rsp = true;
} else {
ok = false;
- LOG_WARN("Cmd not found for rsp sig=%d label=%d", sig, label);
+ log::warn("Cmd not found for rsp sig={} label={}", sig, label);
}
}
}
diff --git a/system/stack/avdt/avdt_scb.cc b/system/stack/avdt/avdt_scb.cc
index fb7c40c..c15d13a 100644
--- a/system/stack/avdt/avdt_scb.cc
+++ b/system/stack/avdt/avdt_scb.cc
@@ -23,6 +23,7 @@
*
******************************************************************************/
+#include <bluetooth/log.h>
#include <string.h>
#include "avdt_api.h"
@@ -32,6 +33,8 @@
#include "internal_include/bt_target.h"
#include "osi/include/osi.h"
+using namespace bluetooth;
+
/*****************************************************************************
* state machine constants and types
****************************************************************************/
@@ -759,10 +762,10 @@
uint8_t action;
#if (AVDT_DEBUG == TRUE)
- LOG_VERBOSE("%s: SCB hdl=%d event=%d/%s state=%s p_avdt_scb=%p scb_index=%d",
- __func__, avdt_scb_to_hdl(p_scb), event, avdt_scb_evt_str[event],
- avdt_scb_st_str[p_scb->state], p_scb,
- p_scb->stream_config.scb_index);
+ log::verbose("SCB hdl={} event={}/{} state={} p_avdt_scb={} scb_index={}",
+ avdt_scb_to_hdl(p_scb), event, avdt_scb_evt_str[event],
+ avdt_scb_st_str[p_scb->state], fmt::ptr(p_scb),
+ p_scb->stream_config.scb_index);
#endif
/* Check that we only send AVDT_SCB_API_WRITE_REQ_EVT to the active stream
@@ -789,7 +792,7 @@
avdtp_cb.ccb[ccb_index].scb[scb_index].curr_stream = true;
} else if (num_st_streams > 1 && !p_scb->curr_stream &&
event == AVDT_SCB_API_WRITE_REQ_EVT) {
- LOG_ERROR("%s: ignore AVDT_SCB_API_WRITE_REQ_EVT", __func__);
+ log::error("ignore AVDT_SCB_API_WRITE_REQ_EVT");
avdt_scb_free_pkt(p_scb, p_data);
return;
}
@@ -855,13 +858,13 @@
for (int i = 0; i < AVDT_NUM_SEPS; i++, p_scb++) {
if (!p_scb->allocated) {
p_scb->Allocate(&avdtp_cb.ccb[peer_id], avdtp_stream_config);
- LOG_VERBOSE("%s: allocated (handle=%d, psc_mask:0x%x)", __func__,
- p_scb->ScbHandle(), avdtp_stream_config.cfg.psc_mask);
+ log::verbose("allocated (handle={}, psc_mask:0x{:x})", p_scb->ScbHandle(),
+ avdtp_stream_config.cfg.psc_mask);
return p_scb;
}
}
- LOG_WARN("%s: out of AvdtScb entries for peer_id %d", __func__, peer_id);
+ log::warn("out of AvdtScb entries for peer_id {}", peer_id);
return nullptr;
}
@@ -886,7 +889,7 @@
*
******************************************************************************/
void avdt_scb_dealloc(AvdtpScb* p_scb, UNUSED_ATTR tAVDT_SCB_EVT* p_data) {
- LOG_VERBOSE("%s: hdl=%d", __func__, avdt_scb_to_hdl(p_scb));
+ log::verbose("hdl={}", avdt_scb_to_hdl(p_scb));
p_scb->Recycle();
}
@@ -916,7 +919,7 @@
AvdtpScb* avdt_scb_by_hdl(uint8_t hdl) {
// Verify the index
if ((hdl < 1) || (hdl > AVDT_NUM_LINKS * AVDT_NUM_SEPS)) {
- LOG_WARN("%s: SCB handle %d out of range", __func__, hdl);
+ log::warn("SCB handle {} out of range", hdl);
return nullptr;
}
@@ -927,12 +930,12 @@
AvdtpScb* p_scb = &avdtp_cb.ccb[i].scb[j];
// Verify the whether the scb is allocated
if (!p_scb->allocated) {
- LOG_WARN("%s: SCB handle %d not allocated", __func__, hdl);
+ log::warn("SCB handle {} not allocated", hdl);
return nullptr;
}
- LOG_VERBOSE("%s: SCB for handle %d found: p_scb=%p scb_index=%d", __func__,
- hdl, p_scb, p_scb->stream_config.scb_index);
+ log::verbose("SCB for handle {} found: p_scb={} scb_index={}", hdl,
+ fmt::ptr(p_scb), p_scb->stream_config.scb_index);
return p_scb;
}
@@ -948,7 +951,7 @@
******************************************************************************/
uint8_t avdt_scb_verify(AvdtpCcb* p_ccb, uint8_t state, uint8_t* p_seid,
uint16_t num_seid, uint8_t* p_err_code) {
- LOG_VERBOSE("avdt_scb_verify state %d", state);
+ log::verbose("avdt_scb_verify state {}", state);
/* set nonsupported command mask */
/* translate public state into private state */
uint8_t nsc_mask = 0;
diff --git a/system/stack/avdt/avdt_scb_act.cc b/system/stack/avdt/avdt_scb_act.cc
index 9920f01..58b651a 100644
--- a/system/stack/avdt/avdt_scb_act.cc
+++ b/system/stack/avdt/avdt_scb_act.cc
@@ -25,6 +25,7 @@
#define LOG_TAG "bluetooth"
+#include <bluetooth/log.h>
#include <string.h>
#include "a2dp_codec_api.h"
@@ -38,6 +39,8 @@
#include "stack/include/bt_types.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
/* This table is used to lookup the callback event that matches a particular
* state machine API request event. Note that state machine API request
* events are at the beginning of the event list starting at zero, thus
@@ -274,7 +277,7 @@
/* do sanity check */
if (pad_len >= (len - offset)) {
- LOG_WARN("Got bad media packet");
+ log::warn("Got bad media packet");
osi_free_and_reset((void**)&p_data->p_pkt);
}
/* adjust offset and length and send it up */
@@ -294,8 +297,7 @@
}
return;
length_error:
- LOG_WARN("%s: hdl packet length %d too short: must be at least %d", __func__,
- len, offset);
+ log::warn("hdl packet length {} too short: must be at least {}", len, offset);
osi_free_and_reset((void**)&p_data->p_pkt);
}
@@ -317,13 +319,13 @@
AVDT_REPORT_TYPE pt;
tAVDT_REPORT_DATA report;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
if (p_scb->stream_config.p_report_cback) {
/* parse report packet header */
min_len += 8;
if (min_len > len) {
- LOG_WARN("%s: hdl packet length %d too short: must be at least %d",
- __func__, len, min_len);
+ log::warn("hdl packet length {} too short: must be at least {}", len,
+ min_len);
goto avdt_scb_hdl_report_exit;
}
AVDT_MSG_PRS_RPT_OCTET1(p, o_v, o_p, o_cc);
@@ -335,8 +337,8 @@
case AVDT_RTCP_PT_SR: /* the packet type - SR (Sender Report) */
min_len += 20;
if (min_len > len) {
- LOG_WARN("%s: hdl packet length %d too short: must be at least %d",
- __func__, len, min_len);
+ log::warn("hdl packet length {} too short: must be at least {}", len,
+ min_len);
goto avdt_scb_hdl_report_exit;
}
BE_STREAM_TO_UINT32(report.sr.ntp_sec, p);
@@ -349,8 +351,8 @@
case AVDT_RTCP_PT_RR: /* the packet type - RR (Receiver Report) */
min_len += 20;
if (min_len > len) {
- LOG_WARN("%s: hdl packet length %d too short: must be at least %d",
- __func__, len, min_len);
+ log::warn("hdl packet length {} too short: must be at least {}", len,
+ min_len);
goto avdt_scb_hdl_report_exit;
}
report.rr.frag_lost = *p;
@@ -366,8 +368,8 @@
uint8_t sdes_type;
min_len += 1;
if (min_len > len) {
- LOG_WARN("%s: hdl packet length %d too short: must be at least %d",
- __func__, len, min_len);
+ log::warn("hdl packet length {} too short: must be at least {}", len,
+ min_len);
goto avdt_scb_hdl_report_exit;
}
BE_STREAM_TO_UINT8(sdes_type, p);
@@ -375,8 +377,8 @@
uint8_t name_length;
min_len += 1;
if (min_len > len) {
- LOG_WARN("%s: hdl packet length %d too short: must be at least %d",
- __func__, len, min_len);
+ log::warn("hdl packet length {} too short: must be at least {}",
+ len, min_len);
goto avdt_scb_hdl_report_exit;
}
BE_STREAM_TO_UINT8(name_length, p);
@@ -388,18 +390,18 @@
}
} else {
if (min_len + 1 > len) {
- LOG_WARN("%s: hdl packet length %d too short: must be at least %d",
- __func__, len, min_len);
+ log::warn("hdl packet length {} too short: must be at least {}",
+ len, min_len);
goto avdt_scb_hdl_report_exit;
}
- LOG_WARN("%s: SDES SSRC=0x%08x sc=%d %d len=%d", __func__, ssrc, o_cc,
- sdes_type, *p);
+ log::warn("SDES SSRC=0x{:08x} sc={} {} len={}", ssrc, o_cc, sdes_type,
+ *p);
result = AVDT_BUSY;
}
break;
default:
- LOG_ERROR("Bad Report pkt - packet type: %d", pt);
+ log::error("Bad Report pkt - packet type: {}", pt);
result = AVDT_BAD_PARAMS;
}
@@ -442,7 +444,7 @@
*
******************************************************************************/
void avdt_scb_drop_pkt(UNUSED_ATTR AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) {
- LOG_ERROR("%s dropped incoming media packet", __func__);
+ log::error("dropped incoming media packet");
osi_free_and_reset((void**)&p_data->p_pkt);
}
@@ -560,15 +562,15 @@
*
******************************************************************************/
void avdt_scb_hdl_setconfig_cmd(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) {
- LOG_VERBOSE("%s: p_scb->in_use=%d p_avdt_scb=%p scb_index=%d", __func__,
- p_scb->in_use, p_scb, p_scb->stream_config.scb_index);
+ log::verbose("p_scb->in_use={} p_avdt_scb={} scb_index={}", p_scb->in_use,
+ fmt::ptr(p_scb), p_scb->stream_config.scb_index);
if (!p_scb->in_use) {
- LOG_VERBOSE(
- "%s: codec: %s", __func__,
+ log::verbose(
+ "codec: {}",
A2DP_CodecInfoString(p_scb->stream_config.cfg.codec_info).c_str());
- LOG_VERBOSE(
- "%s: codec: %s", __func__,
+ log::verbose(
+ "codec: {}",
A2DP_CodecInfoString(p_data->msg.config_cmd.p_cfg->codec_info).c_str());
AvdtpSepConfig* p_cfg = p_data->msg.config_cmd.p_cfg;
if (A2DP_GetCodecType(p_scb->stream_config.cfg.codec_info) ==
@@ -576,12 +578,11 @@
/* copy info to scb */
AvdtpCcb* p_ccb = avdt_ccb_by_idx(p_data->msg.config_cmd.hdr.ccb_idx);
if (p_scb->p_ccb != p_ccb) {
- LOG_ERROR(
- "%s: mismatch in AVDTP SCB/CCB state: (p_scb->p_ccb=%p != "
- "p_ccb=%p): "
- "p_scb=%p scb_handle=%d ccb_idx=%d",
- __func__, p_scb->p_ccb, p_ccb, p_scb, p_scb->ScbHandle(),
- p_data->msg.config_cmd.hdr.ccb_idx);
+ log::error(
+ "mismatch in AVDTP SCB/CCB state: (p_scb->p_ccb={} != p_ccb={}): "
+ "p_scb={} scb_handle={} ccb_idx={}",
+ fmt::ptr(p_scb->p_ccb), fmt::ptr(p_ccb), fmt::ptr(p_scb),
+ p_scb->ScbHandle(), p_data->msg.config_cmd.hdr.ccb_idx);
avdt_scb_rej_not_in_use(p_scb, p_data);
return;
}
@@ -604,7 +605,7 @@
p_data->msg.hdr.sig_id, &p_data->msg);
}
} else {
- LOG_VERBOSE("%s: calling avdt_scb_rej_in_use()", __func__);
+ log::verbose("calling avdt_scb_rej_in_use()");
avdt_scb_rej_in_use(p_scb, p_data);
}
}
@@ -932,9 +933,9 @@
(p_scb->role == AVDT_OPEN_INT) ? AVDT_OPEN_CFM_EVT : AVDT_OPEN_IND_EVT;
p_data->open.hdr.err_code = 0;
- LOG_VERBOSE("%s: psc_mask: cfg: 0x%x, req:0x%x, cur: 0x%x", __func__,
- p_scb->stream_config.cfg.psc_mask, p_scb->req_cfg.psc_mask,
- p_scb->curr_cfg.psc_mask);
+ log::verbose("psc_mask: cfg: 0x{:x}, req:0x{:x}, cur: 0x{:x}",
+ p_scb->stream_config.cfg.psc_mask, p_scb->req_cfg.psc_mask,
+ p_scb->curr_cfg.psc_mask);
if (p_scb->curr_cfg.psc_mask & AVDT_PSC_REPORT) {
/* open the reporting channel, if both devices support it */
role = (p_scb->role == AVDT_OPEN_INT) ? AVDT_INT : AVDT_ACP;
@@ -994,7 +995,7 @@
/* free packet we're holding, if any; to be replaced with new */
if (p_scb->p_pkt != NULL) {
/* this shouldn't be happening */
- LOG_WARN("Dropped media packet; congested");
+ log::warn("Dropped media packet; congested");
}
osi_free_and_reset((void**)&p_scb->p_pkt);
@@ -1042,7 +1043,7 @@
UNUSED_ATTR tAVDT_SCB_EVT* p_data) {
tAVDT_EVT_HDR hdr;
- LOG_VERBOSE("%s: p_scb->p_ccb=%p", __func__, p_scb->p_ccb);
+ log::verbose("p_scb->p_ccb={}", fmt::ptr(p_scb->p_ccb));
if (p_scb->p_ccb != NULL) {
p_scb->role = AVDT_CLOSE_INT;
@@ -1206,10 +1207,10 @@
*
******************************************************************************/
void avdt_scb_snd_reconfig_req(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) {
- LOG_VERBOSE("%s: p_scb->peer_seid=%d p_data->msg.hdr.seid=%d", __func__,
- p_scb->peer_seid, p_data->msg.hdr.seid);
- LOG_VERBOSE(
- "%s: codec: %s", __func__,
+ log::verbose("p_scb->peer_seid={} p_data->msg.hdr.seid={}", p_scb->peer_seid,
+ p_data->msg.hdr.seid);
+ log::verbose(
+ "codec: {}",
A2DP_CodecInfoString(p_data->msg.config_cmd.p_cfg->codec_info).c_str());
p_scb->req_cfg = *p_data->msg.config_cmd.p_cfg;
@@ -1312,19 +1313,19 @@
*
******************************************************************************/
void avdt_scb_snd_setconfig_req(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) {
- LOG_VERBOSE(
- "%s: codec: %s", __func__,
+ log::verbose(
+ "codec: {}",
A2DP_CodecInfoString(p_data->msg.config_cmd.p_cfg->codec_info).c_str());
/* copy API parameters to scb, set scb as in use */
AvdtpCcb* p_ccb = avdt_ccb_by_idx(p_data->msg.config_cmd.hdr.ccb_idx);
if (p_scb->p_ccb != p_ccb) {
- LOG_ERROR(
- "%s: mismatch in AVDTP SCB/CCB state: (p_scb->p_ccb=%p != p_ccb=%p): "
- "p_scb=%p scb_handle=%d ccb_idx=%d",
- __func__, p_scb->p_ccb, p_ccb, p_scb, p_scb->ScbHandle(),
- p_data->msg.config_cmd.hdr.ccb_idx);
+ log::error(
+ "mismatch in AVDTP SCB/CCB state: (p_scb->p_ccb={} != p_ccb={}): "
+ "p_scb={} scb_handle={} ccb_idx={}",
+ fmt::ptr(p_scb->p_ccb), fmt::ptr(p_ccb), fmt::ptr(p_scb),
+ p_scb->ScbHandle(), p_data->msg.config_cmd.hdr.ccb_idx);
avdt_scb_rej_not_in_use(p_scb, p_data);
return;
}
@@ -1494,7 +1495,7 @@
osi_free_and_reset((void**)&p_data->apiwrite.p_buf);
- LOG_WARN("Dropped media packet");
+ log::warn("Dropped media packet");
/* we need to call callback to keep data flow going */
(*p_scb->stream_config.p_avdt_ctrl_cback)(
@@ -1533,7 +1534,7 @@
if (p_scb->p_pkt != NULL) {
osi_free_and_reset((void**)&p_scb->p_pkt);
- LOG_VERBOSE("Dropped stored media packet");
+ log::verbose("Dropped stored media packet");
/* we need to call callback to keep data flow going */
(*p_scb->stream_config.p_avdt_ctrl_cback)(
diff --git a/system/stack/avrc/avrc_api.cc b/system/stack/avrc/avrc_api.cc
index 328abe1..e1a7643 100644
--- a/system/stack/avrc/avrc_api.cc
+++ b/system/stack/avrc/avrc_api.cc
@@ -24,12 +24,11 @@
#include "avrc_api.h"
#include <android_bluetooth_sysprop.h>
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include <string.h>
#include "avrc_int.h"
#include "btif/include/btif_config.h"
-#include "gd/storage/config_keys.h"
#include "include/check.h"
#include "internal_include/bt_target.h"
#include "os/log.h"
@@ -40,8 +39,11 @@
#include "stack/include/bt_hdr.h"
#include "stack/include/bt_types.h"
#include "stack/include/bt_uuid16.h"
+#include "storage/config_keys.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
/*****************************************************************************
* Global data
****************************************************************************/
@@ -135,7 +137,7 @@
*
*****************************************************************************/
void avrc_flush_cmd_q(uint8_t handle) {
- LOG_VERBOSE("AVRC: Flushing command queue for handle=0x%02x", handle);
+ log::verbose("AVRC: Flushing command queue for handle=0x{:02x}", handle);
avrc_cb.ccb_int[handle].flags &= ~AVRC_CB_FLAGS_RSP_PENDING;
alarm_cancel(avrc_cb.ccb_int[handle].tle);
@@ -155,8 +157,8 @@
void avrc_process_timeout(void* data) {
tAVRC_PARAM* param = (tAVRC_PARAM*)data;
- LOG_VERBOSE("AVRC: command timeout (handle=0x%02x, label=0x%02x)",
- param->handle, param->label);
+ log::verbose("AVRC: command timeout (handle=0x{:02x}, label=0x{:02x})",
+ param->handle, param->label);
/* Notify app */
if (avrc_cb.ccb[param->handle].ctrl_cback) {
@@ -190,8 +192,9 @@
next_label = (p_next_cmd->layer_specific) >> 8; /* extract label */
p_next_cmd->layer_specific &= 0xFF; /* AVCT_DATA_CTRL or AVCT_DATA_BROWSE */
- LOG_VERBOSE("AVRC: Dequeuing command 0x%p (handle=0x%02x, label=0x%02x)",
- p_next_cmd, handle, next_label);
+ log::verbose(
+ "AVRC: Dequeuing command 0x{} (handle=0x{:02x}, label=0x{:02x})",
+ fmt::ptr(p_next_cmd), handle, next_label);
/* Send the message */
if ((AVCT_MsgReq(handle, next_label, AVCT_CMD, p_next_cmd)) ==
@@ -224,8 +227,8 @@
param->label = label;
param->msg_mask = msg_mask;
- LOG_VERBOSE("AVRC: starting timer (handle=0x%02x, label=0x%02x)", handle,
- label);
+ log::verbose("AVRC: starting timer (handle=0x{:02x}, label=0x{:02x})", handle,
+ label);
alarm_set_on_mloop(avrc_cb.ccb_int[handle].tle, AVRC_CMD_TOUT_MS,
avrc_process_timeout, param);
@@ -284,7 +287,7 @@
uint8_t *p_data, *p_orig_data;
uint8_t rsp_type;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
p_fcb = &avrc_cb.fcb[handle];
/* The response type of the end fragment should be the same as the the PDU of
@@ -331,8 +334,7 @@
p_fcb = &avrc_cb.fcb[handle];
p_pkt = p_fcb->p_fmsg;
- LOG_VERBOSE("%s handle = %u label = %u len = %d", __func__, handle, label,
- p_pkt->len);
+ log::verbose("handle = {} label = {} len = {}", handle, label, p_pkt->len);
if (p_pkt->len > AVRC_MAX_CTRL_DATA_LEN) {
int offset_len = MAX(AVCT_MSG_OFFSET, p_pkt->offset);
p_pkt_old = p_fcb->p_fmsg;
@@ -388,7 +390,7 @@
if (pkt_type != AVRC_PKT_SINGLE) {
/* reject - commands can only be in single packets at AVRCP level */
- LOG_ERROR("commands must be in single packet pdu:0x%x", *p_data);
+ 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;
}
@@ -422,9 +424,9 @@
} else {
/* the pdu id does not match - reject the command using the current
* GKI buffer */
- LOG_ERROR(
- "%s continue pdu: 0x%x does not match the current pdu: 0x%x",
- __func__, *(p_data + 4), p_fcb->frag_pdu);
+ log::error(
+ "continue pdu: 0x{:x} does not match the current pdu: 0x{:x}",
+ *(p_data + 4), p_fcb->frag_pdu);
status = AVRC_STS_BAD_PARAM;
abort_frag = true;
}
@@ -491,7 +493,7 @@
p_data += AVRC_VENDOR_HDR_SIZE;
pkt_type = *(p_data + 1) & AVRC_PKT_TYPE_MASK;
- LOG_VERBOSE("pkt_type %d", pkt_type);
+ log::verbose("pkt_type {}", pkt_type);
p_rcb = &avrc_cb.rcb[handle];
/* check if the message needs to be re-assembled */
@@ -534,9 +536,9 @@
} else if (p_rcb->p_rmsg == NULL) {
/* Received a CONTINUE/END, but no corresponding START
(or previous fragmented response was dropped) */
- LOG_VERBOSE(
- "Received a CONTINUE/END without no corresponding START"
- " (or previous fragmented response was dropped)");
+ log::verbose(
+ "Received a CONTINUE/END without no corresponding START (or previous "
+ "fragmented response was dropped)");
drop_code = 5;
osi_free(p_pkt);
*pp_pkt = NULL;
@@ -552,7 +554,7 @@
p_pkt->len -= (AVRC_VENDOR_HDR_SIZE + AVRC_MIN_META_HDR_SIZE);
/* verify length */
if ((p_rcb->p_rmsg->offset + p_pkt->len) > buf_len) {
- LOG_WARN("Fragmented message too big! - report the partial message");
+ log::warn("Fragmented message too big! - report the partial message");
p_pkt->len = buf_len - p_rcb->p_rmsg->offset;
pkt_type = AVRC_PKT_END;
buf_overflow = true;
@@ -577,8 +579,8 @@
*p_data++ = AVRC_PKT_SINGLE;
UINT16_TO_BE_STREAM(p_data,
(p_msg->vendor_len - AVRC_MIN_META_HDR_SIZE));
- LOG_VERBOSE("end frag:%d, total len:%d, offset:%d", p_pkt->len,
- p_pkt_new->len, p_pkt_new->offset);
+ log::verbose("end frag:{}, total len:{}, offset:{}", p_pkt->len,
+ p_pkt_new->len, p_pkt_new->offset);
} else {
p_rcb->p_rmsg->offset += p_pkt->len;
p_rcb->p_rmsg->len += p_pkt->len;
@@ -655,8 +657,8 @@
if (cr == AVCT_CMD && (p_pkt->layer_specific & AVCT_DATA_CTRL &&
p_pkt->len > AVRC_PACKET_LEN)) {
- LOG_WARN("%s: Command length %d too long: must be at most %d", __func__,
- p_pkt->len, AVRC_PACKET_LEN);
+ log::warn("Command length {} too long: must be at most {}", p_pkt->len,
+ AVRC_PACKET_LEN);
osi_free(p_pkt);
return;
}
@@ -669,7 +671,7 @@
return;
} else if (cr == AVCT_RSP) {
/* Received response. Stop command timeout timer */
- LOG_VERBOSE("AVRC: stopping timer (handle=0x%02x)", handle);
+ log::verbose("AVRC: stopping timer (handle=0x{:02x})", handle);
alarm_cancel(avrc_cb.ccb_int[handle].tle);
}
@@ -684,14 +686,14 @@
msg.browse.p_browse_pkt = p_pkt;
} else {
if (p_pkt->len < AVRC_AVC_HDR_SIZE) {
- LOG_WARN("%s: message length %d too short: must be at least %d", __func__,
- p_pkt->len, AVRC_AVC_HDR_SIZE);
+ log::warn("message length {} too short: must be at least {}", p_pkt->len,
+ AVRC_AVC_HDR_SIZE);
osi_free(p_pkt);
return;
}
msg.hdr.ctype = p_data[0] & AVRC_CTYPE_MASK;
- LOG_VERBOSE("%s handle:%d, ctype:%d, offset:%d, len: %d", __func__, handle,
- msg.hdr.ctype, p_pkt->offset, p_pkt->len);
+ log::verbose("handle:{}, ctype:{}, offset:{}, len: {}", handle,
+ msg.hdr.ctype, p_pkt->offset, p_pkt->len);
msg.hdr.subunit_type =
(p_data[1] & AVRC_SUBTYPE_MASK) >> AVRC_SUBTYPE_SHIFT;
msg.hdr.subunit_id = p_data[1] & AVRC_SUBID_MASK;
@@ -723,8 +725,8 @@
} else {
/* parse response */
if (p_pkt->len < AVRC_OP_UNIT_INFO_RSP_LEN) {
- LOG_WARN("%s: message length %d too short: must be at least %d",
- __func__, p_pkt->len, AVRC_OP_UNIT_INFO_RSP_LEN);
+ log::warn("message length {} too short: must be at least {}",
+ p_pkt->len, AVRC_OP_UNIT_INFO_RSP_LEN);
drop = true;
p_drop_msg = "UNIT_INFO_RSP too short";
break;
@@ -759,8 +761,8 @@
} else {
/* parse response */
if (p_pkt->len < AVRC_OP_SUB_UNIT_INFO_RSP_LEN) {
- LOG_WARN("%s: message length %d too short: must be at least %d",
- __func__, p_pkt->len, AVRC_OP_SUB_UNIT_INFO_RSP_LEN);
+ log::warn("message length {} too short: must be at least {}",
+ p_pkt->len, AVRC_OP_SUB_UNIT_INFO_RSP_LEN);
drop = true;
p_drop_msg = "SUB_UNIT_INFO_RSP too short";
break;
@@ -905,8 +907,8 @@
msg.hdr.opcode = opcode;
avrc_cb.ccb[handle].msg_cback.Run(handle, label, opcode, &msg);
} else {
- LOG_WARN("%s %s msg handle:%d, control:%d, cr:%d, opcode:x%x", __func__,
- p_drop_msg, handle, avrc_cb.ccb[handle].control, cr, opcode);
+ log::warn("{} msg handle:{}, control:{}, cr:{}, opcode:x{:x}", p_drop_msg,
+ handle, avrc_cb.ccb[handle].control, cr, opcode);
}
if (opcode == AVRC_OP_BROWSE && msg.browse.p_browse_pkt == NULL) {
@@ -1090,8 +1092,8 @@
avrc_cb.ccb_int[*p_handle].tle = alarm_new("avrcp.commandTimer");
avrc_cb.ccb_int[*p_handle].cmd_q = fixed_queue_new(SIZE_MAX);
}
- LOG_VERBOSE("%s role: %d, control:%d status:%d, handle:%d", __func__, cc.role,
- cc.control, status, *p_handle);
+ log::verbose("role: {}, control:{} status:{}, handle:{}", cc.role, cc.control,
+ status, *p_handle);
return status;
}
@@ -1115,7 +1117,7 @@
*
*****************************************************************************/
uint16_t AVRC_Close(uint8_t handle) {
- LOG_VERBOSE("%s handle:%d", __func__, handle);
+ log::verbose("handle:{}", handle);
avrc_flush_cmd_q(handle);
return AVCT_RemoveConn(handle);
}
@@ -1186,8 +1188,8 @@
if (!p_pkt) return AVRC_BAD_PARAM;
- LOG_VERBOSE("%s handle = %u label = %u ctype = %u len = %d", __func__, handle,
- label, ctype, p_pkt->len);
+ log::verbose("handle = {} label = {} ctype = {} len = {}", handle, label,
+ ctype, p_pkt->len);
/* Handle for AVRCP fragment */
if (!GET_SYSPROP(A2dp, src_sink_coexist, false))
is_new_avrcp =
@@ -1238,8 +1240,8 @@
peer_mtu = AVCT_GetPeerMtu(handle);
}
if (p_pkt->len > (peer_mtu - AVCT_HDR_LEN_SINGLE)) {
- LOG_ERROR("%s bigger than peer mtu (p_pkt->len(%d) > peer_mtu(%d-%d))",
- __func__, p_pkt->len, peer_mtu, AVCT_HDR_LEN_SINGLE);
+ log::error("bigger than peer mtu (p_pkt->len({}) > peer_mtu({}-{}))",
+ p_pkt->len, peer_mtu, AVCT_HDR_LEN_SINGLE);
osi_free(p_pkt);
return AVRC_MSG_TOO_BIG;
}
@@ -1249,7 +1251,7 @@
p_fcb = &avrc_cb.fcb[handle];
if (p_fcb == NULL) {
- LOG_ERROR("%s p_fcb is NULL", __func__);
+ log::error("p_fcb is NULL");
osi_free(p_pkt);
return AVRC_NOT_OPEN;
}
@@ -1291,11 +1293,11 @@
/* prepare the left over for as an end fragment */
avrc_prep_end_frag(handle);
- LOG_VERBOSE("%s p_pkt len:%d/%d, next len:%d", __func__, p_pkt->len,
- len, p_fcb->p_fmsg->len);
+ log::verbose("p_pkt len:{}/{}, next len:{}", p_pkt->len, len,
+ p_fcb->p_fmsg->len);
} else {
/* TODO: Is this "else" block valid? Remove it? */
- LOG_ERROR("%s no buffers for fragmentation", __func__);
+ log::error("no buffers for fragmentation");
osi_free(p_pkt);
return AVRC_NO_RESOURCES;
}
@@ -1309,8 +1311,9 @@
* command
* is received (exception is continuation request command
* must sent that to get additional response frags) */
- LOG_VERBOSE("AVRC: Enqueuing command 0x%p (handle=0x%02x, label=0x%02x)",
- p_pkt, handle, label);
+ log::verbose(
+ "AVRC: Enqueuing command 0x{} (handle=0x{:02x}, label=0x{:02x})",
+ fmt::ptr(p_pkt), handle, label);
/* label in BT_HDR (will need this later when the command is dequeued) */
p_pkt->layer_specific = (label << 8) | (p_pkt->layer_specific & 0xFF);
@@ -1437,21 +1440,21 @@
BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION,
(uint8_t*)&old_version, &version_value_size) &&
new_version == old_version) {
- LOG_INFO("AVRC controller version same as cached config");
+ log::info("AVRC controller version same as cached config");
} else if (btif_config_set_bin(
bdaddr.ToString(), BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION,
(const uint8_t*)&new_version, sizeof(new_version))) {
- LOG_INFO("store AVRC controller version %x for %s into config.",
- new_version, ADDRESS_TO_LOGGABLE_CSTR(bdaddr));
+ log::info("store AVRC controller version {:x} for {} into config.",
+ new_version, ADDRESS_TO_LOGGABLE_CSTR(bdaddr));
} else {
- LOG_WARN("Failed to store AVRC controller version for %s",
- ADDRESS_TO_LOGGABLE_CSTR(bdaddr));
+ log::warn("Failed to store AVRC controller version for {}",
+ ADDRESS_TO_LOGGABLE_CSTR(bdaddr));
}
}
void AVRC_UpdateCcb(RawAddress* addr, uint32_t company_id) {
for (uint8_t i = 0; i < AVCT_NUM_CONN; i++) {
- LOG_INFO("%s: handle:%d, update cback:0x%0x", __func__, i, company_id);
+ log::info("handle:{}, update cback:0x{:0x}", i, company_id);
if (avrc_cb.ccb[i].company_id == company_id) {
avrc_cb.ccb[i].ctrl_cback.Run(i, AVRC_CLOSE_IND_EVT, 0, addr);
}
diff --git a/system/stack/avrc/avrc_bld_ct.cc b/system/stack/avrc/avrc_bld_ct.cc
index 8ac2569..b619bf0 100644
--- a/system/stack/avrc/avrc_bld_ct.cc
+++ b/system/stack/avrc/avrc_bld_ct.cc
@@ -18,6 +18,7 @@
#define LOG_TAG "avrcp"
+#include <bluetooth/log.h>
#include <string.h>
#include "avrc_api.h"
@@ -29,6 +30,8 @@
#include "stack/include/bt_hdr.h"
#include "stack/include/bt_types.h"
+using namespace bluetooth;
+
/*****************************************************************************
* Global data
****************************************************************************/
@@ -46,7 +49,7 @@
static tAVRC_STS avrc_bld_next_cmd(tAVRC_NEXT_CMD* p_cmd, BT_HDR* p_pkt) {
uint8_t *p_data, *p_start;
- LOG_VERBOSE("avrc_bld_next_cmd");
+ log::verbose("avrc_bld_next_cmd");
/* get the existing length, if any, and also the num attributes */
p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
@@ -78,7 +81,7 @@
BT_HDR* p_pkt) {
uint8_t *p_data, *p_start;
- LOG_VERBOSE("avrc_bld_set_abs_volume_cmd");
+ log::verbose("avrc_bld_set_abs_volume_cmd");
/* get the existing length, if any, and also the num attributes */
p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
p_data = p_start + 2; /* pdu + rsvd */
@@ -103,7 +106,7 @@
uint32_t event_param) {
uint8_t *p_data, *p_start;
- LOG_VERBOSE("avrc_bld_register_notifn");
+ log::verbose("avrc_bld_register_notifn");
/* get the existing length, if any, and also the num attributes */
// Set the notify value
p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
@@ -127,7 +130,7 @@
*
******************************************************************************/
static tAVRC_STS avrc_bld_get_capability_cmd(BT_HDR* p_pkt, uint8_t cap_id) {
- LOG_VERBOSE("avrc_bld_get_capability_cmd");
+ log::verbose("avrc_bld_get_capability_cmd");
uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
uint8_t* p_data = p_start + 2; /* pdu + rsvd */
/* add fixed length 1 -*/
@@ -148,7 +151,7 @@
*
******************************************************************************/
static tAVRC_STS avrc_bld_list_player_app_attr_cmd(BT_HDR* p_pkt) {
- LOG_VERBOSE("avrc_bld_list_player_app_attr_cmd");
+ log::verbose("avrc_bld_list_player_app_attr_cmd");
uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
uint8_t* p_data = p_start + 2; /* pdu + rsvd */
/* add fixed length 1 -*/
@@ -169,7 +172,7 @@
******************************************************************************/
static tAVRC_STS avrc_bld_list_player_app_values_cmd(BT_HDR* p_pkt,
uint8_t attrib_id) {
- LOG_VERBOSE("avrc_bld_list_player_app_values_cmd");
+ log::verbose("avrc_bld_list_player_app_values_cmd");
uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
uint8_t* p_data = p_start + 2; /* pdu + rsvd */
/* add fixed length 1 -*/
@@ -192,7 +195,7 @@
******************************************************************************/
static tAVRC_STS avrc_bld_get_current_player_app_values_cmd(
BT_HDR* p_pkt, uint8_t num_attrib_id, uint8_t* attrib_ids) {
- LOG_VERBOSE("avrc_bld_get_current_player_app_values_cmd");
+ log::verbose("avrc_bld_get_current_player_app_values_cmd");
uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
uint8_t* p_data = p_start + 2; /* pdu + rsvd */
uint8_t param_len =
@@ -220,7 +223,7 @@
******************************************************************************/
static tAVRC_STS avrc_bld_set_current_player_app_values_cmd(
BT_HDR* p_pkt, uint8_t num_attrib_id, tAVRC_APP_SETTING* p_val) {
- LOG_VERBOSE("avrc_bld_set_current_player_app_values_cmd");
+ log::verbose("avrc_bld_set_current_player_app_values_cmd");
uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
uint8_t* p_data = p_start + 2; /* pdu + rsvd */
/* we have to store attrib- value pair
@@ -251,7 +254,7 @@
******************************************************************************/
static tAVRC_STS avrc_bld_get_player_app_setting_attr_text_cmd(
BT_HDR* p_pkt, tAVRC_GET_APP_ATTR_TXT_CMD* p_cmd) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
uint8_t* p_data = p_start + 2; /* pdu + rsvd */
@@ -280,7 +283,7 @@
******************************************************************************/
static tAVRC_STS avrc_bld_get_player_app_setting_value_text_cmd(
BT_HDR* p_pkt, tAVRC_GET_APP_VAL_TXT_CMD* p_cmd) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
uint8_t* p_data = p_start + 2; /* pdu + rsvd */
@@ -309,7 +312,7 @@
static tAVRC_STS avrc_bld_get_element_attr_cmd(BT_HDR* p_pkt,
uint8_t num_attrib,
uint32_t* attrib_ids) {
- LOG_VERBOSE("avrc_bld_get_element_attr_cmd");
+ log::verbose("avrc_bld_get_element_attr_cmd");
uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
uint8_t* p_data = p_start + 2; /* pdu + rsvd */
/* we have to store attrib- value pair
@@ -341,7 +344,7 @@
******************************************************************************/
static tAVRC_STS avrc_bld_play_item_cmd(BT_HDR* p_pkt, uint8_t scope,
uint8_t* uid, uint16_t uid_counter) {
- LOG_VERBOSE("avrc_bld_get_element_attr_cmd");
+ log::verbose("avrc_bld_get_element_attr_cmd");
uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
uint8_t* p_data = p_start + 2; /* pdu + rsvd */
/* add fixed length 11 */
@@ -367,7 +370,7 @@
*
******************************************************************************/
static tAVRC_STS avrc_bld_get_play_status_cmd(BT_HDR* p_pkt) {
- LOG_VERBOSE("avrc_bld_list_player_app_attr_cmd");
+ log::verbose("avrc_bld_list_player_app_attr_cmd");
uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
uint8_t* p_data = p_start + 2; /* pdu + rsvd */
/* add fixed length 0 -*/
@@ -388,8 +391,8 @@
******************************************************************************/
static tAVRC_STS avrc_bld_get_folder_items_cmd(BT_HDR* p_pkt,
const tAVRC_GET_ITEMS_CMD* cmd) {
- LOG_VERBOSE(
- "avrc_bld_get_folder_items_cmd scope %d, start_item %d, end_item %d",
+ log::verbose(
+ "avrc_bld_get_folder_items_cmd scope {}, start_item {}, end_item {}",
cmd->scope, cmd->start_item, cmd->end_item);
uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
/* This is where the PDU specific for AVRC starts
@@ -420,7 +423,7 @@
******************************************************************************/
static tAVRC_STS avrc_bld_change_folder_cmd(BT_HDR* p_pkt,
const tAVRC_CHG_PATH_CMD* cmd) {
- LOG_VERBOSE("avrc_bld_change_folder_cmd");
+ log::verbose("avrc_bld_change_folder_cmd");
uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
/* This is where the PDU specific for AVRC starts
* AVRCP Spec 1.4 section 22.19 */
@@ -438,7 +441,7 @@
}
static tAVRC_STS avrc_bld_get_item_attributes_cmd(
BT_HDR* p_pkt, const tAVRC_GET_ATTRS_CMD* cmd) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
/* This is where the PDU specific for AVRC starts
* AVRCP Spec 1.4 section 22.19 */
@@ -466,7 +469,7 @@
******************************************************************************/
static tAVRC_STS avrc_bld_set_browsed_player_cmd(
BT_HDR* p_pkt, const tAVRC_SET_BR_PLAYER_CMD* cmd) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
/* This is where the PDU specific for AVRC starts
* AVRCP Spec 1.4 section 22.19 */
@@ -493,7 +496,7 @@
******************************************************************************/
static tAVRC_STS avrc_bld_set_addressed_player_cmd(
BT_HDR* p_pkt, const tAVRC_SET_ADDR_PLAYER_CMD* cmd) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
/* get the existing length, if any, and also the num attributes */
uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
uint8_t* p_data = p_start + 2; /* pdu + rsvd */
@@ -521,8 +524,8 @@
static BT_HDR* avrc_bld_init_cmd_buffer(tAVRC_COMMAND* p_cmd) {
uint16_t chnl = AVCT_DATA_CTRL;
uint8_t opcode = avrc_opcode_from_pdu(p_cmd->pdu);
- LOG_VERBOSE("avrc_bld_init_cmd_buffer: pdu=%x, opcode=%x", p_cmd->pdu,
- opcode);
+ log::verbose("avrc_bld_init_cmd_buffer: pdu={:x}, opcode={:x}", p_cmd->pdu,
+ opcode);
uint16_t offset = 0;
switch (opcode) {
@@ -583,19 +586,19 @@
tAVRC_STS AVRC_BldCommand(tAVRC_COMMAND* p_cmd, BT_HDR** pp_pkt) {
tAVRC_STS status = AVRC_STS_BAD_PARAM;
bool alloc = false;
- LOG_VERBOSE("AVRC_BldCommand: pdu=%x status=%x", p_cmd->cmd.pdu,
- p_cmd->cmd.status);
+ log::verbose("AVRC_BldCommand: pdu={:x} status={:x}", p_cmd->cmd.pdu,
+ p_cmd->cmd.status);
if (!p_cmd || !pp_pkt) {
- LOG_VERBOSE(
- "AVRC_BldCommand. Invalid parameters passed. p_cmd=%p, pp_pkt=%p",
- p_cmd, pp_pkt);
+ log::verbose(
+ "AVRC_BldCommand. Invalid parameters passed. p_cmd={}, pp_pkt={}",
+ fmt::ptr(p_cmd), fmt::ptr(pp_pkt));
return AVRC_STS_BAD_PARAM;
}
if (*pp_pkt == NULL) {
*pp_pkt = avrc_bld_init_cmd_buffer(p_cmd);
if (*pp_pkt == NULL) {
- LOG_VERBOSE("AVRC_BldCommand: Failed to initialize command buffer");
+ log::verbose("AVRC_BldCommand: Failed to initialize command buffer");
return AVRC_STS_INTERNAL_ERR;
}
alloc = true;
@@ -684,6 +687,6 @@
osi_free(p_pkt);
*pp_pkt = NULL;
}
- LOG_VERBOSE("AVRC_BldCommand: returning %d", status);
+ log::verbose("AVRC_BldCommand: returning {}", status);
return status;
}
diff --git a/system/stack/avrc/avrc_bld_tg.cc b/system/stack/avrc/avrc_bld_tg.cc
index 304f250..0fa9cf2 100644
--- a/system/stack/avrc/avrc_bld_tg.cc
+++ b/system/stack/avrc/avrc_bld_tg.cc
@@ -17,7 +17,7 @@
******************************************************************************/
#define LOG_TAG "avrcp"
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include <string.h>
#include "avrc_api.h"
@@ -32,6 +32,8 @@
#include "stack/include/bt_hdr.h"
#include "stack/include/bt_types.h"
+using namespace bluetooth;
+
/*****************************************************************************
* Global data
****************************************************************************/
@@ -65,12 +67,12 @@
tAVRC_STS status = AVRC_STS_NO_ERROR;
if (!(AVRC_IS_VALID_CAP_ID(p_rsp->capability_id))) {
- LOG_ERROR("%s bad parameter. p_rsp: %p", __func__, p_rsp);
+ log::error("bad parameter. p_rsp: {}", fmt::ptr(p_rsp));
status = AVRC_STS_BAD_PARAM;
return status;
}
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
/* get the existing length, if any, and also the num attributes */
p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
p_data = p_len = p_start + 2; /* pdu + rsvd */
@@ -129,7 +131,7 @@
uint16_t len = 0;
uint8_t xx;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
/* get the existing length, if any, and also the num attributes */
p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
p_data = p_len = p_start + 2; /* pdu + rsvd */
@@ -175,7 +177,7 @@
uint8_t xx;
uint16_t len;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
p_data = p_len = p_start + 2; /* pdu + rsvd */
@@ -220,11 +222,11 @@
uint8_t xx;
if (!p_rsp->p_vals) {
- LOG_ERROR("%s NULL parameter", __func__);
+ log::error("NULL parameter");
return AVRC_STS_BAD_PARAM;
}
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
/* get the existing length, if any, and also the num attributes */
p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
p_data = p_len = p_start + 2; /* pdu + rsvd */
@@ -268,7 +270,7 @@
static tAVRC_STS avrc_bld_set_app_setting_value_rsp(
UNUSED_ATTR tAVRC_RSP* p_rsp, UNUSED_ATTR BT_HDR* p_pkt) {
/* nothing to be added. */
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
return AVRC_STS_NO_ERROR;
}
@@ -292,7 +294,7 @@
uint8_t num_added = 0;
if (!p_rsp->p_attrs) {
- LOG_ERROR("%s NULL parameter", __func__);
+ log::error("NULL parameter");
return AVRC_STS_BAD_PARAM;
}
/* get the existing length, if any, and also the num attributes */
@@ -317,14 +319,14 @@
for (xx = 0; xx < p_rsp->num_attr; xx++) {
if (len_left < (p_rsp->p_attrs[xx].str_len + 4)) {
- LOG_ERROR("%s out of room (str_len:%d, left:%d)", __func__,
- p_rsp->p_attrs[xx].str_len, len_left);
+ log::error("out of room (str_len:{}, left:{})",
+ p_rsp->p_attrs[xx].str_len, len_left);
p_rsp->num_attr = num_added;
sts = AVRC_STS_INTERNAL_ERR;
break;
}
if (!p_rsp->p_attrs[xx].str_len || !p_rsp->p_attrs[xx].p_str) {
- LOG_ERROR("%s NULL attr text[%d]", __func__, xx);
+ log::error("NULL attr text[{}]", xx);
continue;
}
UINT8_TO_BE_STREAM(p_data, p_rsp->p_attrs[xx].attr_id);
@@ -355,7 +357,7 @@
******************************************************************************/
static tAVRC_STS avrc_bld_get_app_setting_attr_text_rsp(
tAVRC_GET_APP_ATTR_TXT_RSP* p_rsp, BT_HDR* p_pkt) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
return avrc_bld_app_setting_text_rsp(p_rsp, p_pkt);
}
@@ -372,7 +374,7 @@
******************************************************************************/
static tAVRC_STS avrc_bld_get_app_setting_value_text_rsp(
tAVRC_GET_APP_ATTR_TXT_RSP* p_rsp, BT_HDR* p_pkt) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
return avrc_bld_app_setting_text_rsp(p_rsp, p_pkt);
}
@@ -390,7 +392,7 @@
static tAVRC_STS avrc_bld_inform_charset_rsp(UNUSED_ATTR tAVRC_RSP* p_rsp,
UNUSED_ATTR BT_HDR* p_pkt) {
/* nothing to be added. */
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
return AVRC_STS_NO_ERROR;
}
@@ -408,7 +410,7 @@
static tAVRC_STS avrc_bld_inform_battery_status_rsp(
UNUSED_ATTR tAVRC_RSP* p_rsp, UNUSED_ATTR BT_HDR* p_pkt) {
/* nothing to be added. */
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
return AVRC_STS_NO_ERROR;
}
@@ -417,12 +419,12 @@
int remaining_buffer_capacity,
uint8_t** pp_data,
uint8_t* p_attribute_count) {
- LOG_VERBOSE("%s num_attrs: %d, remaining_buffer_capacity: %d", __func__,
- num_attrs, remaining_buffer_capacity);
+ log::verbose("num_attrs: {}, remaining_buffer_capacity: {}", num_attrs,
+ remaining_buffer_capacity);
uint8_t* p_data = *pp_data;
/* Fill in the Attribute ID, Character Set, Length and Values */
for (int index = 0; index < num_attrs; index++) {
- LOG_VERBOSE("%s attr id[%d]: %d", __func__, index, p_attrs[index].attr_id);
+ log::verbose("attr id[{}]: {}", index, p_attrs[index].attr_id);
CHECK(AVRC_IS_VALID_MEDIA_ATTRIBUTE(p_attrs[index].attr_id));
if (!p_attrs[index].name.p_str) {
p_attrs[index].name.str_len = 0;
@@ -430,17 +432,15 @@
/* 8 is the size of attr_id, char set and str_len */
remaining_buffer_capacity -= 8;
if (remaining_buffer_capacity < 0) {
- LOG_WARN(
- "%s not enough buffer space for attr_id[%d]: %d,"
- " skipping %d attributes",
- __func__, index, p_attrs[index].attr_id, num_attrs - index);
+ log::warn(
+ "not enough buffer space for attr_id[{}]: {}, skipping {} attributes",
+ index, p_attrs[index].attr_id, num_attrs - index);
break;
}
if (remaining_buffer_capacity < p_attrs[index].name.str_len) {
- LOG_WARN(
- "%s not enough buffer space for attr_id[%d]: %d,"
- " truncating attribute",
- __func__, index, p_attrs[index].attr_id);
+ log::warn(
+ "not enough buffer space for attr_id[{}]: {}, truncating attribute",
+ index, p_attrs[index].attr_id);
p_attrs[index].name.str_len = remaining_buffer_capacity;
remaining_buffer_capacity = 0;
}
@@ -453,8 +453,8 @@
(*p_attribute_count)++;
}
*pp_data = p_data;
- LOG_VERBOSE("%s filled attributes, remaining_buffer_capacity: %d", __func__,
- remaining_buffer_capacity);
+ log::verbose("filled attributes, remaining_buffer_capacity: {}",
+ remaining_buffer_capacity);
}
/*******************************************************************************
@@ -470,17 +470,17 @@
******************************************************************************/
static tAVRC_STS avrc_bld_get_elem_attrs_rsp(tAVRC_GET_ATTRS_RSP* p_rsp,
BT_HDR* p_pkt) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
if (!p_rsp->p_attrs) {
- LOG_ERROR("%s NULL p_attrs", __func__);
+ log::error("NULL p_attrs");
return AVRC_STS_BAD_PARAM;
}
/* Figure out how much we have left in current buffer */
int remaining_buffer_capacity =
BT_DEFAULT_BUFFER_SIZE - BT_HDR_SIZE - p_pkt->offset;
if (remaining_buffer_capacity < 5) {
- LOG_ERROR("%d not enough buffer for packet header",
- remaining_buffer_capacity);
+ log::error("{} not enough buffer for packet header",
+ remaining_buffer_capacity);
return AVRC_STS_INTERNAL_ERR;
}
/* Get to the beginning of PDU */
@@ -504,7 +504,7 @@
remaining_buffer_capacity -= p_data - p_pdu_start;
;
if (remaining_buffer_capacity < 0) {
- LOG_ERROR("%s not enough buffer capacity for response", __func__);
+ log::error("not enough buffer capacity for response");
return AVRC_STS_BAD_PARAM;
}
/* Fill in the Attribute ID, Character Set, Length and Values */
@@ -532,7 +532,7 @@
BT_HDR* p_pkt) {
uint8_t *p_data, *p_start;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
p_data = p_start + 2;
@@ -564,7 +564,7 @@
uint8_t xx;
tAVRC_STS status = AVRC_STS_NO_ERROR;
- LOG_VERBOSE("%s event_id %d", __func__, p_rsp->event_id);
+ log::verbose("event_id {}", p_rsp->event_id);
p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
p_data = p_len = p_start + 2; /* pdu + rsvd */
@@ -579,7 +579,7 @@
UINT8_TO_BE_STREAM(p_data, p_rsp->param.play_status);
len = 2;
} else {
- LOG_ERROR("%s bad play state", __func__);
+ log::error("bad play state");
status = AVRC_STS_BAD_PARAM;
}
break;
@@ -606,7 +606,7 @@
UINT8_TO_BE_STREAM(p_data, p_rsp->param.battery_status);
len = 2;
} else {
- LOG_ERROR("%s bad battery status", __func__);
+ log::error("bad battery status");
status = AVRC_STS_BAD_PARAM;
}
break;
@@ -616,7 +616,7 @@
UINT8_TO_BE_STREAM(p_data, p_rsp->param.system_status);
len = 2;
} else {
- LOG_ERROR("%s bad system status", __func__);
+ log::error("bad system status");
status = AVRC_STS_BAD_PARAM;
}
break;
@@ -636,7 +636,7 @@
UINT8_TO_BE_STREAM(p_data,
p_rsp->param.player_setting.attr_value[xx]);
} else {
- LOG_ERROR("%s bad player app seeting attribute or value", __func__);
+ log::error("bad player app seeting attribute or value");
status = AVRC_STS_BAD_PARAM;
break;
}
@@ -664,7 +664,7 @@
default:
status = AVRC_STS_BAD_PARAM;
- LOG_ERROR("%s unknown event_id", __func__);
+ log::error("unknown event_id");
}
UINT16_TO_BE_STREAM(p_len, len);
@@ -691,7 +691,7 @@
UINT16_TO_BE_STREAM(p_data, 0x0001); /* only one attribute to be sent */
UINT8_TO_BE_STREAM(p_data, p_rsp->target_pdu);
- LOG_VERBOSE("%s: target_pdu: 0x%02x", __func__, p_rsp->target_pdu);
+ log::verbose("target_pdu: 0x{:02x}", p_rsp->target_pdu);
return AVRC_STS_NO_ERROR;
}
@@ -706,7 +706,7 @@
*****************************************************************************/
static tAVRC_STS avrc_bld_set_absolute_volume_rsp(uint8_t abs_vol,
BT_HDR* p_pkt) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
/* To calculate length */
uint8_t* p_data = p_start + 2;
@@ -730,10 +730,10 @@
******************************************************************************/
tAVRC_STS avrc_bld_group_navigation_rsp(uint16_t navi_id, BT_HDR* p_pkt) {
if (!AVRC_IS_VALID_GROUP(navi_id)) {
- LOG_ERROR("%s bad navigation op id: %d", __func__, navi_id);
+ log::error("bad navigation op id: {}", navi_id);
return AVRC_STS_BAD_PARAM;
}
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
uint8_t* p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
UINT16_TO_BE_STREAM(p_data, navi_id);
p_pkt->len = 2;
@@ -754,8 +754,8 @@
uint8_t* p_data;
uint8_t opcode = p_rsp->opcode;
- LOG_VERBOSE("%s: status=%d, pdu:x%x, opcode=%x", __func__, p_rsp->status,
- p_rsp->pdu, opcode);
+ log::verbose("status={}, pdu:x{:x}, opcode={:x}", p_rsp->status, p_rsp->pdu,
+ opcode);
if (opcode == AVRC_OP_BROWSE) {
p_data = p_start + 1;
@@ -769,7 +769,7 @@
} else {
p_data = p_start + 2;
}
- LOG_VERBOSE("%s pdu:x%x, Opcode:%x", __func__, *p_start, opcode);
+ log::verbose("pdu:x{:x}, Opcode:{:x}", *p_start, opcode);
UINT16_TO_BE_STREAM(p_data, 1);
UINT8_TO_BE_STREAM(p_data, p_rsp->status);
p_pkt->len = p_data - p_start;
@@ -792,7 +792,7 @@
******************************************************************************/
static tAVRC_STS avrc_bld_ctrl_status_rsp(tAVRC_RSP* p_rsp, BT_HDR* p_pkt) {
uint8_t* p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
- LOG_VERBOSE("pdu:x%x", *p_start);
+ log::verbose("pdu:x{:x}", *p_start);
/* To calculate length */
uint8_t* p_data = p_start + 2; /* pdu + rsvd */
@@ -815,7 +815,7 @@
*
******************************************************************************/
static tAVRC_STS avrc_bld_set_addr_player_rsp(tAVRC_RSP* p_rsp, BT_HDR* p_pkt) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
return avrc_bld_ctrl_status_rsp(p_rsp, p_pkt);
}
@@ -849,7 +849,7 @@
len_left = mtu;
}
len_left = len_left - p_pkt->offset - p_pkt->len;
- LOG_VERBOSE("len_left:%d, mtu:%d ", len_left, mtu);
+ log::verbose("len_left:{}, mtu:{} ", len_left, mtu);
/* get the existing length, if any, and also the num attributes */
p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
@@ -925,7 +925,7 @@
uint16_t item_count;
uint16_t mtu;
bool multi_items_add_fail = false;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
/* make sure the given buffer can accomodate this response */
len_left = BT_DEFAULT_BUFFER_SIZE - BT_HDR_SIZE;
@@ -937,7 +937,7 @@
// Version 5.3 | Vol 3, Part A, Chapter 5
// MTU may be controlled by the peer
if (len_left < p_pkt->offset + p_pkt->len) {
- LOG_ERROR("memory not enough (len_left=%d)", len_left);
+ log::error("memory not enough (len_left={})", len_left);
return AVRC_STS_INTERNAL_ERR;
}
@@ -959,7 +959,7 @@
len = 5;
if (len_left < 5) {
- LOG_ERROR("memory not enough (len_left=%d)", len_left);
+ log::error("memory not enough (len_left={})", len_left);
return AVRC_STS_INTERNAL_ERR;
}
@@ -969,7 +969,7 @@
p = p_num;
BE_STREAM_TO_UINT16(item_count, p);
}
- LOG_VERBOSE("len:%d, len_left:%d, num:%d", len, len_left, item_count);
+ log::verbose("len:{}, len_left:{}, num:{}", len, len_left, item_count);
/* min len required = item_type(1) + item len(2) + min item (14) = 17 */
for (xx = 0;
@@ -1092,8 +1092,8 @@
status = AVRC_STS_BAD_PARAM;
break;
}
- LOG_VERBOSE("len:%d, len_left:%d, num:%d, item_len:%zu", len, len_left,
- item_count, item_len);
+ log::verbose("len:{}, len_left:{}, num:{}, item_len:{}", len, len_left,
+ item_count, item_len);
} /* for item_count */
UINT16_TO_BE_STREAM(p_num, item_count);
@@ -1147,9 +1147,9 @@
******************************************************************************/
static tAVRC_STS avrc_bld_get_item_attrs_rsp(tAVRC_GET_ATTRS_RSP* p_rsp,
BT_HDR* p_pkt) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
if (!p_rsp->p_attrs) {
- LOG_ERROR("%s NULL p_attrs", __func__);
+ log::error("NULL p_attrs");
return AVRC_STS_BAD_PARAM;
}
/* Figure out how much we have left in current buffer */
@@ -1163,11 +1163,11 @@
if (remaining_buffer_capacity > mtu) {
remaining_buffer_capacity = mtu;
}
- LOG_VERBOSE("%s: remaining_buffer_capacity:%d, mtu:%d", __func__,
- remaining_buffer_capacity, mtu);
+ log::verbose("remaining_buffer_capacity:{}, mtu:{}",
+ remaining_buffer_capacity, mtu);
if (remaining_buffer_capacity < 5) {
- LOG_ERROR("%s: not enough space for packet header, remaining:%d < 5",
- __func__, remaining_buffer_capacity);
+ log::error("not enough space for packet header, remaining:{} < 5",
+ remaining_buffer_capacity);
return AVRC_STS_INTERNAL_ERR;
}
/* Get to the beginning of PDU */
@@ -1225,7 +1225,7 @@
BT_HDR* p_pkt) {
uint8_t *p_data, *p_start, *p_len;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
/* get the existing length, if any, and also the num attributes */
p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
p_data = p_len = p_start + 1; /* pdu */
@@ -1262,7 +1262,7 @@
static tAVRC_STS avrc_bld_search_rsp(tAVRC_SEARCH_RSP* p_rsp, BT_HDR* p_pkt) {
uint8_t *p_data, *p_start, *p_len;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
/* get the existing length, if any, and also the num attributes */
p_start = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
p_data = p_len = p_start + 1; /* pdu */
@@ -1287,7 +1287,7 @@
*
******************************************************************************/
static tAVRC_STS avrc_bld_play_item_rsp(tAVRC_RSP* p_rsp, BT_HDR* p_pkt) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
return avrc_bld_ctrl_status_rsp(p_rsp, p_pkt);
}
@@ -1303,7 +1303,7 @@
******************************************************************************/
static tAVRC_STS avrc_bld_add_to_now_playing_rsp(tAVRC_RSP* p_rsp,
BT_HDR* p_pkt) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
return avrc_bld_ctrl_status_rsp(p_rsp, p_pkt);
}
@@ -1322,12 +1322,12 @@
uint16_t chnl = AVCT_DATA_CTRL;
uint8_t opcode = avrc_opcode_from_pdu(p_rsp->pdu);
- LOG_VERBOSE("%s: pdu=%x, opcode=%x/%x", __func__, p_rsp->pdu, opcode,
- p_rsp->rsp.opcode);
+ log::verbose("pdu={:x}, opcode={:x}/{:x}", p_rsp->pdu, opcode,
+ p_rsp->rsp.opcode);
if (opcode != p_rsp->rsp.opcode && p_rsp->rsp.status != AVRC_STS_NO_ERROR &&
avrc_is_valid_opcode(p_rsp->rsp.opcode)) {
opcode = p_rsp->rsp.opcode;
- LOG_VERBOSE("%s opcode=%x", __func__, opcode);
+ log::verbose("opcode={:x}", opcode);
}
switch (opcode) {
@@ -1395,15 +1395,15 @@
uint16_t peer_mtu;
if (!p_rsp || !pp_pkt) {
- LOG_VERBOSE("%s Invalid parameters passed. p_rsp=%p, pp_pkt=%p", __func__,
- p_rsp, pp_pkt);
+ log::verbose("Invalid parameters passed. p_rsp={}, pp_pkt={}",
+ fmt::ptr(p_rsp), fmt::ptr(pp_pkt));
return AVRC_STS_BAD_PARAM;
}
if (*pp_pkt == NULL) {
*pp_pkt = avrc_bld_init_rsp_buffer(p_rsp);
if (*pp_pkt == NULL) {
- LOG_VERBOSE("%s Failed to initialize response buffer", __func__);
+ log::verbose("Failed to initialize response buffer");
return AVRC_STS_INTERNAL_ERR;
}
@@ -1418,8 +1418,7 @@
status = AVRC_STS_NO_ERROR;
p_pkt = *pp_pkt;
- LOG_VERBOSE("%s pdu=%x status=%x", __func__, p_rsp->rsp.pdu,
- p_rsp->rsp.status);
+ log::verbose("pdu={:x} status={:x}", p_rsp->rsp.pdu, p_rsp->rsp.status);
if (p_rsp->rsp.status != AVRC_STS_NO_ERROR) {
return (avrc_bld_rejected_rsp(&p_rsp->rsp, p_pkt));
}
@@ -1537,6 +1536,6 @@
osi_free(p_pkt);
*pp_pkt = NULL;
}
- LOG_VERBOSE("%s returning %d", __func__, status);
+ log::verbose("returning {}", status);
return status;
}
diff --git a/system/stack/avrc/avrc_opt.cc b/system/stack/avrc/avrc_opt.cc
index ec097bf..09e623b 100644
--- a/system/stack/avrc/avrc_opt.cc
+++ b/system/stack/avrc/avrc_opt.cc
@@ -21,7 +21,7 @@
* Interface to AVRCP optional commands
*
******************************************************************************/
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include <string.h>
#include "avrc_api.h"
@@ -30,6 +30,8 @@
#include "osi/include/allocator.h"
#include "stack/include/bt_hdr.h"
+using namespace bluetooth;
+
/******************************************************************************
*
* Function avrc_vendor_msg
@@ -40,7 +42,7 @@
* p_msg: Pointer to VENDOR DEPENDENT message structure.
*
* Output Parameters:
-* None.
+ * None.
*
* Returns pointer to a valid GKI buffer if successful.
* NULL if p_msg is NULL.
diff --git a/system/stack/avrc/avrc_pars_ct.cc b/system/stack/avrc/avrc_pars_ct.cc
index aa4f3fc..3179204 100644
--- a/system/stack/avrc/avrc_pars_ct.cc
+++ b/system/stack/avrc/avrc_pars_ct.cc
@@ -15,6 +15,7 @@
* limitations under the License.
*
******************************************************************************/
+#include <bluetooth/log.h>
#include <string.h>
#include "avrc_api.h"
@@ -25,6 +26,8 @@
#include "osi/include/osi.h"
#include "stack/include/bt_types.h"
+using namespace bluetooth;
+
/*****************************************************************************
* Global data
****************************************************************************/
@@ -55,26 +58,25 @@
if (p_msg->p_vendor_data == NULL) return AVRC_STS_INTERNAL_ERR;
if (p_msg->vendor_len < 4) {
- LOG_WARN("%s: message length %d too short: must be at least 4", __func__,
- p_msg->vendor_len);
+ log::warn("message length {} too short: must be at least 4",
+ p_msg->vendor_len);
return AVRC_STS_INTERNAL_ERR;
}
p = p_msg->p_vendor_data;
BE_STREAM_TO_UINT8(p_result->pdu, p);
p++; /* skip the reserved/packe_type byte */
BE_STREAM_TO_UINT16(len, p);
- LOG_VERBOSE("%s ctype:0x%x pdu:0x%x, len:%d/0x%x vendor_len=0x%x", __func__,
- p_msg->hdr.ctype, p_result->pdu, len, len, p_msg->vendor_len);
+ log::verbose("ctype:0x{:x} pdu:0x{:x}, len:{}/0x{:x} vendor_len=0x{:x}",
+ p_msg->hdr.ctype, p_result->pdu, len, len, p_msg->vendor_len);
if (p_msg->vendor_len < len + 4) {
- LOG_WARN("%s: message length %d too short: must be at least %d", __func__,
- p_msg->vendor_len, len + 4);
+ log::warn("message length {} too short: must be at least {}",
+ p_msg->vendor_len, len + 4);
return AVRC_STS_INTERNAL_ERR;
}
if (p_msg->hdr.ctype == AVRC_RSP_REJ) {
if (len < 1) {
- LOG_WARN("%s: invalid parameter length %d: must be at least 1", __func__,
- len);
+ log::warn("invalid parameter length {}: must be at least 1", len);
return AVRC_STS_INTERNAL_ERR;
}
p_result->rsp.status = *p;
@@ -101,8 +103,7 @@
break;
}
if (len < 1) {
- LOG_WARN("%s: invalid parameter length %d: must be at least 1",
- __func__, len);
+ log::warn("invalid parameter length {}: must be at least 1", len);
return AVRC_STS_INTERNAL_ERR;
}
BE_STREAM_TO_UINT8(eventid, p);
@@ -112,16 +113,15 @@
AVRC_RSP_REJ == p_msg->hdr.ctype ||
AVRC_RSP_NOT_IMPL == p_msg->hdr.ctype)) {
if (len < 2) {
- LOG_WARN("%s: invalid parameter length %d: must be at least 2",
- __func__, len);
+ log::warn("invalid parameter length {}: must be at least 2", len);
return AVRC_STS_INTERNAL_ERR;
}
p_result->reg_notif.status = p_msg->hdr.ctype;
p_result->reg_notif.event_id = eventid;
BE_STREAM_TO_UINT8(p_result->reg_notif.param.volume, p);
}
- LOG_VERBOSE("%s PDU reg notif response:event %x, volume %x", __func__,
- eventid, p_result->reg_notif.param.volume);
+ log::verbose("PDU reg notif response:event {:x}, volume {:x}", eventid,
+ p_result->reg_notif.param.volume);
break;
default:
status = AVRC_STS_BAD_CMD;
@@ -201,8 +201,7 @@
return AVRC_STS_NO_ERROR;
length_error:
- LOG_WARN("%s: invalid parameter length %d: must be at least %d", __func__,
- len, min_len);
+ log::warn("invalid parameter length {}: must be at least {}", len, min_len);
return AVRC_STS_INTERNAL_ERR;
}
@@ -212,7 +211,7 @@
uint8_t pdu;
if (p_msg->browse_len == 0) {
- LOG_ERROR("%s length %d", __func__, p_msg->browse_len);
+ log::error("length {}", p_msg->browse_len);
return AVRC_STS_BAD_PARAM;
}
@@ -220,8 +219,8 @@
/* read the pdu */
if (p_msg->browse_len < 3) {
- LOG_WARN("%s: message length %d too short: must be at least 3", __func__,
- p_msg->browse_len);
+ log::warn("message length {} too short: must be at least 3",
+ p_msg->browse_len);
return AVRC_STS_BAD_PARAM;
}
BE_STREAM_TO_UINT8(pdu, p);
@@ -230,11 +229,11 @@
/* read the entire packet len */
BE_STREAM_TO_UINT16(pkt_len, p);
- LOG_VERBOSE("%s pdu:%d, pkt_len:%d", __func__, pdu, pkt_len);
+ log::verbose("pdu:{}, pkt_len:{}", pdu, pkt_len);
if (p_msg->browse_len < (pkt_len + 3)) {
- LOG_WARN("%s: message length %d too short: must be at least %d", __func__,
- p_msg->browse_len, pkt_len + 3);
+ log::warn("message length {} too short: must be at least {}",
+ p_msg->browse_len, pkt_len + 3);
return AVRC_STS_INTERNAL_ERR;
}
@@ -249,7 +248,7 @@
/* read the status */
BE_STREAM_TO_UINT8(get_item_rsp->status, p);
if (get_item_rsp->status != AVRC_STS_NO_ERROR) {
- LOG_WARN("%s returning error %d", __func__, get_item_rsp->status);
+ log::warn("returning error {}", get_item_rsp->status);
return get_item_rsp->status;
}
@@ -260,9 +259,9 @@
/* read the number of items */
BE_STREAM_TO_UINT16(get_item_rsp->item_count, p);
- LOG_VERBOSE("%s pdu %d status %d pkt_len %d uid counter %d item count %d",
- __func__, get_item_rsp->pdu, get_item_rsp->status, pkt_len,
- get_item_rsp->uid_counter, get_item_rsp->item_count);
+ log::verbose("pdu {} status {} pkt_len {} uid counter {} item count {}",
+ get_item_rsp->pdu, get_item_rsp->status, pkt_len,
+ get_item_rsp->uid_counter, get_item_rsp->item_count);
/* get each of the items */
get_item_rsp->p_item_list = (tAVRC_ITEM*)osi_calloc(
@@ -272,7 +271,7 @@
min_len += 1;
if (pkt_len < min_len) goto browse_length_error;
BE_STREAM_TO_UINT8(curr_item->item_type, p);
- LOG_VERBOSE("%s item type %d", __func__, curr_item->item_type);
+ log::verbose("item type {}", curr_item->item_type);
switch (curr_item->item_type) {
case AVRC_ITEM_PLAYER: {
/* Handle player */
@@ -297,11 +296,11 @@
player->name.p_str = (uint8_t*)osi_calloc(
(player->name.str_len + 1) * sizeof(uint8_t));
BE_STREAM_TO_ARRAY(p, player->name.p_str, player->name.str_len);
- LOG_VERBOSE(
- "%s type %d id %d mtype %d stype %d ps %d cs %d name len %d",
- __func__, curr_item->item_type, player->player_id,
- player->major_type, player->sub_type, player->play_status,
- player->name.charset_id, player->name.str_len);
+ log::verbose(
+ "type {} id {} mtype {} stype {} ps {} cs {} name len {}",
+ curr_item->item_type, player->player_id, player->major_type,
+ player->sub_type, player->play_status, player->name.charset_id,
+ player->name.str_len);
} break;
case AVRC_ITEM_FOLDER: {
@@ -325,9 +324,9 @@
folder->name.p_str = (uint8_t*)osi_calloc(
(folder->name.str_len + 1) * sizeof(uint8_t));
BE_STREAM_TO_ARRAY(p, folder->name.p_str, folder->name.str_len);
- LOG_VERBOSE("%s type %d playable %d cs %d name len %d", __func__,
- folder->type, folder->playable, folder->name.charset_id,
- folder->name.str_len);
+ log::verbose("type {} playable {} cs {} name len {}", folder->type,
+ folder->playable, folder->name.charset_id,
+ folder->name.str_len);
} break;
case AVRC_ITEM_MEDIA: {
@@ -351,9 +350,9 @@
BE_STREAM_TO_ARRAY(p, media->name.p_str, media->name.str_len);
BE_STREAM_TO_UINT8(media->attr_count, p);
- LOG_VERBOSE("%s media type %d charset id %d len %d attr ct %d",
- __func__, media->type, media->name.charset_id,
- media->name.str_len, media->attr_count);
+ log::verbose("media type {} charset id {} len {} attr ct {}",
+ media->type, media->name.charset_id,
+ media->name.str_len, media->attr_count);
media->p_attr_list = (tAVRC_ATTR_ENTRY*)osi_calloc(
media->attr_count * sizeof(tAVRC_ATTR_ENTRY));
@@ -372,19 +371,18 @@
attr_entry->name.str_len * sizeof(uint8_t));
BE_STREAM_TO_ARRAY(p, attr_entry->name.p_str,
attr_entry->name.str_len);
- LOG_VERBOSE("%s media attr id %d cs %d name len %d", __func__,
- attr_entry->attr_id, attr_entry->name.charset_id,
- attr_entry->name.str_len);
+ log::verbose("media attr id {} cs {} name len {}",
+ attr_entry->attr_id, attr_entry->name.charset_id,
+ attr_entry->name.str_len);
}
} break;
default:
- LOG_ERROR("%s item type not handled %d", __func__,
- curr_item->item_type);
+ log::error("item type not handled {}", curr_item->item_type);
return AVRC_STS_INTERNAL_ERR;
}
- LOG_VERBOSE("%s pkt_len %d min_len %d", __func__, pkt_len, min_len);
+ log::verbose("pkt_len {} min_len {}", pkt_len, min_len);
/* advance to populate the next item */
curr_item++;
@@ -403,9 +401,8 @@
/* Read the number of items in folder */
BE_STREAM_TO_UINT32(change_path_rsp->num_items, p);
- LOG_VERBOSE("%s pdu %d status %d item count %d", __func__,
- change_path_rsp->pdu, change_path_rsp->status,
- change_path_rsp->num_items);
+ log::verbose("pdu {} status {} item count {}", change_path_rsp->pdu,
+ change_path_rsp->status, change_path_rsp->num_items);
break;
}
@@ -432,9 +429,8 @@
attr_entry->name.p_str =
(uint8_t*)osi_malloc(attr_entry->name.str_len * sizeof(uint8_t));
BE_STREAM_TO_ARRAY(p, attr_entry->name.p_str, attr_entry->name.str_len);
- LOG_VERBOSE("%s media attr id %d cs %d name len %d", __func__,
- attr_entry->attr_id, attr_entry->name.charset_id,
- attr_entry->name.str_len);
+ log::verbose("media attr id {} cs {} name len {}", attr_entry->attr_id,
+ attr_entry->name.charset_id, attr_entry->name.str_len);
}
break;
@@ -450,18 +446,18 @@
BE_STREAM_TO_UINT8(set_br_pl_rsp->status, p);
if (set_br_pl_rsp->status != AVRC_STS_NO_ERROR) {
- LOG_ERROR(
- "%s Stopping further parsing because player not browsable sts %d",
- __func__, set_br_pl_rsp->status);
+ log::error(
+ "Stopping further parsing because player not browsable sts {}",
+ set_br_pl_rsp->status);
break;
}
BE_STREAM_TO_UINT16(set_br_pl_rsp->uid_counter, p);
BE_STREAM_TO_UINT32(set_br_pl_rsp->num_items, p);
BE_STREAM_TO_UINT16(set_br_pl_rsp->charset_id, p);
BE_STREAM_TO_UINT8(set_br_pl_rsp->folder_depth, p);
- LOG_VERBOSE(
- "%s AVRC_PDU_SET_BROWSED_PLAYER status %d items %d cs %d depth %d",
- __func__, set_br_pl_rsp->status, set_br_pl_rsp->num_items,
+ log::verbose(
+ "AVRC_PDU_SET_BROWSED_PLAYER status {} items {} cs {} depth {}",
+ set_br_pl_rsp->status, set_br_pl_rsp->num_items,
set_br_pl_rsp->charset_id, set_br_pl_rsp->folder_depth);
set_br_pl_rsp->p_folders = (tAVRC_NAME*)osi_calloc(
@@ -475,8 +471,8 @@
BE_STREAM_TO_UINT16(folder_name->str_len, p);
min_len += folder_name->str_len;
if (pkt_len < min_len) goto browse_length_error;
- LOG_VERBOSE("%s AVRC_PDU_SET_BROWSED_PLAYER item: %d len: %d", __func__,
- i, folder_name->str_len);
+ log::verbose("AVRC_PDU_SET_BROWSED_PLAYER item: {} len: {}", i,
+ folder_name->str_len);
folder_name->p_str =
(uint8_t*)osi_calloc((folder_name->str_len + 1) * sizeof(uint8_t));
BE_STREAM_TO_ARRAY(p, folder_name->p_str, folder_name->str_len);
@@ -485,14 +481,14 @@
}
default:
- LOG_ERROR("%s pdu %d not handled", __func__, pdu);
+ log::error("pdu {} not handled", pdu);
}
return status;
browse_length_error:
- LOG_WARN("%s: invalid parameter length %d: must be at least %d", __func__,
- pkt_len, min_len);
+ log::warn("invalid parameter length {}: must be at least {}", pkt_len,
+ min_len);
return AVRC_STS_BAD_CMD;
}
@@ -512,8 +508,8 @@
tAVRC_RESPONSE* p_result,
uint8_t* p_buf, uint16_t* buf_len) {
if (p_msg->vendor_len < 4) {
- LOG_WARN("%s: message length %d too short: must be at least 4", __func__,
- p_msg->vendor_len);
+ log::warn("message length {} too short: must be at least 4",
+ p_msg->vendor_len);
return AVRC_STS_INTERNAL_ERR;
}
@@ -524,11 +520,11 @@
uint16_t len;
uint32_t min_len = 0;
BE_STREAM_TO_UINT16(len, p);
- LOG_VERBOSE("%s ctype:0x%x pdu:0x%x, len:%d vendor_len=0x%x", __func__,
- p_msg->hdr.ctype, p_result->pdu, len, p_msg->vendor_len);
+ log::verbose("ctype:0x{:x} pdu:0x{:x}, len:{} vendor_len=0x{:x}",
+ p_msg->hdr.ctype, p_result->pdu, len, p_msg->vendor_len);
if (p_msg->vendor_len < len + 4) {
- LOG_WARN("%s: message length %d too short: must be at least %d", __func__,
- p_msg->vendor_len, len + 4);
+ log::warn("message length {} too short: must be at least {}",
+ p_msg->vendor_len, len + 4);
return AVRC_STS_INTERNAL_ERR;
}
/* Todo: Issue in handling reject, check */
@@ -557,8 +553,8 @@
if (len < min_len) goto length_error;
BE_STREAM_TO_UINT8(p_result->get_caps.capability_id, p);
BE_STREAM_TO_UINT8(p_result->get_caps.count, p);
- LOG_VERBOSE("%s cap id = %d, cap_count = %d ", __func__,
- p_result->get_caps.capability_id, p_result->get_caps.count);
+ log::verbose("cap id = {}, cap_count = {} ",
+ p_result->get_caps.capability_id, p_result->get_caps.count);
if (p_result->get_caps.capability_id == AVRC_CAP_COMPANY_ID) {
if (p_result->get_caps.count > AVRC_CAP_MAX_NUM_COMP_ID) {
return AVRC_STS_INTERNAL_ERR;
@@ -592,8 +588,7 @@
}
min_len += 1;
BE_STREAM_TO_UINT8(p_result->list_app_attr.num_attr, p);
- LOG_VERBOSE("%s attr count = %d ", __func__,
- p_result->list_app_attr.num_attr);
+ log::verbose("attr count = {} ", p_result->list_app_attr.num_attr);
if (p_result->list_app_attr.num_attr > AVRC_MAX_APP_ATTR_SIZE) {
p_result->list_app_attr.num_attr = AVRC_MAX_APP_ATTR_SIZE;
@@ -617,8 +612,7 @@
p_result->list_app_values.num_val = AVRC_MAX_APP_ATTR_SIZE;
}
- LOG_VERBOSE("%s value count = %d ", __func__,
- p_result->list_app_values.num_val);
+ log::verbose("value count = {} ", p_result->list_app_values.num_val);
min_len += p_result->list_app_values.num_val;
if (len < min_len) goto length_error;
for (int xx = 0; xx < p_result->list_app_values.num_val; xx++) {
@@ -633,8 +627,7 @@
}
min_len += 1;
BE_STREAM_TO_UINT8(p_result->get_cur_app_val.num_val, p);
- LOG_VERBOSE("%s attr count = %d ", __func__,
- p_result->get_cur_app_val.num_val);
+ log::verbose("attr count = {} ", p_result->get_cur_app_val.num_val);
if (p_result->get_cur_app_val.num_val > AVRC_MAX_APP_ATTR_SIZE) {
p_result->get_cur_app_val.num_val = AVRC_MAX_APP_ATTR_SIZE;
@@ -666,8 +659,7 @@
if (num_attrs > AVRC_MAX_APP_ATTR_SIZE) {
num_attrs = AVRC_MAX_APP_ATTR_SIZE;
}
- LOG_VERBOSE("%s attr count = %d ", __func__,
- p_result->get_app_attr_txt.num_attr);
+ log::verbose("attr count = {} ", p_result->get_app_attr_txt.num_attr);
p_result->get_app_attr_txt.num_attr = num_attrs;
p_result->get_app_attr_txt.p_attrs = (tAVRC_APP_SETTING_TEXT*)osi_calloc(
@@ -720,8 +712,7 @@
num_vals = AVRC_MAX_APP_ATTR_SIZE;
}
p_result->get_app_val_txt.num_attr = num_vals;
- LOG_VERBOSE("%s value count = %d ", __func__,
- p_result->get_app_val_txt.num_attr);
+ log::verbose("value count = {} ", p_result->get_app_val_txt.num_attr);
p_result->get_app_val_txt.p_attrs = (tAVRC_APP_SETTING_TEXT*)osi_calloc(
num_vals * sizeof(tAVRC_APP_SETTING_TEXT));
@@ -824,7 +815,7 @@
case AVRC_PDU_SET_ADDRESSED_PLAYER:
if (len != 1) {
- LOG_ERROR("%s pdu: %d len %d", __func__, p_result->pdu, len);
+ log::error("pdu: {} len {}", p_result->pdu, len);
return AVRC_STS_BAD_CMD;
}
BE_STREAM_TO_UINT8(p_result->rsp.status, p);
@@ -836,8 +827,7 @@
return AVRC_STS_NO_ERROR;
length_error:
- LOG_WARN("%s: invalid parameter length %d: must be at least %d", __func__,
- len, min_len);
+ log::warn("invalid parameter length {}: must be at least {}", len, min_len);
return AVRC_STS_INTERNAL_ERR;
}
@@ -867,7 +857,7 @@
break;
default:
- LOG_ERROR("%s unknown opcode:0x%x", __func__, p_msg->hdr.opcode);
+ log::error("unknown opcode:0x{:x}", p_msg->hdr.opcode);
break;
}
p_result->rsp.opcode = p_msg->hdr.opcode;
@@ -908,7 +898,7 @@
break;
default:
- LOG_ERROR("%s unknown opcode:0x%x", __func__, p_msg->hdr.opcode);
+ log::error("unknown opcode:0x{:x}", p_msg->hdr.opcode);
break;
}
p_result->rsp.opcode = p_msg->hdr.opcode;
diff --git a/system/stack/avrc/avrc_pars_tg.cc b/system/stack/avrc/avrc_pars_tg.cc
index a6ae9a6..4a053c6 100644
--- a/system/stack/avrc/avrc_pars_tg.cc
+++ b/system/stack/avrc/avrc_pars_tg.cc
@@ -15,6 +15,7 @@
* limitations under the License.
*
******************************************************************************/
+#include <bluetooth/log.h>
#include <string.h>
#include "avrc_api.h"
@@ -23,6 +24,8 @@
#include "os/log.h"
#include "stack/include/bt_types.h"
+using namespace bluetooth;
+
/*****************************************************************************
* Global data
****************************************************************************/
@@ -44,15 +47,15 @@
tAVRC_STS status = AVRC_STS_NO_ERROR;
if (p_msg->vendor_len < 4) { // 4 == pdu + reserved byte + len as uint16
- LOG_WARN("%s: message length %d too short: must be at least 4", __func__,
- p_msg->vendor_len);
+ log::warn("message length {} too short: must be at least 4",
+ p_msg->vendor_len);
return AVRC_STS_INTERNAL_ERR;
}
uint8_t* p = p_msg->p_vendor_data;
p_result->pdu = *p++;
- LOG_VERBOSE("%s pdu:0x%x", __func__, p_result->pdu);
+ log::verbose("pdu:0x{:x}", p_result->pdu);
if (!AVRC_IsValidAvcType(p_result->pdu, p_msg->hdr.ctype)) {
- LOG_VERBOSE("%s detects wrong AV/C type!", __func__);
+ log::verbose("detects wrong AV/C type!");
status = AVRC_STS_BAD_CMD;
}
@@ -123,24 +126,23 @@
if (p_msg->p_vendor_data == NULL) return AVRC_STS_INTERNAL_ERR;
if (p_msg->vendor_len < 4) {
- LOG_WARN("%s: message length %d too short: must be at least 4", __func__,
- p_msg->vendor_len);
+ log::warn("message length {} too short: must be at least 4",
+ p_msg->vendor_len);
return AVRC_STS_INTERNAL_ERR;
}
p = p_msg->p_vendor_data;
p_result->pdu = *p++;
- LOG_VERBOSE("%s pdu:0x%x", __func__, p_result->pdu);
+ log::verbose("pdu:0x{:x}", p_result->pdu);
if (!AVRC_IsValidAvcType(p_result->pdu, p_msg->hdr.ctype)) {
- LOG_VERBOSE("%s detects wrong AV/C type(0x%x)!", __func__,
- p_msg->hdr.ctype);
+ log::verbose("detects wrong AV/C type(0x{:x})!", p_msg->hdr.ctype);
status = AVRC_STS_BAD_CMD;
}
p++; /* skip the reserved byte */
BE_STREAM_TO_UINT16(len, p);
if ((len + 4) != (p_msg->vendor_len)) {
- LOG_ERROR("%s incorrect length :%d, %d", __func__, len, p_msg->vendor_len);
+ log::error("incorrect length :{}, {}", len, p_msg->vendor_len);
status = AVRC_STS_INTERNAL_ERR;
}
@@ -211,16 +213,15 @@
status = AVRC_STS_BAD_PARAM;
}
if (xx != p_result->set_app_val.num_val) {
- LOG_ERROR(
- "%s AVRC_PDU_SET_PLAYER_APP_VALUE not enough room:%d orig "
- "num_val:%d",
- __func__, xx, p_result->set_app_val.num_val);
+ log::error(
+ "AVRC_PDU_SET_PLAYER_APP_VALUE not enough room:{} orig "
+ "num_val:{}",
+ xx, p_result->set_app_val.num_val);
p_result->set_app_val.num_val = xx;
}
} else {
- LOG_ERROR(
- "%s AVRC_PDU_SET_PLAYER_APP_VALUE NULL decode buffer or bad len",
- __func__);
+ log::error(
+ "AVRC_PDU_SET_PLAYER_APP_VALUE NULL decode buffer or bad len");
status = AVRC_STS_INTERNAL_ERR;
}
break;
@@ -320,8 +321,7 @@
else {
BE_STREAM_TO_UINT8(p_result->reg_notif.event_id, p);
if (!AVRC_IS_VALID_EVENT_ID(p_result->reg_notif.event_id)) {
- LOG_ERROR("%s: Invalid event id: %d", __func__,
- p_result->reg_notif.event_id);
+ log::error("Invalid event id: {}", p_result->reg_notif.event_id);
return AVRC_STS_BAD_PARAM;
}
@@ -352,7 +352,7 @@
case AVRC_PDU_SET_ADDRESSED_PLAYER: /* 0x60 */
if (len != 2) {
- LOG_ERROR("AVRC_PDU_SET_ADDRESSED_PLAYER length is incorrect:%d", len);
+ log::error("AVRC_PDU_SET_ADDRESSED_PLAYER length is incorrect:{}", len);
return AVRC_STS_INTERNAL_ERR;
}
BE_STREAM_TO_UINT16(p_result->addr_player.player_id, p);
@@ -400,13 +400,13 @@
break;
default:
- LOG_ERROR("%s unknown opcode:0x%x", __func__, p_msg->hdr.opcode);
+ log::error("unknown opcode:0x{:x}", p_msg->hdr.opcode);
break;
}
p_result->cmd.opcode = p_msg->hdr.opcode;
p_result->cmd.status = status;
}
- LOG_VERBOSE("%s return status:0x%x", __func__, status);
+ log::verbose("return status:0x{:x}", status);
return status;
}
@@ -440,7 +440,7 @@
"msg too short");
p_result->pdu = *p++;
- LOG_VERBOSE("avrc_pars_browsing_cmd() pdu:0x%x", p_result->pdu);
+ log::verbose("avrc_pars_browsing_cmd() pdu:0x{:x}", p_result->pdu);
/* skip over len */
p += 2;
@@ -621,12 +621,12 @@
break;
default:
- LOG_ERROR("%s unknown opcode:0x%x", __func__, p_msg->hdr.opcode);
+ log::error("unknown opcode:0x{:x}", p_msg->hdr.opcode);
break;
}
p_result->cmd.opcode = p_msg->hdr.opcode;
p_result->cmd.status = status;
}
- LOG_VERBOSE("%s return status:0x%x", __func__, status);
+ log::verbose("return status:0x{:x}", status);
return status;
}
diff --git a/system/stack/avrc/avrc_sdp.cc b/system/stack/avrc/avrc_sdp.cc
index e6f4671..5944a10 100644
--- a/system/stack/avrc/avrc_sdp.cc
+++ b/system/stack/avrc/avrc_sdp.cc
@@ -23,6 +23,7 @@
******************************************************************************/
#define LOG_TAG "avrcp"
+#include <bluetooth/log.h>
#include <string.h>
#include "avrc_api.h"
@@ -36,6 +37,7 @@
#include "types/bluetooth/uuid.h"
#include "types/raw_address.h"
+using namespace bluetooth;
using namespace bluetooth::legacy::stack::sdp;
using bluetooth::Uuid;
@@ -67,7 +69,7 @@
*****************************************************************************/
static void avrc_sdp_cback(UNUSED_ATTR const RawAddress& bd_addr,
tSDP_STATUS status) {
- LOG_VERBOSE("%s status: %d", __func__, status);
+ log::verbose("status: {}", status);
/* reset service_uuid, so can start another find service */
avrc_cb.service_uuid = 0;
@@ -122,7 +124,7 @@
const tAVRC_FIND_CBACK& find_cback) {
bool result = true;
- LOG_VERBOSE("%s uuid: %x", __func__, service_uuid);
+ log::verbose("uuid: {:x}", service_uuid);
if ((service_uuid != UUID_SERVCLASS_AV_REM_CTRL_TARGET &&
service_uuid != UUID_SERVCLASS_AV_REMOTE_CONTROL) ||
p_db == NULL || p_db->p_db == NULL || find_cback.is_null())
@@ -155,8 +157,8 @@
bd_addr, p_db->p_db, avrc_sdp_cback);
if (!result) {
- LOG_ERROR("%s: Failed to init SDP for peer %s", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::error("Failed to init SDP for peer {}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
avrc_sdp_cback(bd_addr, SDP_GENERIC_ERROR);
}
}
@@ -218,10 +220,10 @@
uint8_t index = 0;
uint16_t class_list[2];
- LOG_VERBOSE(
- "%s: Add AVRCP SDP record, uuid: %x, profile_version: 0x%x, "
- "supported_features: 0x%x, psm: 0x%x",
- __func__, service_uuid, profile_version, categories, cover_art_psm);
+ log::verbose(
+ "Add AVRCP SDP record, uuid: {:x}, profile_version: 0x{:x}, "
+ "supported_features: 0x{:x}, psm: 0x{:x}",
+ service_uuid, profile_version, categories, cover_art_psm);
if (service_uuid != UUID_SERVCLASS_AV_REM_CTRL_TARGET &&
service_uuid != UUID_SERVCLASS_AV_REMOTE_CONTROL)
@@ -270,10 +272,7 @@
/* If we support browsing then add the list */
if (browse_supported) {
- LOG_VERBOSE(
- "%s: Add Browsing PSM to additional protocol descriptor"
- " lists",
- __func__);
+ log::verbose("Add Browsing PSM to additional protocol descriptor lists");
num_additional_protocols++;
avrc_add_proto_desc_lists[i].num_elems = 2;
avrc_add_proto_desc_lists[i].list_elem[0].num_params = 1;
@@ -294,10 +293,10 @@
if (profile_version >= AVRC_REV_1_6 &&
service_uuid == UUID_SERVCLASS_AV_REM_CTRL_TARGET &&
cover_art_psm > 0) {
- LOG_VERBOSE(
- "%s: Add AVRCP BIP PSM to additional protocol descriptor"
- " lists, psm: 0x%x",
- __func__, cover_art_psm);
+ log::verbose(
+ "Add AVRCP BIP PSM to additional protocol descriptor lists, psm: "
+ "0x{:x}",
+ cover_art_psm);
num_additional_protocols++;
avrc_add_proto_desc_lists[i].num_elems = 2;
avrc_add_proto_desc_lists[i].list_elem[0].num_params = 1;
@@ -314,8 +313,8 @@
/* Add the additional lists if we support any */
if (num_additional_protocols > 0) {
- LOG_VERBOSE("%s: Add %d additional protocol descriptor lists", __func__,
- num_additional_protocols);
+ log::verbose("Add {} additional protocol descriptor lists",
+ num_additional_protocols);
result &= get_legacy_stack_sdp_api()->handle.SDP_AddAdditionProtoLists(
sdp_handle, num_additional_protocols, avrc_add_proto_desc_lists);
}
@@ -367,7 +366,7 @@
*
*******************************************************************************/
uint16_t AVRC_RemoveRecord(uint32_t sdp_handle) {
- LOG_VERBOSE("%s: remove AVRCP SDP record", __func__);
+ log::verbose("remove AVRCP SDP record");
bool result = get_legacy_stack_sdp_api()->handle.SDP_DeleteRecord(sdp_handle);
return (result ? AVRC_SUCCESS : AVRC_FAIL);
}
diff --git a/system/stack/avrc/avrc_utils.cc b/system/stack/avrc/avrc_utils.cc
index 1d0247e..968cd50 100644
--- a/system/stack/avrc/avrc_utils.cc
+++ b/system/stack/avrc/avrc_utils.cc
@@ -18,11 +18,15 @@
#define LOG_TAG "avrcp"
+#include <bluetooth/log.h>
+
#include "avrc_api.h"
#include "avrc_int.h"
#include "os/log.h"
#include "stack/include/bt_types.h"
+using namespace bluetooth;
+
/**************************************************************************
*
* Function AVRC_IsValidAvcType
@@ -113,8 +117,8 @@
if (attrib >= AVRC_PLAYER_SETTING_LOW_MENU_EXT) result = true;
if (!result) {
- LOG_ERROR(" %s found not matching attrib(x%x)-value(x%x) pair!", __func__,
- attrib, value);
+ log::error(" found not matching attrib(x{:x})-value(x{:x}) pair!", attrib,
+ value);
}
return result;
}
diff --git a/system/stack/bnep/bnep_api.cc b/system/stack/bnep/bnep_api.cc
index c2a381c..c41d786 100644
--- a/system/stack/bnep/bnep_api.cc
+++ b/system/stack/bnep/bnep_api.cc
@@ -24,7 +24,7 @@
#include "bnep_api.h"
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include <string.h>
#include "bnep_int.h"
@@ -37,6 +37,7 @@
#include "types/bluetooth/uuid.h"
#include "types/raw_address.h"
+using namespace bluetooth;
using bluetooth::Uuid;
/*******************************************************************************
@@ -136,7 +137,7 @@
uint16_t cid;
tBNEP_CONN* p_bcb = bnepu_find_bcb_by_bd_addr(p_rem_bda);
- VLOG(0) << __func__ << " BDA:" << p_rem_bda;
+ log::verbose("BDA:{}", ADDRESS_TO_LOGGABLE_STR(p_rem_bda));
if (!bnep_cb.profile_registered) return BNEP_WRONG_STATE;
@@ -162,8 +163,8 @@
*/
p_bcb->con_state = BNEP_STATE_SEC_CHECKING;
- LOG_VERBOSE("BNEP initiating security procedures for src uuid %s",
- p_bcb->src_uuid.ToString().c_str());
+ log::verbose("BNEP initiating security procedures for src uuid {}",
+ p_bcb->src_uuid.ToString().c_str());
bnep_sec_check_complete(&p_bcb->rem_bda, BT_TRANSPORT_BR_EDR, p_bcb);
} else {
@@ -177,7 +178,7 @@
p_bcb->l2cap_cid = cid;
} else {
- LOG_ERROR("BNEP - Originate failed");
+ log::error("BNEP - Originate failed");
if (bnep_cb.p_conn_state_cb)
(*bnep_cb.p_conn_state_cb)(p_bcb->handle, p_bcb->rem_bda,
BNEP_CONN_FAILED, false);
@@ -221,7 +222,7 @@
(!(p_bcb->con_flags & BNEP_FLAGS_SETUP_RCVD)))
return (BNEP_WRONG_STATE);
- LOG_DEBUG("handle %d, responce %d", handle, resp);
+ log::debug("handle {}, responce {}", handle, resp);
/* Form appropriate responce based on profile responce */
if (resp == BNEP_CONN_FAILED_SRC_UUID)
@@ -294,7 +295,7 @@
if (p_bcb->con_state == BNEP_STATE_IDLE) return (BNEP_WRONG_HANDLE);
- LOG_VERBOSE("BNEP_Disconnect() for handle %d", handle);
+ log::verbose("BNEP_Disconnect() for handle {}", handle);
L2CA_DisconnectReq(p_bcb->l2cap_cid);
@@ -340,8 +341,7 @@
p_bcb = &(bnep_cb.bcb[handle - 1]);
/* Check MTU size */
if (p_buf->len > BNEP_MTU_SIZE) {
- LOG_ERROR("%s length %d exceeded MTU %d", __func__, p_buf->len,
- BNEP_MTU_SIZE);
+ log::error("length {} exceeded MTU {}", p_buf->len, BNEP_MTU_SIZE);
osi_free(p_buf);
return (BNEP_MTU_EXCEDED);
}
@@ -445,7 +445,7 @@
/* Check MTU size. Consider the possibility of having extension headers */
if (len > BNEP_MTU_SIZE) {
- LOG_ERROR("%s length %d exceeded MTU %d", __func__, len, BNEP_MTU_SIZE);
+ log::error("length {} exceeded MTU {}", len, BNEP_MTU_SIZE);
return (BNEP_MTU_EXCEDED);
}
diff --git a/system/stack/bnep/bnep_main.cc b/system/stack/bnep/bnep_main.cc
index 1cd8829..6f6ed8f 100644
--- a/system/stack/bnep/bnep_main.cc
+++ b/system/stack/bnep/bnep_main.cc
@@ -24,7 +24,7 @@
#define LOG_TAG "bluetooth"
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include <string.h>
#include "bnep_api.h"
@@ -42,6 +42,8 @@
#include "stack/include/bt_types.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
/******************************************************************************/
/* G L O B A L B N E P D A T A */
/******************************************************************************/
@@ -90,7 +92,7 @@
if (!L2CA_Register2(BT_PSM_BNEP, bnep_cb.reg_info, false /* enable_snoop */,
nullptr, BNEP_MTU_SIZE, BNEP_MTU_SIZE,
BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)) {
- LOG_ERROR("BNEP - Registration failed");
+ log::error("BNEP - Registration failed");
return BNEP_SECURITY_FAIL;
}
@@ -130,7 +132,7 @@
alarm_set_on_mloop(p_bcb->conn_timer, BNEP_CONN_TIMEOUT_MS,
bnep_conn_timer_timeout, p_bcb);
- LOG_DEBUG("BNEP - Rcvd L2CAP conn ind, CID: 0x%x", p_bcb->l2cap_cid);
+ log::debug("BNEP - Rcvd L2CAP conn ind, CID: 0x{:x}", p_bcb->l2cap_cid);
}
static void bnep_on_l2cap_error(uint16_t l2cap_cid, uint16_t result) {
@@ -165,7 +167,7 @@
/* Find CCB based on CID */
p_bcb = bnepu_find_bcb_by_cid(l2cap_cid);
if (p_bcb == NULL) {
- LOG_WARN("BNEP - Rcvd conn cnf for unknown CID 0x%x", l2cap_cid);
+ log::warn("BNEP - Rcvd conn cnf for unknown CID 0x{:x}", l2cap_cid);
return;
}
@@ -179,9 +181,10 @@
alarm_set_on_mloop(p_bcb->conn_timer, BNEP_CONN_TIMEOUT_MS,
bnep_conn_timer_timeout, p_bcb);
- LOG_DEBUG("BNEP - got conn cnf, sent cfg req, CID: 0x%x", p_bcb->l2cap_cid);
+ log::debug("BNEP - got conn cnf, sent cfg req, CID: 0x{:x}",
+ p_bcb->l2cap_cid);
} else {
- LOG(ERROR) << __func__ << ": invoked with non OK status";
+ log::error("invoked with non OK status");
}
}
@@ -199,12 +202,12 @@
tL2CAP_CFG_INFO* p_cfg) {
tBNEP_CONN* p_bcb;
- LOG_DEBUG("BNEP - Rcvd cfg cfm, CID: 0x%x", l2cap_cid);
+ log::debug("BNEP - Rcvd cfg cfm, CID: 0x{:x}", l2cap_cid);
/* Find CCB based on CID */
p_bcb = bnepu_find_bcb_by_cid(l2cap_cid);
if (p_bcb == NULL) {
- LOG_WARN("BNEP - Rcvd L2CAP cfg ind, unknown CID: 0x%x", l2cap_cid);
+ log::warn("BNEP - Rcvd L2CAP cfg ind, unknown CID: 0x{:x}", l2cap_cid);
return;
}
@@ -236,11 +239,11 @@
/* Find CCB based on CID */
p_bcb = bnepu_find_bcb_by_cid(l2cap_cid);
if (p_bcb == NULL) {
- LOG_WARN("BNEP - Rcvd L2CAP disc, unknown CID: 0x%x", l2cap_cid);
+ log::warn("BNEP - Rcvd L2CAP disc, unknown CID: 0x{:x}", l2cap_cid);
return;
}
- LOG_DEBUG("BNEP - Rcvd L2CAP disc, CID: 0x%x", l2cap_cid);
+ log::debug("BNEP - Rcvd L2CAP disc, CID: 0x{:x}", l2cap_cid);
/* Tell the user if there is a callback */
if (p_bcb->con_state == BNEP_STATE_CONNECTED) {
@@ -272,7 +275,7 @@
/* Find BCB based on CID */
p_bcb = bnepu_find_bcb_by_cid(l2cap_cid);
if (p_bcb == NULL) {
- LOG_WARN("BNEP - Rcvd L2CAP cong, unknown CID: 0x%x", l2cap_cid);
+ log::warn("BNEP - Rcvd L2CAP cong, unknown CID: 0x{:x}", l2cap_cid);
return;
}
@@ -329,7 +332,7 @@
/* Find CCB based on CID */
p_bcb = bnepu_find_bcb_by_cid(l2cap_cid);
if (p_bcb == NULL) {
- LOG_WARN("BNEP - Rcvd L2CAP data, unknown CID: 0x%x", l2cap_cid);
+ log::warn("BNEP - Rcvd L2CAP data, unknown CID: 0x{:x}", l2cap_cid);
osi_free(p_buf);
return;
}
@@ -339,12 +342,13 @@
extension_present = type >> 7;
type &= 0x7f;
if (type >= sizeof(bnep_frame_hdr_sizes) / sizeof(bnep_frame_hdr_sizes[0])) {
- LOG_INFO("BNEP - rcvd frame, bad type: 0x%02x", type);
+ log::info("BNEP - rcvd frame, bad type: 0x{:02x}", type);
osi_free(p_buf);
return;
}
if ((rem_len <= bnep_frame_hdr_sizes[type]) || (rem_len > BNEP_MTU_SIZE)) {
- LOG_DEBUG("BNEP - rcvd frame, bad len: %d type: 0x%02x", p_buf->len, type);
+ log::debug("BNEP - rcvd frame, bad len: {} type: 0x{:02x}", p_buf->len,
+ type);
osi_free(p_buf);
return;
}
@@ -354,8 +358,8 @@
if ((p_bcb->con_state != BNEP_STATE_CONNECTED) &&
(!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED)) &&
(type != BNEP_FRAME_CONTROL)) {
- LOG_WARN("BNEP - Ignored L2CAP data while in state: %d, CID: 0x%x",
- p_bcb->con_state, l2cap_cid);
+ log::warn("BNEP - Ignored L2CAP data while in state: {}, CID: 0x{:x}",
+ p_bcb->con_state, l2cap_cid);
if (extension_present) {
/*
@@ -398,13 +402,13 @@
}
if (type > BNEP_FRAME_COMPRESSED_ETHERNET_DEST_ONLY) {
- LOG_DEBUG("BNEP - rcvd frame, unknown type: 0x%02x", type);
+ log::debug("BNEP - rcvd frame, unknown type: 0x{:02x}", type);
osi_free(p_buf);
return;
}
- LOG_DEBUG("BNEP - rcv frame, type: %d len: %d Ext: %d", type, p_buf->len,
- extension_present);
+ log::debug("BNEP - rcv frame, type: {} len: {} Ext: {}", type, p_buf->len,
+ extension_present);
/* Initialize addresses to 'not supplied' */
RawAddress src_addr = RawAddress::kEmpty;
@@ -476,7 +480,7 @@
/* if unknown extension present stop processing */
if (ext_type) {
- LOG_DEBUG("Data extension type 0x%x found", ext_type);
+ log::debug("Data extension type 0x{:x} found", ext_type);
break;
}
@@ -524,14 +528,14 @@
void bnep_conn_timer_timeout(void* data) {
tBNEP_CONN* p_bcb = (tBNEP_CONN*)data;
- LOG_DEBUG(
- "BNEP - CCB timeout in state: %d CID: 0x%x flags %x, re_transmit %d",
+ log::debug(
+ "BNEP - CCB timeout in state: {} CID: 0x{:x} flags {:x}, re_transmit {}",
p_bcb->con_state, p_bcb->l2cap_cid, p_bcb->con_flags,
p_bcb->re_transmits);
if (p_bcb->con_state == BNEP_STATE_CONN_SETUP) {
- LOG_DEBUG("BNEP - CCB timeout in state: %d CID: 0x%x", p_bcb->con_state,
- p_bcb->l2cap_cid);
+ log::debug("BNEP - CCB timeout in state: {} CID: 0x{:x}", p_bcb->con_state,
+ p_bcb->l2cap_cid);
if (!(p_bcb->con_flags & BNEP_FLAGS_IS_ORIG)) {
L2CA_DisconnectReq(p_bcb->l2cap_cid);
@@ -555,8 +559,8 @@
return;
}
} else if (p_bcb->con_state != BNEP_STATE_CONNECTED) {
- LOG_DEBUG("BNEP - CCB timeout in state: %d CID: 0x%x", p_bcb->con_state,
- p_bcb->l2cap_cid);
+ log::debug("BNEP - CCB timeout in state: {} CID: 0x{:x}", p_bcb->con_state,
+ p_bcb->l2cap_cid);
L2CA_DisconnectReq(p_bcb->l2cap_cid);
diff --git a/system/stack/bnep/bnep_utils.cc b/system/stack/bnep/bnep_utils.cc
index b286f64..51e5059 100644
--- a/system/stack/bnep/bnep_utils.cc
+++ b/system/stack/bnep/bnep_utils.cc
@@ -22,7 +22,7 @@
*
******************************************************************************/
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include <stdio.h>
#include <string.h>
@@ -36,6 +36,7 @@
#include "types/bluetooth/uuid.h"
#include "types/raw_address.h"
+using namespace bluetooth;
using bluetooth::Uuid;
/******************************************************************************/
@@ -169,8 +170,8 @@
BT_HDR* p_buf = (BT_HDR*)osi_malloc(BNEP_BUF_SIZE);
uint8_t *p, *p_start;
- LOG_VERBOSE("%s: sending setup req with dst uuid %s", __func__,
- p_bcb->dst_uuid.ToString().c_str());
+ log::verbose("sending setup req with dst uuid {}",
+ p_bcb->dst_uuid.ToString().c_str());
p_buf->offset = L2CAP_MIN_OFFSET;
p = p_start = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
@@ -198,9 +199,9 @@
memcpy(p, p_bcb->src_uuid.To128BitBE().data(), Uuid::kNumBytes128);
p += Uuid::kNumBytes128;
} else {
- LOG_ERROR("%s: uuid: %s, invalid length: %zu", __func__,
- p_bcb->dst_uuid.ToString().c_str(),
- p_bcb->dst_uuid.GetShortestRepresentationSize());
+ log::error("uuid: {}, invalid length: {}",
+ p_bcb->dst_uuid.ToString().c_str(),
+ p_bcb->dst_uuid.GetShortestRepresentationSize());
}
p_buf->len = (uint16_t)(p - p_start);
@@ -221,7 +222,8 @@
BT_HDR* p_buf = (BT_HDR*)osi_malloc(BNEP_BUF_SIZE);
uint8_t* p;
- LOG_DEBUG("BNEP - bnep_send_conn_response for CID: 0x%x", p_bcb->l2cap_cid);
+ log::debug("BNEP - bnep_send_conn_response for CID: 0x{:x}",
+ p_bcb->l2cap_cid);
p_buf->offset = L2CAP_MIN_OFFSET;
p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
@@ -253,7 +255,7 @@
uint8_t* p;
uint16_t xx;
- LOG_VERBOSE("BNEP sending peer our filters");
+ log::verbose("BNEP sending peer our filters");
p_buf->offset = L2CAP_MIN_OFFSET;
p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
@@ -295,7 +297,7 @@
uint8_t* p;
uint16_t xx;
- LOG_VERBOSE("BNEP sending peer our multicast filters");
+ log::verbose("BNEP sending peer our multicast filters");
p_buf->offset = L2CAP_MIN_OFFSET;
p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
@@ -338,7 +340,7 @@
BT_HDR* p_buf = (BT_HDR*)osi_malloc(BNEP_BUF_SIZE);
uint8_t* p;
- LOG_VERBOSE("BNEP sending filter response");
+ log::verbose("BNEP sending filter response");
p_buf->offset = L2CAP_MIN_OFFSET;
p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
@@ -369,8 +371,9 @@
BT_HDR* p_buf = (BT_HDR*)osi_malloc(BNEP_BUF_SIZE);
uint8_t* p;
- LOG_VERBOSE("BNEP - bnep_send_command_not_understood for CID: 0x%x, cmd 0x%x",
- p_bcb->l2cap_cid, cmd_code);
+ log::verbose(
+ "BNEP - bnep_send_command_not_understood for CID: 0x{:x}, cmd 0x{:x}",
+ p_bcb->l2cap_cid, cmd_code);
p_buf->offset = L2CAP_MIN_OFFSET;
p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
@@ -400,10 +403,12 @@
*
******************************************************************************/
void bnepu_check_send_packet(tBNEP_CONN* p_bcb, BT_HDR* p_buf) {
- LOG_DEBUG("BNEP - bnepu_check_send_packet for CID: 0x%x", p_bcb->l2cap_cid);
+ log::debug("BNEP - bnepu_check_send_packet for CID: 0x{:x}",
+ p_bcb->l2cap_cid);
if (p_bcb->con_flags & BNEP_FLAGS_L2CAP_CONGESTED) {
if (fixed_queue_length(p_bcb->xmit_q) >= BNEP_MAX_XMITQ_DEPTH) {
- LOG_WARN("BNEP - congested, dropping buf, CID: 0x%x", p_bcb->l2cap_cid);
+ log::warn("BNEP - congested, dropping buf, CID: 0x{:x}",
+ p_bcb->l2cap_cid);
osi_free(p_buf);
} else {
@@ -531,12 +536,12 @@
******************************************************************************/
void bnep_process_setup_conn_req(tBNEP_CONN* p_bcb, uint8_t* p_setup,
uint8_t len) {
- LOG_DEBUG("BNEP - for CID: 0x%x", p_bcb->l2cap_cid);
+ log::debug("BNEP - for CID: 0x{:x}", p_bcb->l2cap_cid);
if (p_bcb->con_state != BNEP_STATE_CONN_SETUP &&
p_bcb->con_state != BNEP_STATE_SEC_CHECKING &&
p_bcb->con_state != BNEP_STATE_CONNECTED) {
- LOG_ERROR("BNEP - setup request in bad state %d", p_bcb->con_state);
+ log::error("BNEP - setup request in bad state {}", p_bcb->con_state);
bnep_send_conn_response(p_bcb, BNEP_SETUP_CONN_NOT_ALLOWED);
return;
}
@@ -544,7 +549,7 @@
/* Check if we already initiated security check or if waiting for user
* responce */
if (p_bcb->con_flags & BNEP_FLAGS_SETUP_RCVD) {
- LOG_WARN(
+ log::warn(
"BNEP - Duplicate Setup message received while doing security check");
return;
}
@@ -553,8 +558,8 @@
if (p_bcb->con_state != BNEP_STATE_CONNECTED &&
(!(p_bcb->con_flags & BNEP_FLAGS_SETUP_RCVD)) &&
(p_bcb->con_flags & BNEP_FLAGS_IS_ORIG)) {
- LOG_ERROR("BNEP - setup request when we are originator state:%hu",
- p_bcb->con_state);
+ log::error("BNEP - setup request when we are originator state:{}",
+ p_bcb->con_state);
bnep_send_conn_response(p_bcb, BNEP_SETUP_CONN_NOT_ALLOWED);
return;
}
@@ -596,7 +601,7 @@
p_bcb->dst_uuid = Uuid::From128BitBE(p_setup);
p_setup += len;
} else {
- LOG_ERROR("BNEP - Bad UID len %d in ConnReq", len);
+ log::error("BNEP - Bad UID len {} in ConnReq", len);
bnep_send_conn_response(p_bcb, BNEP_SETUP_INVALID_UUID_SIZE);
return;
}
@@ -604,8 +609,8 @@
p_bcb->con_state = BNEP_STATE_SEC_CHECKING;
p_bcb->con_flags |= BNEP_FLAGS_SETUP_RCVD;
- LOG_DEBUG("BNEP initiating security check for incoming call for uuid %s",
- p_bcb->src_uuid.ToString().c_str());
+ log::debug("BNEP initiating security check for incoming call for uuid {}",
+ p_bcb->src_uuid.ToString().c_str());
bnep_sec_check_complete(&p_bcb->rem_bda, BT_TRANSPORT_BR_EDR, p_bcb);
}
@@ -624,17 +629,17 @@
tBNEP_RESULT resp;
uint16_t resp_code;
- LOG_VERBOSE("BNEP received setup responce");
+ log::verbose("BNEP received setup responce");
/* The state should be either SETUP or CONNECTED */
if (p_bcb->con_state != BNEP_STATE_CONN_SETUP) {
/* Should we disconnect ? */
- LOG_ERROR("BNEP - setup response in bad state %d", p_bcb->con_state);
+ log::error("BNEP - setup response in bad state {}", p_bcb->con_state);
return;
}
/* Check if we are the originator */
if (!(p_bcb->con_flags & BNEP_FLAGS_IS_ORIG)) {
- LOG_ERROR("BNEP - setup response when we are not originator");
+ log::error("BNEP - setup response when we are not originator");
return;
}
@@ -662,7 +667,7 @@
/* Check the responce code */
if (resp_code != BNEP_SETUP_CONN_OK) {
if (p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED) {
- LOG_VERBOSE("BNEP - role change response is %d", resp_code);
+ log::verbose("BNEP - role change response is {}", resp_code);
/* Restore the earlier BNEP status */
p_bcb->con_state = BNEP_STATE_CONNECTED;
@@ -680,7 +685,7 @@
return;
} else {
- LOG_ERROR("BNEP - setup response %d is not OK", resp_code);
+ log::error("BNEP - setup response {} is not OK", resp_code);
L2CA_DisconnectReq(p_bcb->l2cap_cid);
@@ -715,8 +720,8 @@
if (p == NULL || rem_len == NULL) {
if (rem_len != NULL) *rem_len = 0;
- LOG_VERBOSE("%s: invalid packet: p = %p rem_len = %p", __func__, p,
- rem_len);
+ log::verbose("invalid packet: p = {} rem_len = {}", fmt::ptr(p),
+ fmt::ptr(rem_len));
return NULL;
}
uint16_t rem_len_orig = *rem_len;
@@ -731,37 +736,33 @@
control_type = *p++;
*rem_len = *rem_len - 1;
- LOG_VERBOSE(
- "%s: BNEP processing control packet rem_len %d, is_ext %d, ctrl_type %d",
- __func__, *rem_len, is_ext, control_type);
+ log::verbose(
+ "BNEP processing control packet rem_len {}, is_ext {}, ctrl_type {}",
+ *rem_len, is_ext, control_type);
switch (control_type) {
case BNEP_CONTROL_COMMAND_NOT_UNDERSTOOD:
if (*rem_len < 1) {
- LOG_ERROR(
- "%s: Received BNEP_CONTROL_COMMAND_NOT_UNDERSTOOD with bad length",
- __func__);
+ log::error(
+ "Received BNEP_CONTROL_COMMAND_NOT_UNDERSTOOD with bad length");
goto bad_packet_length;
}
- LOG_ERROR(
- "%s: Received BNEP_CONTROL_COMMAND_NOT_UNDERSTOOD for pkt type: %d",
- __func__, *p);
+ log::error(
+ "Received BNEP_CONTROL_COMMAND_NOT_UNDERSTOOD for pkt type: {}", *p);
p++;
*rem_len = *rem_len - 1;
break;
case BNEP_SETUP_CONNECTION_REQUEST_MSG:
if (*rem_len < 1) {
- LOG_ERROR(
- "%s: Received BNEP_SETUP_CONNECTION_REQUEST_MSG with bad length",
- __func__);
+ log::error(
+ "Received BNEP_SETUP_CONNECTION_REQUEST_MSG with bad length");
goto bad_packet_length;
}
len = *p++;
if (*rem_len < ((2 * len) + 1)) {
- LOG_ERROR(
- "%s: Received BNEP_SETUP_CONNECTION_REQUEST_MSG with bad length",
- __func__);
+ log::error(
+ "Received BNEP_SETUP_CONNECTION_REQUEST_MSG with bad length");
goto bad_packet_length;
}
if (!is_ext) bnep_process_setup_conn_req(p_bcb, p, (uint8_t)len);
@@ -771,9 +772,8 @@
case BNEP_SETUP_CONNECTION_RESPONSE_MSG:
if (*rem_len < 2) {
- LOG_ERROR(
- "%s: Received BNEP_SETUP_CONNECTION_RESPONSE_MSG with bad length",
- __func__);
+ log::error(
+ "Received BNEP_SETUP_CONNECTION_RESPONSE_MSG with bad length");
goto bad_packet_length;
}
if (!is_ext) bnep_process_setup_conn_responce(p_bcb, p);
@@ -783,14 +783,12 @@
case BNEP_FILTER_NET_TYPE_SET_MSG:
if (*rem_len < 2) {
- LOG_ERROR("%s: Received BNEP_FILTER_NET_TYPE_SET_MSG with bad length",
- __func__);
+ log::error("Received BNEP_FILTER_NET_TYPE_SET_MSG with bad length");
goto bad_packet_length;
}
BE_STREAM_TO_UINT16(len, p);
if (*rem_len < (len + 2)) {
- LOG_ERROR("%s: Received BNEP_FILTER_NET_TYPE_SET_MSG with bad length",
- __func__);
+ log::error("Received BNEP_FILTER_NET_TYPE_SET_MSG with bad length");
goto bad_packet_length;
}
bnepu_process_peer_filter_set(p_bcb, p, len);
@@ -800,9 +798,8 @@
case BNEP_FILTER_NET_TYPE_RESPONSE_MSG:
if (*rem_len < 2) {
- LOG_ERROR(
- "%s: Received BNEP_FILTER_NET_TYPE_RESPONSE_MSG with bad length",
- __func__);
+ log::error(
+ "Received BNEP_FILTER_NET_TYPE_RESPONSE_MSG with bad length");
goto bad_packet_length;
}
bnepu_process_peer_filter_rsp(p_bcb, p);
@@ -812,14 +809,12 @@
case BNEP_FILTER_MULTI_ADDR_SET_MSG:
if (*rem_len < 2) {
- LOG_ERROR("%s: Received BNEP_FILTER_MULTI_ADDR_SET_MSG with bad length",
- __func__);
+ log::error("Received BNEP_FILTER_MULTI_ADDR_SET_MSG with bad length");
goto bad_packet_length;
}
BE_STREAM_TO_UINT16(len, p);
if (*rem_len < (len + 2)) {
- LOG_ERROR("%s: Received BNEP_FILTER_MULTI_ADDR_SET_MSG with bad length",
- __func__);
+ log::error("Received BNEP_FILTER_MULTI_ADDR_SET_MSG with bad length");
goto bad_packet_length;
}
bnepu_process_peer_multicast_filter_set(p_bcb, p, len);
@@ -829,9 +824,8 @@
case BNEP_FILTER_MULTI_ADDR_RESPONSE_MSG:
if (*rem_len < 2) {
- LOG_ERROR(
- "%s: Received BNEP_FILTER_MULTI_ADDR_RESPONSE_MSG with bad length",
- __func__);
+ log::error(
+ "Received BNEP_FILTER_MULTI_ADDR_RESPONSE_MSG with bad length");
goto bad_packet_length;
}
bnepu_process_multicast_filter_rsp(p_bcb, p);
@@ -840,7 +834,7 @@
break;
default:
- LOG_ERROR("%s: BNEP - bad ctl pkt type: %d", __func__, control_type);
+ log::error("BNEP - bad ctl pkt type: {}", control_type);
bnep_send_command_not_understood(p_bcb, control_type);
if (is_ext && (ext_len > 0)) {
if (*rem_len < (ext_len - 1)) {
@@ -854,8 +848,8 @@
return p;
bad_packet_length:
- LOG_ERROR("%s: bad control packet length: original=%d remaining=%d", __func__,
- rem_len_orig, *rem_len);
+ log::error("bad control packet length: original={} remaining={}",
+ rem_len_orig, *rem_len);
*rem_len = 0;
return NULL;
}
@@ -880,15 +874,15 @@
if ((p_bcb->con_state != BNEP_STATE_CONNECTED) &&
(!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) {
- LOG_VERBOSE(
+ log::verbose(
"BNEP received filter set from peer when there is no connection");
return;
}
- LOG_VERBOSE("BNEP received filter set from peer");
+ log::verbose("BNEP received filter set from peer");
/* Check for length not a multiple of 4 */
if (len & 3) {
- LOG_VERBOSE("BNEP - bad filter len: %d", len);
+ log::verbose("BNEP - bad filter len: {}", len);
bnepu_send_peer_filter_rsp(p_bcb, BNEP_FILTER_CRL_BAD_RANGE);
return;
}
@@ -944,17 +938,17 @@
uint16_t resp_code;
tBNEP_RESULT result;
- LOG_VERBOSE("BNEP received filter responce");
+ log::verbose("BNEP received filter responce");
/* The state should be CONNECTED */
if ((p_bcb->con_state != BNEP_STATE_CONNECTED) &&
(!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) {
- LOG_ERROR("BNEP - filter response in bad state %d", p_bcb->con_state);
+ log::error("BNEP - filter response in bad state {}", p_bcb->con_state);
return;
}
/* Check if we are the originator */
if (!(p_bcb->con_flags & BNEP_FLAGS_FILTER_RESP_PEND)) {
- LOG_ERROR("BNEP - filter response when not expecting");
+ log::error("BNEP - filter response when not expecting");
return;
}
@@ -986,18 +980,18 @@
uint16_t resp_code;
tBNEP_RESULT result;
- LOG_VERBOSE("BNEP received multicast filter responce");
+ log::verbose("BNEP received multicast filter responce");
/* The state should be CONNECTED */
if ((p_bcb->con_state != BNEP_STATE_CONNECTED) &&
(!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) {
- LOG_ERROR("BNEP - multicast filter response in bad state %d",
- p_bcb->con_state);
+ log::error("BNEP - multicast filter response in bad state {}",
+ p_bcb->con_state);
return;
}
/* Check if we are the originator */
if (!(p_bcb->con_flags & BNEP_FLAGS_MULTI_RESP_PEND)) {
- LOG_ERROR("BNEP - multicast filter response when not expecting");
+ log::error("BNEP - multicast filter response when not expecting");
return;
}
@@ -1034,20 +1028,20 @@
if ((p_bcb->con_state != BNEP_STATE_CONNECTED) &&
(!(p_bcb->con_flags & BNEP_FLAGS_CONN_COMPLETED))) {
- LOG_VERBOSE(
+ log::verbose(
"BNEP received multicast filter set from peer when there is no "
"connection");
return;
}
if (len % 12) {
- LOG_VERBOSE("BNEP - bad filter len: %d", len);
+ log::verbose("BNEP - bad filter len: {}", len);
bnepu_send_peer_multicast_filter_rsp(p_bcb, BNEP_FILTER_CRL_BAD_RANGE);
return;
}
if (len > (BNEP_MAX_MULTI_FILTERS * 2 * BD_ADDR_LEN)) {
- LOG_VERBOSE("BNEP - Too many filters");
+ log::verbose("BNEP - Too many filters");
bnepu_send_peer_multicast_filter_rsp(p_bcb, BNEP_FILTER_CRL_MAX_REACHED);
return;
}
@@ -1088,7 +1082,7 @@
}
}
- LOG_VERBOSE("BNEP multicast filters %d", p_bcb->rcvd_mcast_filters);
+ log::verbose("BNEP multicast filters {}", p_bcb->rcvd_mcast_filters);
bnepu_send_peer_multicast_filter_rsp(p_bcb, resp_code);
if (bnep_cb.p_mfilter_ind_cb)
@@ -1109,7 +1103,7 @@
BT_HDR* p_buf = (BT_HDR*)osi_malloc(BNEP_BUF_SIZE);
uint8_t* p;
- LOG_VERBOSE("BNEP sending multicast filter response %d", response_code);
+ log::verbose("BNEP sending multicast filter response {}", response_code);
p_buf->offset = L2CAP_MIN_OFFSET;
p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
@@ -1150,8 +1144,8 @@
/* check if the port is still waiting for security to complete */
if (p_bcb->con_state != BNEP_STATE_SEC_CHECKING) {
- LOG_ERROR("BNEP Connection in wrong state %d when security is completed",
- p_bcb->con_state);
+ log::error("BNEP Connection in wrong state {} when security is completed",
+ p_bcb->con_state);
return;
}
@@ -1230,7 +1224,7 @@
}
if (i == p_bcb->rcvd_num_filters) {
- LOG_VERBOSE("Ignoring protocol 0x%x in BNEP data write", proto);
+ log::verbose("Ignoring protocol 0x{:x} in BNEP data write", proto);
return BNEP_IGNORE_CMD;
}
}
@@ -1258,8 +1252,8 @@
*/
if ((p_bcb->rcvd_mcast_filters == 0xFFFF) ||
(i == p_bcb->rcvd_mcast_filters)) {
- VLOG(1) << "Ignoring multicast address " << dest_addr
- << " in BNEP data write";
+ log::verbose("Ignoring multicast address {} in BNEP data write",
+ ADDRESS_TO_LOGGABLE_STR(dest_addr));
return BNEP_IGNORE_CMD;
}
}
diff --git a/system/stack/btm/ble_scanner_hci_interface.cc b/system/stack/btm/ble_scanner_hci_interface.cc
index ac443bc..9f59be0 100644
--- a/system/stack/btm/ble_scanner_hci_interface.cc
+++ b/system/stack/btm/ble_scanner_hci_interface.cc
@@ -19,6 +19,7 @@
#include <base/functional/bind.h>
#include <base/logging.h>
+#include <bluetooth/log.h>
#include "btm_api.h"
#include "device/include/controller.h"
@@ -26,6 +27,8 @@
#include "stack/include/hcimsgs.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
namespace {
BleScannerHciInterface* instance = nullptr;
@@ -55,7 +58,7 @@
handle = handle & 0x0EFF;
} else {
- VLOG(1) << __func__ << " hci response error code: " << int{status};
+ log::verbose("hci response error code: {}", int{status});
}
cb.Run(status, handle);
}
@@ -135,8 +138,7 @@
uint16_t acl_handle = BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE);
if (acl_handle == HCI_INVALID_HANDLE) {
- LOG(ERROR) << __func__
- << ": Wrong mode: no LE link exist or LE not supported";
+ log::error("Wrong mode: no LE link exist or LE not supported");
return;
}
@@ -151,8 +153,7 @@
uint16_t acl_handle = BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE);
if (acl_handle == HCI_INVALID_HANDLE) {
- LOG(ERROR) << __func__
- << ": Wrong mode: no LE link exist or LE not supported";
+ log::error("Wrong mode: no LE link exist or LE not supported");
return;
}
@@ -168,8 +169,7 @@
uint16_t acl_handle = BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE);
if (acl_handle == HCI_INVALID_HANDLE) {
- LOG(ERROR) << __func__
- << ": Wrong mode: no LE link exist or LE not supported";
+ log::error("Wrong mode: no LE link exist or LE not supported");
return;
}
@@ -246,8 +246,7 @@
uint16_t acl_handle = BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE);
if (acl_handle == HCI_INVALID_HANDLE) {
- LOG(ERROR) << __func__
- << ": Wrong mode: no LE link exist or LE not supported";
+ log::error("Wrong mode: no LE link exist or LE not supported");
return;
}
@@ -262,8 +261,7 @@
uint16_t acl_handle = BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE);
if (acl_handle == HCI_INVALID_HANDLE) {
- LOG(ERROR) << __func__
- << ": Wrong mode: no LE link exist or LE not supported";
+ log::error("Wrong mode: no LE link exist or LE not supported");
return;
}
@@ -279,8 +277,7 @@
uint16_t acl_handle = BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE);
if (acl_handle == HCI_INVALID_HANDLE) {
- LOG(ERROR) << __func__
- << ": Wrong mode: no LE link exist or LE not supported";
+ log::error("Wrong mode: no LE link exist or LE not supported");
return;
}
@@ -308,16 +305,16 @@
if ((controller_get_interface()->get_ble_periodic_advertiser_list_size()) &&
(controller_get_interface()
->SupportsBlePeriodicAdvertisingSyncTransferSender())) {
- LOG(INFO) << "Advertiser list in controller can be used";
- LOG(INFO) << "Periodic Adv Sync Transfer Sender role is supported";
+ log::info("Advertiser list in controller can be used");
+ log::info("Periodic Adv Sync Transfer Sender role is supported");
instance = new BleScannerCompleteImpl();
} else if (controller_get_interface()
->SupportsBlePeriodicAdvertisingSyncTransferSender()) {
- LOG(INFO) << "Periodic Adv Sync Transfer Sender role is supported";
+ log::info("Periodic Adv Sync Transfer Sender role is supported");
instance = new BleScannerSyncTransferImpl();
} else if (controller_get_interface()
->get_ble_periodic_advertiser_list_size()) {
- LOG(INFO) << "Periodic Adv Sync Transfer Recipient role is supported";
+ log::info("Periodic Adv Sync Transfer Recipient role is supported");
instance = new BleScannerListImpl();
}
// TODO: Implement periodic adv. sync. recipient role if ever needed.
diff --git a/system/stack/btm/btm_ble.cc b/system/stack/btm/btm_ble.cc
index f3f9f6e..36d6dde 100644
--- a/system/stack/btm/btm_ble.cc
+++ b/system/stack/btm/btm_ble.cc
@@ -25,6 +25,8 @@
#define LOG_TAG "ble"
+#include <bluetooth/log.h>
+
#include <cstdint>
#include "base/functional/bind.h"
@@ -38,6 +40,8 @@
#include "stack/include/gatt_api.h"
#include "stack/include/hcimsgs.h"
+using namespace bluetooth;
+
extern tBTM_CB btm_cb;
/*******************************************************************************
@@ -162,7 +166,7 @@
const RawAddress& bd_addr,
base::Callback<void(uint8_t tx_phy, uint8_t rx_phy, uint8_t status)> cb) {
if (!BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) {
- LOG_ERROR("Wrong mode: no LE link exist or LE not supported");
+ log::error("Wrong mode: no LE link exist or LE not supported");
cb.Run(0, 0, HCI_ERR_NO_CONNECTION);
return;
}
@@ -170,7 +174,7 @@
// checking if local controller supports it!
if (!controller_get_interface()->SupportsBle2mPhy() &&
!controller_get_interface()->SupportsBleCodedPhy()) {
- LOG_ERROR("request not supported in local controller!");
+ log::error("request not supported in local controller!");
cb.Run(0, 0, GATT_REQ_NOT_SUPPORTED);
return;
}
@@ -190,7 +194,7 @@
void BTM_BleSetPhy(const RawAddress& bd_addr, uint8_t tx_phys, uint8_t rx_phys,
uint16_t phy_options) {
if (!BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) {
- LOG_INFO(
+ log::info(
"Unable to set phy preferences because no le acl is connected to "
"device");
return;
@@ -205,7 +209,8 @@
// checking if local controller supports it!
if (!controller_get_interface()->SupportsBle2mPhy() &&
!controller_get_interface()->SupportsBleCodedPhy()) {
- LOG_INFO("Local controller unable to support setting of le phy parameters");
+ log::info(
+ "Local controller unable to support setting of le phy parameters");
gatt_notify_phy_updated(static_cast<tHCI_STATUS>(GATT_REQ_NOT_SUPPORTED),
handle, tx_phys, rx_phys);
return;
@@ -213,7 +218,7 @@
if (!acl_peer_supports_ble_2m_phy(handle) &&
!acl_peer_supports_ble_coded_phy(handle)) {
- LOG_INFO("Remote device unable to support setting of le phy parameter");
+ log::info("Remote device unable to support setting of le phy parameter");
gatt_notify_phy_updated(static_cast<tHCI_STATUS>(GATT_REQ_NOT_SUPPORTED),
handle, tx_phys, rx_phys);
return;
diff --git a/system/stack/btm/btm_ble_addr.cc b/system/stack/btm/btm_ble_addr.cc
index e9a85a9..988a3c9 100644
--- a/system/stack/btm/btm_ble_addr.cc
+++ b/system/stack/btm/btm_ble_addr.cc
@@ -27,6 +27,7 @@
#include "stack/include/btm_ble_addr.h"
#include <base/functional/bind.h>
+#include <bluetooth/log.h>
#include <string.h>
#include "btm_ble_int.h"
@@ -43,6 +44,8 @@
#include "types/ble_address_with_type.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
extern tBTM_CB btm_cb;
/* This function generates Resolvable Private Address (RPA) from Identity
@@ -76,7 +79,7 @@
void btm_gen_resolve_paddr_low(const RawAddress& address) {
/* when GD advertising and scanning modules are enabled, set random address
* via address manager in GD */
- LOG_INFO("GD advertising and scanning modules are enabled, skip");
+ log::info("GD advertising and scanning modules are enabled, skip");
}
/** This function generate a resolvable private address using local IRK */
@@ -205,8 +208,8 @@
if (p_dev_rec->ble.identity_address_with_type.bda == bd_addr) {
if ((p_dev_rec->ble.identity_address_with_type.type &
(~BLE_ADDR_TYPE_ID_BIT)) != (addr_type & (~BLE_ADDR_TYPE_ID_BIT)))
- LOG_WARN("pseudo->random match with diff addr type: %d vs %d",
- p_dev_rec->ble.identity_address_with_type.type, addr_type);
+ log::warn("pseudo->random match with diff addr type: {} vs {}",
+ p_dev_rec->ble.identity_address_with_type.type, addr_type);
/* found the match */
return p_dev_rec;
@@ -293,7 +296,7 @@
tBLE_RAND_ADDR_TYPE rra_type) {
tBTM_SEC_DEV_REC* p_sec_rec = btm_find_dev(pseudo_bda);
if (p_sec_rec == nullptr) {
- LOG_WARN("No matching known device in record");
+ log::warn("No matching known device in record");
return;
}
@@ -316,7 +319,7 @@
if (!acl_refresh_remote_address(identity_address, identity_address_type,
p_sec_rec->ble.pseudo_addr, rra_type,
rpa)) {
- LOG_ERROR("Unknown device to refresh remote device");
+ log::error("Unknown device to refresh remote device");
}
}
}
@@ -341,8 +344,8 @@
if (!is_in_security_db && addr_is_rpa) {
tBTM_SEC_DEV_REC* match_rec = btm_ble_resolve_random_addr(*bda);
if (match_rec) {
- LOG_INFO("matched/resolved random address:%s",
- ADDRESS_TO_LOGGABLE_CSTR(*bda));
+ log::info("matched/resolved random address:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(*bda));
is_in_security_db = true;
match_rec->ble.active_addr_type = BTM_BLE_ADDR_RRA;
match_rec->ble.cur_rand_addr = *bda;
@@ -354,8 +357,8 @@
*bda = match_rec->bd_addr;
}
} else {
- LOG_INFO("unable to match/resolve random address:%s",
- ADDRESS_TO_LOGGABLE_CSTR(*bda));
+ log::info("unable to match/resolve random address:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(*bda));
}
}
return is_in_security_db;
diff --git a/system/stack/btm/btm_ble_adv_filter.cc b/system/stack/btm/btm_ble_adv_filter.cc
index 1c0cfe7..f345c4c 100644
--- a/system/stack/btm/btm_ble_adv_filter.cc
+++ b/system/stack/btm/btm_ble_adv_filter.cc
@@ -19,6 +19,7 @@
#define LOG_TAG "bt_btm_ble"
#include <base/functional/bind.h>
+#include <bluetooth/log.h>
#include "btm_ble_api.h"
#include "os/log.h"
@@ -32,6 +33,7 @@
extern tBTM_CB btm_cb;
+using namespace bluetooth;
using base::Bind;
using bluetooth::Uuid;
@@ -125,7 +127,7 @@
static void btm_flt_update_cb(uint8_t expected_ocf, tBTM_BLE_PF_CFG_CBACK cb,
uint8_t* p, uint16_t evt_len) {
if (evt_len != 4) {
- LOG_ERROR("%s: bad length: %d", __func__, evt_len);
+ log::error("bad length: {}", evt_len);
return;
}
@@ -136,8 +138,8 @@
STREAM_TO_UINT8(num_avail, p);
if (expected_ocf != op_subcode) {
- LOG_ERROR("%s: Incorrect opcode: 0x%02x, expected: 0x%02x", __func__,
- expected_ocf, op_subcode);
+ log::error("Incorrect opcode: 0x{:02x}, expected: 0x{:02x}", expected_ocf,
+ op_subcode);
return;
}
@@ -149,8 +151,8 @@
}
uint8_t cond_type = btm_ble_ocf_to_condtype(expected_ocf);
- LOG_VERBOSE("%s: Recd: %d, %d, %d, %d, %d", __func__, op_subcode,
- expected_ocf, action, status, num_avail);
+ log::verbose("Recd: {}, {}, {}, {}, {}", op_subcode, expected_ocf, action,
+ status, num_avail);
if (HCI_SUCCESS == status) {
if (btm_ble_adv_filt_cb.cur_filter_target.bda.IsEmpty())
btm_ble_cs_update_pf_counter(static_cast<tBTM_BLE_SCAN_COND_OP>(action),
@@ -269,7 +271,7 @@
uint8_t* p_counter = NULL;
if (cond_type > BTM_BLE_PF_TYPE_ALL) {
- LOG_ERROR("unknown PF filter condition type %d", cond_type);
+ log::error("unknown PF filter condition type {}", cond_type);
return BTM_BLE_INVALID_COUNTER;
}
@@ -300,13 +302,13 @@
p_counter = p_addr_filter->pf_counter;
if (num_available > 0) p_counter[cond_type] += 1;
- LOG_VERBOSE("counter = %d, maxfilt = %d, num_avbl=%d",
- p_counter[cond_type], cmn_ble_vsc_cb.max_filter,
- num_available);
+ log::verbose("counter = {}, maxfilt = {}, num_avbl={}",
+ p_counter[cond_type], cmn_ble_vsc_cb.max_filter,
+ num_available);
return p_counter[cond_type];
}
} else {
- LOG_ERROR("no matching filter counter found");
+ log::error("no matching filter counter found");
}
/* no matching filter located and updated */
return BTM_BLE_INVALID_COUNTER;
@@ -341,17 +343,17 @@
p = param;
memset(param, 0, len);
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
if (BTM_BLE_SCAN_COND_ADD == action) {
p_bda_filter = btm_ble_find_addr_filter_counter(nullptr);
if (NULL == p_bda_filter) {
- LOG_ERROR("BD Address not found!");
+ log::error("BD Address not found!");
cb.Run(0, BTM_BLE_PF_ENABLE, btm_status_value(BTM_UNKNOWN_ADDR));
return;
}
- LOG_VERBOSE("%s : Feat mask:%d", __func__, p_filt_params->feat_seln);
+ log::verbose("Feat mask:{}", p_filt_params->feat_seln);
/* select feature based on control block settings */
UINT8_TO_STREAM(p, BTM_BLE_META_PF_FEAT_SEL);
UINT8_TO_STREAM(p, BTM_BLE_SCAN_COND_ADD);
diff --git a/system/stack/btm/btm_ble_bgconn.cc b/system/stack/btm/btm_ble_bgconn.cc
index a5511bb..487359a 100644
--- a/system/stack/btm/btm_ble_bgconn.cc
+++ b/system/stack/btm/btm_ble_bgconn.cc
@@ -26,6 +26,8 @@
#include "stack/btm/btm_ble_bgconn.h"
+#include <bluetooth/log.h>
+
#include <cstdint>
#include <unordered_map>
@@ -37,6 +39,8 @@
#include "stack/btm/btm_int_types.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
extern tBTM_CB btm_cb;
// Unfortunately (for now?) we have to maintain a copy of the device acceptlist
@@ -77,7 +81,7 @@
? BTM_BLE_GAP_DISC_SCAN_WIN
: btm_cb.ble_ctr_cb.inq_var.scan_window;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
btm_cb.ble_ctr_cb.inq_var.sfp = scan_policy;
btm_cb.ble_ctr_cb.inq_var.scan_type =
@@ -102,7 +106,7 @@
* be added, true otherwise. */
bool BTM_AcceptlistAdd(const RawAddress& address, bool is_direct) {
if (!controller_get_interface()->SupportsBle()) {
- LOG_WARN("Controller does not support Le");
+ log::warn("Controller does not support Le");
return false;
}
@@ -113,7 +117,7 @@
/** Removes the device from acceptlist */
void BTM_AcceptlistRemove(const RawAddress& address) {
if (!controller_get_interface()->SupportsBle()) {
- LOG_WARN("Controller does not support Le");
+ log::warn("Controller does not support Le");
return;
}
@@ -125,7 +129,7 @@
/** Clear the acceptlist, end any pending acceptlist connections */
void BTM_AcceptlistClear() {
if (!controller_get_interface()->SupportsBle()) {
- LOG_WARN("Controller does not support Le");
+ log::warn("Controller does not support Le");
return;
}
bluetooth::shim::ACL_IgnoreAllLeConnections();
diff --git a/system/stack/btm/btm_ble_cont_energy.cc b/system/stack/btm/btm_ble_cont_energy.cc
index 4d1a7e7..c61918f 100644
--- a/system/stack/btm/btm_ble_cont_energy.cc
+++ b/system/stack/btm/btm_ble_cont_energy.cc
@@ -18,6 +18,7 @@
#define LOG_TAG "btm_ble_cont_energy"
+#include <bluetooth/log.h>
#include <inttypes.h>
#include <string.h>
@@ -27,6 +28,8 @@
#include "stack/btm/btm_int_types.h"
#include "stack/include/bt_types.h"
+using namespace bluetooth;
+
extern tBTM_CB btm_cb;
tBTM_BLE_ENERGY_INFO_CB ble_energy_info_cb;
@@ -49,7 +52,7 @@
total_energy_used = 0;
if (len < 17) {
- LOG_ERROR("wrong length for btm_ble_cont_energy_cmpl_cback");
+ log::error("wrong length for btm_ble_cont_energy_cmpl_cback");
return;
}
@@ -61,10 +64,9 @@
STREAM_TO_UINT32(total_idle_time, p);
STREAM_TO_UINT32(total_energy_used, p);
- LOG_VERBOSE("energy_info status=%d,tx_t=%" PRId32 ", rx_t=%" PRId32
- ", ener_used=%" PRId32 ", idle_t=%" PRId32,
- status, total_tx_time, total_rx_time, total_energy_used,
- total_idle_time);
+ log::verbose(
+ "energy_info status={},tx_t={}, rx_t={}, ener_used={}, idle_t={}", status,
+ total_tx_time, total_rx_time, total_energy_used, total_idle_time);
if (NULL != ble_energy_info_cb.p_ener_cback)
ble_energy_info_cb.p_ener_cback(total_tx_time, total_rx_time,
@@ -90,10 +92,10 @@
BTM_BleGetVendorCapabilities(&cmn_ble_vsc_cb);
- LOG_VERBOSE("BTM_BleGetEnergyInfo");
+ log::verbose("BTM_BleGetEnergyInfo");
if (0 == cmn_ble_vsc_cb.energy_support) {
- LOG_ERROR("Controller does not support get energy info");
+ log::error("Controller does not support get energy info");
return BTM_ERR_PROCESSING;
}
diff --git a/system/stack/btm/btm_ble_gap.cc b/system/stack/btm/btm_ble_gap.cc
index c449370..b8a9c3a 100644
--- a/system/stack/btm/btm_ble_gap.cc
+++ b/system/stack/btm/btm_ble_gap.cc
@@ -28,8 +28,8 @@
#include <android_bluetooth_flags.h>
#include <android_bluetooth_sysprop.h>
#include <base/functional/bind.h>
-#include <base/logging.h>
#include <base/strings/string_number_conversions.h>
+#include <bluetooth/log.h>
#include <cstdint>
#include <list>
@@ -72,6 +72,8 @@
#include "types/ble_address_with_type.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
extern tBTM_CB btm_cb;
void btm_inq_remote_name_timer_timeout(void* data);
@@ -491,6 +493,16 @@
}
}
+std::pair<uint16_t /* interval */, uint16_t /* window */>
+get_low_latency_scan_params() {
+ uint16_t scan_interval = osi_property_get_int32(kPropertyInquiryScanInterval,
+ BTM_BLE_LOW_LATENCY_SCAN_INT);
+ uint16_t scan_window = osi_property_get_int32(kPropertyInquiryScanWindow,
+ BTM_BLE_LOW_LATENCY_SCAN_WIN);
+
+ return std::make_pair(scan_interval, scan_window);
+}
+
/*******************************************************************************
*
* Function BTM_BleObserve
@@ -513,21 +525,23 @@
tBTM_CMPL_CB* p_cmpl_cb, bool low_latency_scan) {
tBTM_STATUS status = BTM_WRONG_MODE;
- uint32_t scan_interval = !btm_cb.ble_ctr_cb.inq_var.scan_interval
+ uint16_t scan_interval = !btm_cb.ble_ctr_cb.inq_var.scan_interval
? BTM_BLE_GAP_DISC_SCAN_INT
: btm_cb.ble_ctr_cb.inq_var.scan_interval;
- uint32_t scan_window = !btm_cb.ble_ctr_cb.inq_var.scan_window
+ uint16_t scan_window = !btm_cb.ble_ctr_cb.inq_var.scan_window
? BTM_BLE_GAP_DISC_SCAN_WIN
: btm_cb.ble_ctr_cb.inq_var.scan_window;
// use low latency scanning if the scanning is active
+ uint16_t ll_scan_interval, ll_scan_window;
+ std::tie(ll_scan_interval, ll_scan_window) = get_low_latency_scan_params();
if (low_latency_scan) {
- scan_interval = BTM_BLE_LOW_LATENCY_SCAN_INT;
- scan_window = BTM_BLE_LOW_LATENCY_SCAN_WIN;
+ std::tie(scan_interval, scan_window) =
+ std::tie(ll_scan_interval, ll_scan_window);
}
- LOG_VERBOSE("%s : scan_type:%d, %d, %d", __func__,
- btm_cb.ble_ctr_cb.inq_var.scan_type, scan_interval, scan_window);
+ log::verbose("scan_type:{}, {}, {}", btm_cb.ble_ctr_cb.inq_var.scan_type,
+ scan_interval, scan_window);
if (!controller_get_interface()->SupportsBle()) return BTM_ILLEGAL_VALUE;
@@ -540,12 +554,12 @@
if (alarm_is_scheduled(btm_cb.ble_ctr_cb.observer_timer)) {
alarm_cancel(btm_cb.ble_ctr_cb.observer_timer);
} else {
- LOG_ERROR("%s Scan with no duration started twice!", __func__);
+ log::error("Scan with no duration started twice!");
}
} else {
if (!low_latency_scan &&
alarm_is_scheduled(btm_cb.ble_ctr_cb.observer_timer)) {
- LOG_ERROR("%s Scan with duration started twice!", __func__);
+ log::error("Scan with duration started twice!");
}
}
/*
@@ -554,12 +568,11 @@
* 2. current ongoing scanning is low latency
*/
bool is_ongoing_low_latency =
- btm_cb.ble_ctr_cb.inq_var.scan_interval ==
- BTM_BLE_GAP_DISC_SCAN_INT &&
- btm_cb.ble_ctr_cb.inq_var.scan_window == BTM_BLE_LOW_LATENCY_SCAN_WIN;
+ btm_cb.ble_ctr_cb.inq_var.scan_interval == ll_scan_interval &&
+ btm_cb.ble_ctr_cb.inq_var.scan_window == ll_scan_window;
if (!low_latency_scan || is_ongoing_low_latency) {
- LOG_WARN("%s Observer was already active, is_low_latency: %d", __func__,
- is_ongoing_low_latency);
+ log::warn("Observer was already active, is_low_latency: {}",
+ is_ongoing_low_latency);
return BTM_CMD_STARTED;
}
// stop any scan without low latency config
@@ -615,7 +628,7 @@
status = BTM_CMD_STARTED;
btm_ble_stop_observe();
} else {
- LOG_ERROR("%s Observe not active", __func__);
+ log::error("Observe not active");
}
return status;
@@ -623,11 +636,10 @@
static void btm_get_dynamic_audio_buffer_vsc_cmpl_cback(
tBTM_VSC_CMPL* p_vsc_cmpl_params) {
- LOG(INFO) << __func__;
+ log::info("");
if (p_vsc_cmpl_params->param_len < 1) {
- LOG(ERROR) << __func__
- << ": The length of returned parameters is less than 1";
+ log::error("The length of returned parameters is less than 1");
return;
}
uint8_t* p_event_param_buf = p_vsc_cmpl_params->p_param_buf;
@@ -642,24 +654,22 @@
// Audio_Codec_Buffer_Time | 192 octet| Default/Max/Min buffer time
STREAM_TO_UINT8(status, p_event_param_buf);
if (status != HCI_SUCCESS) {
- LOG(ERROR) << __func__
- << ": Fail to configure DFTB. status: " << loghex(status);
+ log::error("Fail to configure DFTB. status: {}", loghex(status));
return;
}
if (p_vsc_cmpl_params->param_len != 198) {
- LOG(FATAL) << __func__
- << ": The length of returned parameters is not equal to 198: "
- << std::to_string(p_vsc_cmpl_params->param_len);
+ log::fatal("The length of returned parameters is not equal to 198: {}",
+ p_vsc_cmpl_params->param_len);
return;
}
STREAM_TO_UINT8(opcode, p_event_param_buf);
- LOG(INFO) << __func__ << ": opcode = " << loghex(opcode);
+ log::info("opcode = {}", loghex(opcode));
if (opcode == 0x01) {
STREAM_TO_UINT32(codec_mask, p_event_param_buf);
- LOG(INFO) << __func__ << ": codec_mask = " << loghex(codec_mask);
+ log::info("codec_mask = {}", loghex(codec_mask));
for (int i = 0; i < BTM_CODEC_TYPE_MAX_RECORDS; i++) {
STREAM_TO_UINT16(btm_cb.dynamic_audio_buffer_cb[i].default_buffer_time,
@@ -670,7 +680,7 @@
p_event_param_buf);
}
- LOG(INFO) << __func__ << ": Succeed to receive Media Tx Buffer.";
+ log::info("Succeed to receive Media Tx Buffer.");
}
}
@@ -685,7 +695,7 @@
******************************************************************************/
static void btm_ble_vendor_capability_vsc_cmpl_cback(
tBTM_VSC_CMPL* p_vcs_cplt_params) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
/* Check status of command complete event */
CHECK(p_vcs_cplt_params->opcode == HCI_BLE_VENDOR_CAP);
@@ -697,7 +707,7 @@
tHCI_STATUS status = to_hci_status_code(raw_status);
if (status != HCI_SUCCESS) {
- LOG_VERBOSE("%s: Status = 0x%02x (0 is success)", __func__, status);
+ log::verbose("Status = 0x{:02x} (0 is success)", status);
return;
}
CHECK(p_vcs_cplt_params->param_len >= BTM_VSC_CHIP_CAPABILITY_RSP_LEN);
@@ -759,12 +769,12 @@
btm_cb.cmn_ble_vsc_cb.values_read = true;
- LOG_VERBOSE("%s: stat=%d, irk=%d, ADV ins:%d, rpa=%d, ener=%d, ext_scan=%d",
- __func__, status, btm_cb.cmn_ble_vsc_cb.max_irk_list_sz,
- btm_cb.cmn_ble_vsc_cb.adv_inst_max,
- btm_cb.cmn_ble_vsc_cb.rpa_offloading,
- btm_cb.cmn_ble_vsc_cb.energy_support,
- btm_cb.cmn_ble_vsc_cb.extended_scan_support);
+ log::verbose("stat={}, irk={}, ADV ins:{}, rpa={}, ener={}, ext_scan={}",
+ status, btm_cb.cmn_ble_vsc_cb.max_irk_list_sz,
+ btm_cb.cmn_ble_vsc_cb.adv_inst_max,
+ btm_cb.cmn_ble_vsc_cb.rpa_offloading,
+ btm_cb.cmn_ble_vsc_cb.energy_support,
+ btm_cb.cmn_ble_vsc_cb.extended_scan_support);
if (btm_cb.cmn_ble_vsc_cb.max_filter > 0) btm_ble_adv_filter_init();
@@ -798,7 +808,7 @@
void BTM_BleGetDynamicAudioBuffer(
tBTM_BT_DYNAMIC_AUDIO_BUFFER_CB p_dynamic_audio_buffer_cb[]) {
- LOG_VERBOSE("BTM_BleGetDynamicAudioBuffer");
+ log::verbose("BTM_BleGetDynamicAudioBuffer");
if (NULL != p_dynamic_audio_buffer_cb) {
for (int i = 0; i < 32; i++) {
@@ -824,7 +834,7 @@
if (btm_cb.cmn_ble_vsc_cb.values_read) return;
- LOG_VERBOSE("BTM_BleReadControllerFeatures");
+ log::verbose("BTM_BleReadControllerFeatures");
if (IS_FLAG_ENABLED(report_vsc_data_from_the_gd_controller)) {
btm_cb.cmn_ble_vsc_cb.values_read = true;
@@ -862,6 +872,8 @@
vendor_capabilities.bluetooth_quality_report_support_;
btm_cb.cmn_ble_vsc_cb.dynamic_audio_buffer_support =
vendor_capabilities.dynamic_audio_buffer_support_;
+ btm_cb.cmn_ble_vsc_cb.a2dp_offload_v2_support =
+ vendor_capabilities.a2dp_offload_v2_support_;
if (vendor_capabilities.dynamic_audio_buffer_support_) {
std::array<bluetooth::hci::DynamicAudioBufferCodecCapability,
@@ -887,12 +899,12 @@
btm_cb.cmn_ble_vsc_cb.adv_filter_extended_features_mask = 0x00;
}
- LOG_VERBOSE("irk=%d, ADV ins:%d, rpa=%d, ener=%d, ext_scan=%d",
- btm_cb.cmn_ble_vsc_cb.max_irk_list_sz,
- btm_cb.cmn_ble_vsc_cb.adv_inst_max,
- btm_cb.cmn_ble_vsc_cb.rpa_offloading,
- btm_cb.cmn_ble_vsc_cb.energy_support,
- btm_cb.cmn_ble_vsc_cb.extended_scan_support);
+ log::verbose("irk={}, ADV ins:{}, rpa={}, ener={}, ext_scan={}",
+ btm_cb.cmn_ble_vsc_cb.max_irk_list_sz,
+ btm_cb.cmn_ble_vsc_cb.adv_inst_max,
+ btm_cb.cmn_ble_vsc_cb.rpa_offloading,
+ btm_cb.cmn_ble_vsc_cb.energy_support,
+ btm_cb.cmn_ble_vsc_cb.extended_scan_support);
if (btm_cb.cmn_ble_vsc_cb.max_filter > 0) btm_ble_adv_filter_init();
@@ -927,7 +939,7 @@
*
******************************************************************************/
bool BTM_BleConfigPrivacy(bool privacy_mode) {
- LOG_WARN("%s %d", __func__, (int)privacy_mode);
+ log::warn("{}", (int)privacy_mode);
/* if LE is not supported, return error */
if (!controller_get_interface()->SupportsBle()) return false;
@@ -953,8 +965,9 @@
} else /* 4.1/4.0 controller */
btm_cb.ble_ctr_cb.privacy_mode = BTM_PRIVACY_1_1;
}
- VLOG(2) << __func__ << " privacy_mode: " << btm_cb.ble_ctr_cb.privacy_mode
- << " own_addr_type: " << btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type;
+ log::verbose("privacy_mode: {} own_addr_type: {}",
+ btm_cb.ble_ctr_cb.privacy_mode,
+ btm_cb.ble_ctr_cb.addr_mgnt_cb.own_addr_type);
GAP_BleAttrDBUpdate(GATT_UUID_GAP_CENTRAL_ADDR_RESOL, &gap_ble_attr_value);
@@ -1007,7 +1020,7 @@
static void sync_queue_add(sync_node_t* p_param) {
std::unique_lock<std::mutex> guard(sync_queue_mutex_);
if (!sync_queue) {
- LOG_INFO("%s: allocating sync queue", __func__);
+ log::info("allocating sync queue");
sync_queue = list_new(osi_free);
CHECK(sync_queue != NULL);
}
@@ -1020,12 +1033,12 @@
}
static void sync_queue_advance() {
- LOG_DEBUG("%s", "");
+ log::debug("");
std::unique_lock<std::mutex> guard(sync_queue_mutex_);
if (sync_queue && !list_is_empty(sync_queue)) {
sync_node_t* p_head = (sync_node_t*)list_front(sync_queue);
- LOG_INFO("queue_advance");
+ log::info("queue_advance");
list_remove(sync_queue, p_head);
}
}
@@ -1043,10 +1056,10 @@
node = list_next(node);
if (sync_request->sid == p_param->sid &&
sync_request->address == p_param->address) {
- LOG_INFO("%s: removing connection request SID=%04X, bd_addr=%s, busy=%d",
- __func__, sync_request->sid,
- ADDRESS_TO_LOGGABLE_CSTR(sync_request->address),
- sync_request->busy);
+ log::info("removing connection request SID={:04X}, bd_addr={}, busy={}",
+ sync_request->sid,
+ ADDRESS_TO_LOGGABLE_CSTR(sync_request->address),
+ sync_request->busy);
list_remove(sync_queue, sync_request);
}
}
@@ -1066,7 +1079,7 @@
int index = btm_ble_get_psync_index(sid, addr);
if (index == MAX_SYNC_TRANSACTION) {
- LOG_ERROR("Failed to get sync transfer index");
+ log::error("Failed to get sync transfer index");
return;
}
@@ -1083,16 +1096,16 @@
static void btm_queue_sync_next() {
if (!sync_queue || list_is_empty(sync_queue)) {
- LOG_DEBUG("sync_queue empty");
+ log::debug("sync_queue empty");
return;
}
sync_node_t* p_head = (sync_node_t*)list_front(sync_queue);
- LOG_INFO("%s: executing sync request SID=%04X, bd_addr=%s", __func__,
- p_head->sid, ADDRESS_TO_LOGGABLE_CSTR(p_head->address));
+ log::info("executing sync request SID={:04X}, bd_addr={}", p_head->sid,
+ ADDRESS_TO_LOGGABLE_CSTR(p_head->address));
if (p_head->busy) {
- LOG_DEBUG("BUSY");
+ log::debug("BUSY");
return;
}
@@ -1105,11 +1118,11 @@
static void btm_ble_sync_queue_handle(uint16_t event, char* param) {
switch (event) {
case BTM_QUEUE_SYNC_REQ_EVT:
- LOG_DEBUG("BTIF_QUEUE_SYNC_REQ_EVT");
+ log::debug("BTIF_QUEUE_SYNC_REQ_EVT");
sync_queue_add((sync_node_t*)param);
break;
case BTM_QUEUE_SYNC_ADVANCE_EVT:
- LOG_DEBUG("BTIF_QUEUE_ADVANCE_EVT");
+ log::debug("BTIF_QUEUE_ADVANCE_EVT");
sync_queue_advance();
break;
case BTM_QUEUE_SYNC_CLEANUP_EVT:
@@ -1121,7 +1134,7 @@
void btm_queue_start_sync_req(uint8_t sid, RawAddress address, uint16_t skip,
uint16_t timeout) {
- LOG_DEBUG("address = %s, sid = %d", ADDRESS_TO_LOGGABLE_CSTR(address), sid);
+ log::debug("address = {}, sid = {}", ADDRESS_TO_LOGGABLE_CSTR(address), sid);
sync_node_t node = {};
node.sid = sid;
node.address = address;
@@ -1131,12 +1144,12 @@
}
static void btm_sync_queue_advance() {
- LOG_DEBUG("%s", "");
+ log::debug("");
btm_ble_sync_queue_handle(BTM_QUEUE_SYNC_ADVANCE_EVT, nullptr);
}
static void btm_ble_start_sync_timeout(void* data) {
- LOG_DEBUG("%s", "");
+ log::debug("");
sync_node_t* p_head = (sync_node_t*)list_front(sync_queue);
uint8_t adv_sid = p_head->sid;
RawAddress address = p_head->address;
@@ -1144,7 +1157,7 @@
int index = btm_ble_get_psync_index(adv_sid, address);
if (index == MAX_SYNC_TRANSACTION) {
- LOG_ERROR("Failed to get sync transfer index");
+ log::error("Failed to get sync transfer index");
return;
}
@@ -1168,7 +1181,7 @@
for (i = 0; i < MAX_SYNC_TRANSACTION; i++) {
if (btm_ble_pa_sync_cb.p_sync[i].sync_handle == handle &&
btm_ble_pa_sync_cb.p_sync[i].sync_state == PERIODIC_SYNC_ESTABLISHED) {
- LOG_DEBUG("found index at %d", i);
+ log::debug("found index at {}", i);
return i;
}
}
@@ -1180,7 +1193,7 @@
for (i = 0; i < MAX_SYNC_TRANSACTION; i++) {
if (btm_ble_pa_sync_cb.p_sync[i].sid == adv_sid &&
btm_ble_pa_sync_cb.p_sync[i].remote_bda == addr) {
- LOG_DEBUG("found index at %d", i);
+ log::debug("found index at {}", i);
return i;
}
}
@@ -1191,7 +1204,7 @@
int i;
for (i = 0; i < MAX_SYNC_TRANSACTION; i++) {
if (btm_ble_pa_sync_cb.sync_transfer[i].conn_handle == conn_handle) {
- LOG_DEBUG("found index at %d", i);
+ log::debug("found index at {}", i);
return i;
}
}
@@ -1213,14 +1226,14 @@
const RawAddress& addr, uint8_t phy,
uint16_t interval,
uint8_t adv_clock_accuracy) {
- LOG_DEBUG(
- "[PSync]: status=%d, sync_handle=%d, s_id=%d, "
- "addr_type=%d, adv_phy=%d,adv_interval=%d, clock_acc=%d",
+ log::debug(
+ "[PSync]: status={}, sync_handle={}, s_id={}, addr_type={}, "
+ "adv_phy={},adv_interval={}, clock_acc={}",
status, sync_handle, adv_sid, address_type, phy, interval,
adv_clock_accuracy);
/*if (param_len != ADV_SYNC_ESTB_EVT_LEN) {
- LOG_ERROR("[PSync]%s: Invalid event length",__func__);
+ log::error("[PSync]Invalid event length");
STREAM_TO_UINT8(status, param);
if (status == BTM_SUCCESS) {
STREAM_TO_UINT16(sync_handle, param);
@@ -1241,9 +1254,9 @@
}
int index = btm_ble_get_psync_index(adv_sid, bda);
if (index == MAX_SYNC_TRANSACTION) {
- LOG_WARN("[PSync]%s: Invalid index for sync established", __func__);
+ log::warn("[PSync]: Invalid index for sync established");
if (status == BTM_SUCCESS) {
- LOG_WARN("%s: Terminate sync", __func__);
+ log::warn("Terminate sync");
if (BleScanningManager::IsInitialized()) {
BleScanningManager::Get()->PeriodicScanTerminate(sync_handle);
}
@@ -1271,9 +1284,9 @@
int8_t rssi, uint8_t cte_type,
uint8_t data_status, uint8_t data_len,
const uint8_t* periodic_data) {
- LOG_DEBUG(
- "[PSync]: sync_handle = %u, tx_power = %d, rssi = %d,"
- "cte_type = %u, data_status = %u, data_len = %u",
+ log::debug(
+ "[PSync]: sync_handle = {}, tx_power = {}, rssi = {},cte_type = {}, "
+ "data_status = {}, data_len = {}",
sync_handle, tx_power, rssi, cte_type, data_status, data_len);
std::vector<uint8_t> data;
@@ -1282,11 +1295,11 @@
}
int index = btm_ble_get_psync_index_from_handle(sync_handle);
if (index == MAX_SYNC_TRANSACTION) {
- LOG_ERROR("[PSync]: index not found for handle %u", sync_handle);
+ log::error("[PSync]: index not found for handle {}", sync_handle);
return;
}
tBTM_BLE_PERIODIC_SYNC* ps = &btm_ble_pa_sync_cb.p_sync[index];
- LOG_DEBUG("%s", "[PSync]: invoking callback");
+ log::debug("[PSync]: invoking callback");
ps->sync_report_cb.Run(sync_handle, tx_power, rssi, data_status, data);
}
@@ -1298,11 +1311,11 @@
*
******************************************************************************/
void btm_ble_periodic_adv_sync_lost(uint16_t sync_handle) {
- LOG_DEBUG("[PSync]: sync_handle = %d", sync_handle);
+ log::debug("[PSync]: sync_handle = {}", sync_handle);
int index = btm_ble_get_psync_index_from_handle(sync_handle);
if (index == MAX_SYNC_TRANSACTION) {
- LOG_ERROR("[PSync]: index not found for handle %u", sync_handle);
+ log::error("[PSync]: index not found for handle {}", sync_handle);
return;
}
tBTM_BLE_PERIODIC_SYNC* ps = &btm_ble_pa_sync_cb.p_sync[index];
@@ -1324,11 +1337,11 @@
******************************************************************************/
void btm_ble_periodic_syc_transfer_cmd_cmpl(uint8_t status,
uint16_t conn_handle) {
- LOG_DEBUG("[PAST]: status = %d, conn_handle =%d", status, conn_handle);
+ log::debug("[PAST]: status = {}, conn_handle ={}", status, conn_handle);
int index = btm_ble_get_sync_transfer_index(conn_handle);
if (index == MAX_SYNC_TRANSACTION) {
- LOG_ERROR("[PAST]:Invalid, conn_handle %u not found in DB", conn_handle);
+ log::error("[PAST]:Invalid, conn_handle {} not found in DB", conn_handle);
return;
}
@@ -1342,7 +1355,7 @@
}
void btm_ble_periodic_syc_transfer_param_cmpl(uint8_t status) {
- LOG_DEBUG("[PAST]: status = %d", status);
+ log::debug("[PAST]: status = {}", status);
}
/*******************************************************************************
@@ -1353,7 +1366,7 @@
*
******************************************************************************/
void btm_ble_biginfo_adv_report_rcvd(const uint8_t* p, uint16_t param_len) {
- LOG_DEBUG("[PAST]: BIGINFO report received, len=%u", param_len);
+ log::debug("[PAST]: BIGINFO report received, len={}", param_len);
uint16_t sync_handle, iso_interval, max_pdu, max_sdu;
uint8_t num_bises, nse, bn, pto, irc, phy, framing, encryption;
uint32_t sdu_interval;
@@ -1363,7 +1376,7 @@
// for sdu_interval, 2 bytes for max_sdu, 1 byte each for phy, framing,
// encryption
if (param_len < 19) {
- LOG_ERROR("Insufficient data");
+ log::error("Insufficient data");
return;
}
@@ -1380,21 +1393,20 @@
STREAM_TO_UINT8(phy, p);
STREAM_TO_UINT8(framing, p);
STREAM_TO_UINT8(encryption, p);
- LOG_DEBUG(
- "[PAST]:sync_handle %u, num_bises = %u, nse = %u,"
- "iso_interval = %d, bn = %u, pto = %u, irc = %u, max_pdu = %u "
- "sdu_interval = %d, max_sdu = %u, phy = %u, framing = %u, encryption = "
- "%u",
+ log::debug(
+ "[PAST]:sync_handle {}, num_bises = {}, nse = {},iso_interval = {}, bn = "
+ "{}, pto = {}, irc = {}, max_pdu = {} sdu_interval = {}, max_sdu = {}, "
+ "phy = {}, framing = {}, encryption = {}",
sync_handle, num_bises, nse, iso_interval, bn, pto, irc, max_pdu,
sdu_interval, max_sdu, phy, framing, encryption);
int index = btm_ble_get_psync_index_from_handle(sync_handle);
if (index == MAX_SYNC_TRANSACTION) {
- LOG_ERROR("[PSync]: index not found for handle %u", sync_handle);
+ log::error("[PSync]: index not found for handle {}", sync_handle);
return;
}
tBTM_BLE_PERIODIC_SYNC* ps = &btm_ble_pa_sync_cb.p_sync[index];
- LOG_DEBUG("%s", "[PSync]: invoking callback");
+ log::debug("[PSync]: invoking callback");
ps->biginfo_report_cb.Run(sync_handle, encryption ? true : false);
}
@@ -1408,9 +1420,9 @@
*
******************************************************************************/
void btm_ble_periodic_adv_sync_tx_rcvd(const uint8_t* p, uint16_t param_len) {
- LOG_DEBUG("[PAST]: PAST received, param_len=%u", param_len);
+ log::debug("[PAST]: PAST received, param_len={}", param_len);
if (param_len < 19) {
- LOG_ERROR("%s", "Insufficient data");
+ log::error("Insufficient data");
return;
}
uint8_t status, adv_sid, address_type, adv_phy, clk_acc;
@@ -1426,10 +1438,10 @@
STREAM_TO_UINT8(adv_phy, p);
STREAM_TO_UINT16(pa_int, p);
STREAM_TO_UINT8(clk_acc, p);
- LOG_VERBOSE(
- "[PAST]: status = %u, conn_handle = %u, service_data = %u,"
- " sync_handle = %u, adv_sid = %u, address_type = %u, addr = %s,"
- " adv_phy = %u, pa_int = %u, clk_acc = %u",
+ log::verbose(
+ "[PAST]: status = {}, conn_handle = {}, service_data = {}, sync_handle = "
+ "{}, adv_sid = {}, address_type = {}, addr = {}, adv_phy = {}, pa_int = "
+ "{}, clk_acc = {}",
status, conn_handle, service_data, sync_handle, adv_sid, address_type,
ADDRESS_TO_LOGGABLE_CSTR(addr), adv_phy, pa_int, clk_acc);
if (syncRcvdCbRegistered) {
@@ -1469,7 +1481,8 @@
.type = *p_peer_addr_type,
.bda = p_peer_addr_ptr,
};
- LOG_DEBUG("Received BLE connect event %s", ADDRESS_TO_LOGGABLE_CSTR(ble_bd_addr));
+ log::debug("Received BLE connect event {}",
+ ADDRESS_TO_LOGGABLE_CSTR(ble_bd_addr));
evt_type = btm_cb.ble_ctr_cb.inq_var.directed_conn;
@@ -1546,7 +1559,7 @@
*
******************************************************************************/
uint16_t BTM_BleReadDiscoverability() {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
return (btm_cb.ble_ctr_cb.inq_var.discoverable_mode);
}
@@ -1562,7 +1575,7 @@
*
******************************************************************************/
uint16_t BTM_BleReadConnectability() {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
return (btm_cb.ble_ctr_cb.inq_var.connectable_mode);
}
@@ -1656,7 +1669,7 @@
btm_ble_update_dmt_flag_bits(&flag, connect_mode, disc_mode);
- LOG_INFO("disc_mode %04x", disc_mode);
+ log::info("disc_mode {:04x}", disc_mode);
/* update discoverable flag */
if (disc_mode & BTM_BLE_LIMITED_DISCOVERABLE) {
flag &= ~BTM_BLE_GEN_DISC_FLAG;
@@ -1695,8 +1708,7 @@
own_addr_type = p_addr_cb->own_addr_type;
uint16_t adv_int_min, adv_int_max;
- LOG_VERBOSE("%s mode=0x%0x combined_mode=0x%x", __func__, mode,
- combined_mode);
+ log::verbose("mode=0x{:0x} combined_mode=0x{:x}", mode, combined_mode);
/*** Check mode parameter ***/
if (mode > BTM_BLE_MAX_DISCOVERABLE) return (BTM_ILLEGAL_VALUE);
@@ -1715,8 +1727,8 @@
alarm_cancel(btm_cb.ble_ctr_cb.inq_var.fast_adv_timer);
/* update adv params if start advertising */
- LOG_VERBOSE("evt_type=0x%x p-cb->evt_type=0x%x ", evt_type,
- btm_cb.ble_ctr_cb.inq_var.evt_type);
+ log::verbose("evt_type=0x{:x} p-cb->evt_type=0x{:x} ", evt_type,
+ btm_cb.ble_ctr_cb.inq_var.evt_type);
if (new_mode == BTM_BLE_ADV_ENABLE) {
btm_ble_set_adv_flag(btm_cb.btm_inq_vars.connectable_mode, combined_mode);
@@ -1753,8 +1765,8 @@
/* set up stop advertising timer */
if (status == BTM_SUCCESS && mode == BTM_BLE_LIMITED_DISCOVERABLE) {
- LOG_VERBOSE("start timer for limited disc mode duration=%d ms",
- BTM_BLE_GAP_LIM_TIMEOUT_MS);
+ log::verbose("start timer for limited disc mode duration={} ms",
+ BTM_BLE_GAP_LIM_TIMEOUT_MS);
/* start Tgap(lim_timeout) */
alarm_set_on_mloop(
btm_cb.ble_ctr_cb.inq_var.inquiry_timer, BTM_BLE_GAP_LIM_TIMEOUT_MS,
@@ -1785,8 +1797,7 @@
own_addr_type = p_addr_cb->own_addr_type;
uint16_t adv_int_min, adv_int_max;
- LOG_VERBOSE("%s mode=0x%0x combined_mode=0x%x", __func__, mode,
- combined_mode);
+ log::verbose("mode=0x{:0x} combined_mode=0x{:x}", mode, combined_mode);
/*** Check mode parameter ***/
if (mode > BTM_BLE_MAX_CONNECTABLE) return (BTM_ILLEGAL_VALUE);
@@ -1871,9 +1882,9 @@
tBTM_BLE_SCAN_COND_OP action_type,
tBTM_STATUS btm_status) {
if (btm_status != btm_status_value(BTM_SUCCESS)) {
- LOG_ERROR("%s, %d", __func__, btm_status);
+ log::error("{}", btm_status);
} else {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
}
}
@@ -1892,13 +1903,13 @@
*
******************************************************************************/
tBTM_STATUS btm_ble_start_inquiry(uint8_t duration) {
- LOG_VERBOSE("btm_ble_start_inquiry: inq_active = 0x%02x",
- btm_cb.btm_inq_vars.inq_active);
+ log::verbose("btm_ble_start_inquiry: inq_active = 0x{:02x}",
+ btm_cb.btm_inq_vars.inq_active);
/* if selective connection is active, or inquiry is already active, reject it
*/
if (btm_cb.ble_ctr_cb.is_ble_inquiry_active()) {
- LOG_ERROR("LE Inquiry is active, can not start inquiry");
+ log::error("LE Inquiry is active, can not start inquiry");
return (BTM_BUSY);
}
@@ -1918,10 +1929,8 @@
BTM_BleAdvFilterParamSetup(BTM_BLE_SCAN_COND_ADD, static_cast<tBTM_BLE_PF_FILT_INDEX>(0),
std::move(adv_filt_param), base::Bind(btm_ble_scan_filt_param_cfg_evt));
- uint16_t scan_interval = osi_property_get_int32(kPropertyInquiryScanInterval,
- BTM_BLE_LOW_LATENCY_SCAN_INT);
- uint16_t scan_window = osi_property_get_int32(kPropertyInquiryScanWindow,
- BTM_BLE_LOW_LATENCY_SCAN_WIN);
+ uint16_t scan_interval, scan_window;
+ std::tie(scan_interval, scan_window) = get_low_latency_scan_params();
if (!btm_cb.ble_ctr_cb.is_ble_scan_active()) {
cache.ClearAll();
@@ -1932,7 +1941,7 @@
btm_ble_start_scan();
} else if ((btm_cb.ble_ctr_cb.inq_var.scan_interval != scan_interval) ||
(btm_cb.ble_ctr_cb.inq_var.scan_window != scan_window)) {
- LOG_VERBOSE("%s, restart LE scan with low latency scan params", __func__);
+ log::verbose("restart LE scan with low latency scan params");
if (IS_FLAG_ENABLED(le_scan_parameters_fix)) {
btm_cb.ble_ctr_cb.inq_var.scan_interval = scan_interval;
btm_cb.ble_ctr_cb.inq_var.scan_window = scan_window;
@@ -1947,8 +1956,8 @@
btm_cb.btm_inq_vars.inq_active |= BTM_BLE_GENERAL_INQUIRY;
btm_cb.ble_ctr_cb.set_ble_inquiry_active();
- LOG_VERBOSE("btm_ble_start_inquiry inq_active = 0x%02x",
- btm_cb.btm_inq_vars.inq_active);
+ log::verbose("btm_ble_start_inquiry inq_active = 0x{:02x}",
+ btm_cb.btm_inq_vars.inq_active);
if (duration != 0) {
/* start inquiry timer */
@@ -2012,7 +2021,7 @@
tINQ_DB_ENT* p_i = btm_inq_db_find(remote_bda);
if (p_i && !ble_evt_type_is_connectable(p_i->inq_info.results.ble_evt_type)) {
- LOG_VERBOSE("name request to non-connectable device failed.");
+ log::verbose("name request to non-connectable device failed.");
return BTM_ERR_PROCESSING;
}
@@ -2072,10 +2081,10 @@
tBTM_BLE_LOCAL_ADV_DATA* p_adv_data = &btm_cb.ble_ctr_cb.inq_var.adv_data;
uint8_t* p;
- LOG_VERBOSE("btm_ble_update_adv_flag new=0x%x", flag);
+ log::verbose("btm_ble_update_adv_flag new=0x{:x}", flag);
if (p_adv_data->p_flags != NULL) {
- LOG_VERBOSE("btm_ble_update_adv_flag old=0x%x", *p_adv_data->p_flags);
+ log::verbose("btm_ble_update_adv_flag old=0x{:x}", *p_adv_data->p_flags);
*p_adv_data->p_flags = flag;
} else /* no FLAGS in ADV data*/
{
@@ -2388,13 +2397,13 @@
if (should_process_flags && (p_cur->flag & BTM_BLE_BREDR_NOT_SPT) == 0 &&
!ble_evt_type_is_directed(evt_type)) {
if (p_cur->ble_addr_type != BLE_ADDR_RANDOM) {
- LOG_VERBOSE("NOT_BR_EDR support bit not set, treat device as DUMO");
+ log::verbose("NOT_BR_EDR support bit not set, treat device as DUMO");
p_cur->device_type |= BT_DEVICE_TYPE_DUMO;
} else {
- LOG_VERBOSE("Random address, treat device as LE only");
+ log::verbose("Random address, treat device as LE only");
}
} else {
- LOG_VERBOSE("NOT_BR/EDR support bit set, treat device as LE only");
+ log::verbose("NOT_BR/EDR support bit set, treat device as LE only");
}
}
@@ -2402,7 +2411,7 @@
/* map address to security record */
bool match = btm_identity_addr_to_random_pseudo(&bda, addr_type, false);
- VLOG(1) << __func__ << ": bda=" << bda;
+ log::verbose("bda={}", ADDRESS_TO_LOGGABLE_STR(bda));
/* always do RRA resolution on host */
if (!match && BTM_BLE_IS_RESOLVE_BDA(bda)) {
tBTM_SEC_DEV_REC* match_rec = btm_ble_resolve_random_addr(bda);
@@ -2422,181 +2431,6 @@
}
/**
- * This function is called when extended advertising report event is received .
- * It updates the inquiry database. If the inquiry database is full, the oldest
- * entry is discarded.
- */
-void btm_ble_process_ext_adv_pkt(uint8_t data_len, const uint8_t* data) {
- RawAddress bda, direct_address;
- const uint8_t* p = data;
- uint8_t addr_type, num_reports, pkt_data_len, primary_phy, secondary_phy,
- advertising_sid;
- int8_t rssi, tx_power;
- uint16_t event_type, periodic_adv_int, direct_address_type;
- size_t bytes_to_process;
-
- /* Only process the results if the inquiry is still active */
- if (!btm_cb.ble_ctr_cb.is_ble_scan_active()) return;
-
- bytes_to_process = 1;
-
- if (data_len < bytes_to_process) {
- LOG(ERROR) << "Malformed LE extended advertising packet: not enough room "
- "for num reports";
- return;
- }
-
- /* Extract the number of reports in this event. */
- STREAM_TO_UINT8(num_reports, p);
-
- while (num_reports--) {
- bytes_to_process += 24;
- if (data_len < bytes_to_process) {
- LOG(ERROR) << "Malformed LE extended advertising packet: not enough room "
- "for metadata";
- return;
- }
-
- /* Extract inquiry results */
- STREAM_TO_UINT16(event_type, p);
- STREAM_TO_UINT8(addr_type, p);
- STREAM_TO_BDADDR(bda, p);
- STREAM_TO_UINT8(primary_phy, p);
- STREAM_TO_UINT8(secondary_phy, p);
- STREAM_TO_UINT8(advertising_sid, p);
- STREAM_TO_INT8(tx_power, p);
- STREAM_TO_INT8(rssi, p);
- STREAM_TO_UINT16(periodic_adv_int, p);
- STREAM_TO_UINT8(direct_address_type, p);
- STREAM_TO_BDADDR(direct_address, p);
- STREAM_TO_UINT8(pkt_data_len, p);
-
- const uint8_t* pkt_data = p;
- p += pkt_data_len; /* Advance to the the next packet*/
-
- bytes_to_process += pkt_data_len;
- if (data_len < bytes_to_process) {
- LOG(ERROR) << "Malformed LE extended advertising packet: not enough room "
- "for packet data";
- return;
- }
-
- if (rssi >= 21 && rssi <= 126) {
- LOG_ERROR("%s: bad rssi value in advertising report: %d", __func__, rssi);
- }
-
- // Store this to pass up the callback chain to GattService#onScanResult for
- // the check in ScanFilter#matches
- RawAddress original_bda = bda;
-
- if (addr_type != BLE_ADDR_ANONYMOUS) {
- btm_ble_process_adv_addr(bda, &addr_type);
- }
-
- btm_ble_process_adv_pkt_cont(
- event_type, addr_type, bda, primary_phy, secondary_phy, advertising_sid,
- tx_power, rssi, periodic_adv_int, pkt_data_len, pkt_data, original_bda);
- }
-}
-
-/**
- * This function is called when advertising report event is received. It updates
- * the inquiry database. If the inquiry database is full, the oldest entry is
- * discarded.
- */
-void btm_ble_process_adv_pkt(uint8_t data_len, const uint8_t* data) {
- RawAddress bda;
- const uint8_t* p = data;
- uint8_t legacy_evt_type, addr_type, num_reports, pkt_data_len;
- int8_t rssi;
- size_t bytes_to_process;
-
- /* Only process the results if the inquiry is still active */
- if (!btm_cb.ble_ctr_cb.is_ble_scan_active()) return;
-
- bytes_to_process = 1;
-
- if (data_len < bytes_to_process) {
- LOG(ERROR)
- << "Malformed LE advertising packet: not enough room for num reports";
- return;
- }
-
- /* Extract the number of reports in this event. */
- STREAM_TO_UINT8(num_reports, p);
-
- while (num_reports--) {
- bytes_to_process += 9;
-
- if (data_len < bytes_to_process) {
- LOG(ERROR)
- << "Malformed LE advertising packet: not enough room for metadata";
- return;
- }
-
- /* Extract inquiry results */
- STREAM_TO_UINT8(legacy_evt_type, p);
- STREAM_TO_UINT8(addr_type, p);
- STREAM_TO_BDADDR(bda, p);
- STREAM_TO_UINT8(pkt_data_len, p);
-
- const uint8_t* pkt_data = p;
- p += pkt_data_len; /* Advance to the the rssi byte */
-
- // include rssi for this check
- bytes_to_process += pkt_data_len + 1;
- if (data_len < bytes_to_process) {
- LOG(ERROR) << "Malformed LE advertising packet: not enough room for "
- "packet data and/or RSSI";
- return;
- }
-
- STREAM_TO_INT8(rssi, p);
-
- if (rssi >= 21 && rssi <= 126) {
- LOG_ERROR("%s: bad rssi value in advertising report: %d", __func__, rssi);
- }
-
- // Pass up the address to GattService#onScanResult to use in
- // ScanFilter#matches
- RawAddress original_bda = bda;
-
- btm_ble_process_adv_addr(bda, &addr_type);
-
- uint16_t event_type;
- event_type = 1 << BLE_EVT_LEGACY_BIT;
- if (legacy_evt_type == BTM_BLE_ADV_IND_EVT) {
- event_type |=
- (1 << BLE_EVT_CONNECTABLE_BIT) | (1 << BLE_EVT_SCANNABLE_BIT);
- } else if (legacy_evt_type == BTM_BLE_ADV_DIRECT_IND_EVT) {
- event_type |=
- (1 << BLE_EVT_CONNECTABLE_BIT) | (1 << BLE_EVT_DIRECTED_BIT);
- } else if (legacy_evt_type == BTM_BLE_ADV_SCAN_IND_EVT) {
- event_type |= (1 << BLE_EVT_SCANNABLE_BIT);
- } else if (legacy_evt_type == BTM_BLE_ADV_NONCONN_IND_EVT) {
- event_type = (1 << BLE_EVT_LEGACY_BIT); // 0x0010;
- } else if (legacy_evt_type == BTM_BLE_SCAN_RSP_EVT) { // SCAN_RSP;
- // We can't distinguish between "SCAN_RSP to an ADV_IND", and "SCAN_RSP to
- // an ADV_SCAN_IND", so always return "SCAN_RSP to an ADV_IND"
- event_type |= (1 << BLE_EVT_CONNECTABLE_BIT) |
- (1 << BLE_EVT_SCANNABLE_BIT) |
- (1 << BLE_EVT_SCAN_RESPONSE_BIT);
- } else {
- LOG_ERROR(
- "Malformed LE Advertising Report Event - unsupported "
- "legacy_event_type 0x%02x",
- legacy_evt_type);
- return;
- }
-
- btm_ble_process_adv_pkt_cont(
- event_type, addr_type, bda, PHY_LE_1M, PHY_LE_NO_PACKET, NO_ADI_PRESENT,
- TX_POWER_NOT_PRESENT, rssi, 0x00 /* no periodic adv */, pkt_data_len,
- pkt_data, original_bda);
- }
-}
-
-/**
* This function is called after random address resolution is done, and proceed
* to process adv packet.
*/
@@ -2638,7 +2472,8 @@
if (!data_complete) {
// If we didn't receive whole adv data yet, don't report the device.
- VLOG(1) << "Data not complete yet, waiting for more " << bda;
+ log::verbose("Data not complete yet, waiting for more {}",
+ ADDRESS_TO_LOGGABLE_STR(bda));
return;
}
@@ -2646,13 +2481,13 @@
btm_cb.ble_ctr_cb.inq_var.scan_type == BTM_BLE_SCAN_MODE_ACTI;
if (is_active_scan && is_scannable && !is_scan_resp) {
// If we didn't receive scan response yet, don't report the device.
- VLOG(1) << " Waiting for scan response " << bda;
+ log::verbose(" Waiting for scan response {}", ADDRESS_TO_LOGGABLE_STR(bda));
return;
}
if (!AdvertiseDataParser::IsValid(adv_data)) {
- VLOG(1) << __func__ << "Dropping bad advertisement packet: "
- << base::HexEncode(adv_data.data(), adv_data.size());
+ log::verbose("Dropping bad advertisement packet: {}",
+ base::HexEncode(adv_data.data(), adv_data.size()));
cache.Clear(addr_type, bda);
return;
}
@@ -2798,7 +2633,7 @@
btm_cb.neighbor.le_inquiry.results++;
btm_cb.neighbor.le_legacy_scan.results++;
} else {
- LOG_WARN("Unable to allocate entry for inquiry result");
+ log::warn("Unable to allocate entry for inquiry result");
return;
}
} else if (p_i->inq_count !=
@@ -2849,22 +2684,6 @@
}
}
-void btm_ble_process_phy_update_pkt(uint8_t len, uint8_t* data) {
- uint8_t status, tx_phy, rx_phy;
- uint16_t handle;
-
- LOG_ASSERT(len == 5);
- uint8_t* p = data;
- STREAM_TO_UINT8(status, p);
- STREAM_TO_UINT16(handle, p);
- handle = handle & 0x0FFF;
- STREAM_TO_UINT8(tx_phy, p);
- STREAM_TO_UINT8(rx_phy, p);
-
- gatt_notify_phy_updated(static_cast<tHCI_STATUS>(status), handle, tx_phy,
- rx_phy);
-}
-
/*******************************************************************************
*
* Function btm_ble_start_scan
@@ -2950,19 +2769,18 @@
/* If no more scan activity, stop LE scan now */
if (!btm_cb.ble_ctr_cb.is_ble_scan_active()) {
btm_ble_stop_scan();
- } else if ((btm_cb.ble_ctr_cb.inq_var.scan_interval !=
- BTM_BLE_LOW_LATENCY_SCAN_INT) ||
- (btm_cb.ble_ctr_cb.inq_var.scan_window !=
- BTM_BLE_LOW_LATENCY_SCAN_WIN)) {
- LOG_VERBOSE("%s: setting default params for ongoing observe", __func__);
+ } else if (get_low_latency_scan_params() !=
+ std::pair(btm_cb.ble_ctr_cb.inq_var.scan_interval,
+ btm_cb.ble_ctr_cb.inq_var.scan_window)) {
+ log::verbose("setting default params for ongoing observe");
btm_ble_stop_scan();
btm_ble_start_scan();
}
/* If we have a callback registered for inquiry complete, call it */
- LOG_VERBOSE("BTM Inq Compl Callback: status 0x%02x, num results %d",
- btm_cb.btm_inq_vars.inq_cmpl_info.status,
- btm_cb.btm_inq_vars.inq_cmpl_info.num_resp);
+ log::verbose("BTM Inq Compl Callback: status 0x{:02x}, num results {}",
+ btm_cb.btm_inq_vars.inq_cmpl_info.status,
+ btm_cb.btm_inq_vars.inq_cmpl_info.num_resp);
btm_process_inq_complete(
HCI_SUCCESS,
@@ -3029,7 +2847,7 @@
break;
default:
- LOG_ERROR("unknown adv event : %d", adv_evt);
+ log::error("unknown adv event : {}", adv_evt);
break;
}
@@ -3159,11 +2977,11 @@
if (status != HCI_SUCCESS) {
if (status != HCI_ERR_UNSUPPORTED_REM_FEATURE) {
- LOG_ERROR("Failed to read remote features status:%s",
- hci_error_code_text(static_cast<tHCI_STATUS>(status)).c_str());
+ log::error("Failed to read remote features status:{}",
+ hci_error_code_text(static_cast<tHCI_STATUS>(status)).c_str());
return;
}
- LOG_WARN("Remote does not support reading remote feature");
+ log::warn("Remote does not support reading remote feature");
}
if (status == HCI_SUCCESS) {
@@ -3174,7 +2992,7 @@
}
if (!acl_set_peer_le_features_from_handle(handle, p)) {
- LOG_ERROR(
+ log::error(
"Unable to find existing connection after read remote features");
return;
}
@@ -3185,7 +3003,7 @@
return;
err_out:
- LOG_ERROR("Bogus event packet, too short");
+ log::error("Bogus event packet, too short");
}
/*******************************************************************************
@@ -3328,7 +3146,7 @@
*
******************************************************************************/
void btm_ble_init(void) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
alarm_free(btm_cb.ble_ctr_cb.observer_timer);
alarm_free(btm_cb.ble_ctr_cb.inq_var.fast_adv_timer);
@@ -3388,7 +3206,7 @@
if (request_state_mask == BTM_BLE_STATE_INVALID ||
request_state_mask > BTM_BLE_STATE_SCAN_ADV_BIT ||
(request_state_mask & (request_state_mask - 1)) != 0) {
- LOG_ERROR("illegal state requested: %d", request_state_mask);
+ log::error("illegal state requested: {}", request_state_mask);
return rt;
}
@@ -3403,7 +3221,7 @@
controller_get_interface()->get_ble_supported_states();
if (!BTM_LE_STATES_SUPPORTED(ble_supported_states, bit_num)) {
- LOG_ERROR("state requested not supported: %d", request_state);
+ log::error("state requested not supported: {}", request_state);
return rt;
}
diff --git a/system/stack/btm/btm_ble_int_types.h b/system/stack/btm/btm_ble_int_types.h
index 443fc79..230f064 100644
--- a/system/stack/btm/btm_ble_int_types.h
+++ b/system/stack/btm/btm_ble_int_types.h
@@ -81,8 +81,8 @@
typedef struct {
uint16_t discoverable_mode;
uint16_t connectable_mode;
- uint32_t scan_window;
- uint32_t scan_interval;
+ uint16_t scan_window;
+ uint16_t scan_interval;
uint8_t scan_type; /* current scan type: active or passive */
tBTM_BLE_AFP afp; /* advertising filter policy */
diff --git a/system/stack/btm/btm_ble_privacy.cc b/system/stack/btm/btm_ble_privacy.cc
index 5c0cffb..90c8b75 100644
--- a/system/stack/btm/btm_ble_privacy.cc
+++ b/system/stack/btm/btm_ble_privacy.cc
@@ -25,6 +25,8 @@
#include "stack/include/btm_ble_privacy.h"
+#include <bluetooth/log.h>
+
#include "btm_dev.h"
#include "btm_sec_cb.h"
#include "btm_sec_int_types.h"
@@ -38,6 +40,8 @@
#include "stack/include/btm_api.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
extern tBTM_CB btm_cb;
/* RPA offload VSC specifics */
@@ -181,7 +185,7 @@
i++;
}
- LOG_ERROR("no index found");
+ log::error("no index found");
return i;
}
@@ -233,13 +237,13 @@
uint8_t status = 0;
if (evt_len < 1) {
- LOG_ERROR("malformatted event packet: containing zero bytes");
+ log::error("malformatted event packet: containing zero bytes");
return;
}
STREAM_TO_UINT8(status, p);
- LOG_VERBOSE("status=%d", status);
+ log::verbose("status={}", status);
if (status == HCI_SUCCESS) {
if (evt_len >= 3) {
@@ -262,8 +266,8 @@
btm_cb.ble_ctr_cb.resolving_list_avail_size =
controller_get_interface()->get_ble_resolving_list_max_size();
- LOG_VERBOSE("resolving_list_avail_size=%d",
- btm_cb.ble_ctr_cb.resolving_list_avail_size);
+ log::verbose("resolving_list_avail_size={}",
+ btm_cb.ble_ctr_cb.resolving_list_avail_size);
list_foreach(btm_sec_cb.sec_dev_rec, clear_resolving_list_bit, NULL);
}
@@ -283,17 +287,17 @@
uint8_t status;
if (evt_len < 1) {
- LOG_ERROR("malformatted event packet: containing zero byte");
+ log::error("malformatted event packet: containing zero byte");
return;
}
STREAM_TO_UINT8(status, p);
- LOG_VERBOSE("status=%d", status);
+ log::verbose("status={}", status);
RawAddress pseudo_bda;
if (!btm_ble_deq_resolving_pending(pseudo_bda)) {
- LOG_VERBOSE("no pending resolving list operation");
+ log::verbose("no pending resolving list operation");
return;
}
@@ -310,7 +314,7 @@
HCI_ERR_MEMORY_FULL) /* BT_ERROR_CODE_MEMORY_CAPACITY_EXCEEDED */
{
btm_cb.ble_ctr_cb.resolving_list_avail_size = 0;
- LOG_VERBOSE("Resolving list Full");
+ log::verbose("Resolving list Full");
}
}
@@ -331,10 +335,10 @@
STREAM_TO_UINT8(status, p);
- LOG_VERBOSE("status=%d", status);
+ log::verbose("status={}", status);
if (!btm_ble_deq_resolving_pending(pseudo_bda)) {
- LOG_ERROR("no pending resolving list operation");
+ log::error("no pending resolving list operation");
return;
}
@@ -365,10 +369,10 @@
STREAM_TO_UINT8(status, p);
- LOG_VERBOSE("status=%d", status);
+ log::verbose("status={}", status);
if (!btm_ble_deq_resolving_pending(pseudo_bda)) {
- LOG_ERROR("no pending resolving list operation");
+ log::error("no pending resolving list operation");
return;
}
@@ -379,7 +383,7 @@
p += (2 + 16 + 1 + 6);
STREAM_TO_BDADDR(rra, p);
- LOG_INFO("peer_addr:%s", ADDRESS_TO_LOGGABLE_CSTR(rra));
+ log::info("peer_addr:{}", ADDRESS_TO_LOGGABLE_CSTR(rra));
} else {
STREAM_TO_BDADDR(rra, p);
}
@@ -407,7 +411,7 @@
op_subcode = *(p + 1);
- LOG_VERBOSE("op_subcode=%d", op_subcode);
+ log::verbose("op_subcode={}", op_subcode);
if (op_subcode == BTM_BLE_META_CLEAR_IRK_LIST) {
btm_ble_clear_resolving_list_complete(p, evt_len);
@@ -496,11 +500,11 @@
******************************************************************************/
bool btm_ble_read_resolving_list_entry(tBTM_SEC_DEV_REC* p_dev_rec) {
if (btm_cb.ble_ctr_cb.privacy_mode < BTM_PRIVACY_1_2) {
- LOG_DEBUG("Privacy 1.2 is not enabled");
+ log::debug("Privacy 1.2 is not enabled");
return false;
}
if (!(p_dev_rec->ble.in_controller_list & BTM_RESOLVING_LIST_BIT)) {
- LOG_INFO("Unable to read resolving list entry as resolving bit not set");
+ log::info("Unable to read resolving list entry as resolving bit not set");
return false;
}
@@ -526,7 +530,7 @@
static void btm_ble_ble_unsupported_resolving_list_load_dev(
tBTM_SEC_DEV_REC* p_dev_rec) {
- LOG_INFO("Controller does not support BLE privacy");
+ log::info("Controller does not support BLE privacy");
uint8_t param[40] = {0};
uint8_t* p = param;
@@ -551,11 +555,11 @@
void btm_ble_resolving_list_load_dev(tBTM_SEC_DEV_REC& dev_rec) {
if (btm_cb.ble_ctr_cb.privacy_mode < BTM_PRIVACY_1_2) {
- LOG_DEBUG("Privacy 1.2 is not enabled");
+ log::debug("Privacy 1.2 is not enabled");
return;
}
if (controller_get_interface()->get_ble_resolving_list_max_size() == 0) {
- LOG_INFO("Controller does not support RPA offloading or privacy 1.2");
+ log::info("Controller does not support RPA offloading or privacy 1.2");
return;
}
@@ -565,14 +569,14 @@
// No need to check for local identity key validity. It remains unchanged.
if (!is_peer_identity_key_valid(dev_rec)) {
- LOG_INFO("Peer is not an RPA enabled device:%s",
- ADDRESS_TO_LOGGABLE_CSTR(dev_rec.ble.identity_address_with_type));
+ log::info("Peer is not an RPA enabled device:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(dev_rec.ble.identity_address_with_type));
return;
}
if (dev_rec.ble.in_controller_list & BTM_RESOLVING_LIST_BIT) {
- LOG_WARN("Already in Address Resolving list device:%s",
- ADDRESS_TO_LOGGABLE_CSTR(dev_rec.ble.identity_address_with_type));
+ log::warn("Already in Address Resolving list device:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(dev_rec.ble.identity_address_with_type));
return;
}
@@ -587,16 +591,16 @@
}
if (!is_ble_addr_type_known(dev_rec.ble.identity_address_with_type.type)) {
- LOG_ERROR("Adding unknown address type(%d) to Address Resolving list.",
- dev_rec.ble.identity_address_with_type.type);
+ log::error("Adding unknown address type({}) to Address Resolving list.",
+ dev_rec.ble.identity_address_with_type.type);
return;
}
bluetooth::shim::ACL_AddToAddressResolution(
dev_rec.ble.identity_address_with_type, peer_irk, local_irk);
- LOG_DEBUG("Added to Address Resolving list device:%s",
- ADDRESS_TO_LOGGABLE_CSTR(dev_rec.ble.identity_address_with_type));
+ log::debug("Added to Address Resolving list device:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(dev_rec.ble.identity_address_with_type));
dev_rec.ble.in_controller_list |= BTM_RESOLVING_LIST_BIT;
}
@@ -614,7 +618,7 @@
******************************************************************************/
void btm_ble_resolving_list_remove_dev(tBTM_SEC_DEV_REC* p_dev_rec) {
if (btm_cb.ble_ctr_cb.privacy_mode < BTM_PRIVACY_1_2) {
- LOG_DEBUG("Privacy 1.2 is not enabled");
+ log::debug("Privacy 1.2 is not enabled");
return;
}
@@ -624,7 +628,7 @@
btm_ble_update_resolving_list(p_dev_rec->bd_addr, false);
btm_ble_remove_resolving_list_entry(p_dev_rec);
} else {
- LOG_VERBOSE("Device not in resolving list");
+ log::verbose("Device not in resolving list");
}
}
@@ -656,7 +660,7 @@
// NOTE: This memory is never freed
btm_cb.ble_ctr_cb.irk_list_mask = (uint8_t*)osi_malloc(irk_mask_size);
- LOG_VERBOSE("max_irk_list_sz=%d", max_irk_list_sz);
+ log::verbose("max_irk_list_sz={}", max_irk_list_sz);
}
controller_get_interface()->set_ble_resolving_list_max_size(max_irk_list_sz);
diff --git a/system/stack/btm/btm_ble_scanner.cc b/system/stack/btm/btm_ble_scanner.cc
index 16864dd..107d710 100644
--- a/system/stack/btm/btm_ble_scanner.cc
+++ b/system/stack/btm/btm_ble_scanner.cc
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include "ble_scanner.h"
#include "ble_scanner_hci_interface.h"
@@ -22,6 +22,8 @@
#include "internal_include/stack_config.h"
#include "stack/btm/btm_ble_int.h"
+using namespace bluetooth;
+
std::mutex lock1;
namespace {
@@ -32,7 +34,7 @@
base::WeakPtr<BleScanningManagerImpl> instance_weakptr;
static void status_callback(uint8_t status) {
- VLOG(1) << __func__ << " Received status_cb with status:" << status;
+ log::verbose("Received status_cb with status:{}", status);
}
class BleScanningManagerImpl
@@ -147,13 +149,13 @@
if (BleScannerHciInterface::Get()) {
BleScanningManager::Initialize(BleScannerHciInterface::Get());
} else {
- VLOG(1) << __func__ << " BleScannerHciInterface::Get() returns null";
+ log::verbose("BleScannerHciInterface::Get() returns null");
}
if ((BleScannerHciInterface::Get()) && (BleScanningManager::Get())) {
BleScannerHciInterface::Get()->SetScanEventObserver(
(BleScanningManagerImpl*)BleScanningManager::Get().get());
} else {
- VLOG(1) << __func__ << " BleScannerHciInterface or BleScanningManager is null";
+ log::verbose("BleScannerHciInterface or BleScanningManager is null");
}
}
diff --git a/system/stack/btm/btm_ble_sec.cc b/system/stack/btm/btm_ble_sec.cc
index 3258cf0..adb241f 100644
--- a/system/stack/btm/btm_ble_sec.cc
+++ b/system/stack/btm/btm_ble_sec.cc
@@ -20,6 +20,7 @@
#include "stack/btm/btm_ble_sec.h"
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <cstddef>
#include <cstdint>
@@ -58,6 +59,8 @@
#include "stack/include/smp_api_types.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
extern tBTM_CB btm_cb;
bool btm_ble_init_pseudo_addr(tBTM_SEC_DEV_REC* p_dev_rec,
@@ -75,7 +78,7 @@
/******************************************************************************/
void BTM_SecAddBleDevice(const RawAddress& bd_addr, tBT_DEVICE_TYPE dev_type,
tBLE_ADDR_TYPE addr_type) {
- LOG_DEBUG("dev_type=0x%x", dev_type);
+ log::debug("dev_type=0x{:x}", dev_type);
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
if (!p_dev_rec) {
@@ -91,9 +94,9 @@
p_dev_rec->conn_params.supervision_tout = BTM_BLE_CONN_PARAM_UNDEF;
p_dev_rec->conn_params.peripheral_latency = BTM_BLE_CONN_PARAM_UNDEF;
- LOG_DEBUG("Device added, handle=0x%x, p_dev_rec=%p, bd_addr=%s",
- p_dev_rec->ble_hci_handle, p_dev_rec,
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::debug("Device added, handle=0x{:x}, p_dev_rec={}, bd_addr={}",
+ p_dev_rec->ble_hci_handle, fmt::ptr(p_dev_rec),
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
}
memset(p_dev_rec->sec_bd_name, 0, sizeof(tBTM_BD_NAME));
@@ -102,7 +105,7 @@
if (is_ble_addr_type_known(addr_type)) {
p_dev_rec->ble.SetAddressType(addr_type);
} else {
- LOG_WARN(
+ log::warn(
"Please do not update device record from anonymous le advertisement");
}
@@ -111,8 +114,8 @@
if (p_info) {
p_info->results.ble_addr_type = p_dev_rec->ble.AddressType();
p_dev_rec->device_type |= p_info->results.device_type;
- LOG_DEBUG("InqDb device_type =0x%x addr_type=0x%x", p_dev_rec->device_type,
- p_info->results.ble_addr_type);
+ log::debug("InqDb device_type =0x{:x} addr_type=0x{:x}",
+ p_dev_rec->device_type, p_info->results.ble_addr_type);
p_info->results.device_type = p_dev_rec->device_type;
}
}
@@ -128,7 +131,7 @@
*
******************************************************************************/
bool BTM_GetRemoteDeviceName(const RawAddress& bd_addr, BD_NAME bd_name) {
- LOG_VERBOSE("bd_addr:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::verbose("bd_addr:{}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
bool ret = FALSE;
bt_bdname_t bdname;
@@ -138,7 +141,7 @@
if (btif_storage_get_remote_device_property(&bd_addr, &prop_name) ==
BT_STATUS_SUCCESS) {
- LOG_VERBOSE("NV name=%s", bdname.name);
+ log::verbose("NV name={}", reinterpret_cast<const char*>(bdname.name));
strncpy((char*)bd_name, (char*)bdname.name, BD_NAME_LEN + 1);
ret = TRUE;
}
@@ -167,13 +170,13 @@
(key_type != BTM_LE_KEY_PENC && key_type != BTM_LE_KEY_PID &&
key_type != BTM_LE_KEY_PCSRK && key_type != BTM_LE_KEY_LENC &&
key_type != BTM_LE_KEY_LCSRK && key_type != BTM_LE_KEY_LID)) {
- LOG_WARN("Wrong Type, or No Device record for bdaddr:%s, Type:0%hhu",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), key_type);
+ log::warn("Wrong Type, or No Device record for bdaddr:{}, Type:0{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr), key_type);
return;
}
- LOG_DEBUG("Adding BLE key device:%s key_type:%hhu",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), key_type);
+ log::debug("Adding BLE key device:{} key_type:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr), key_type);
btm_sec_save_le_key(bd_addr, key_type, p_le_key, false);
// Only set peer irk. Local irk is always the same.
@@ -198,7 +201,7 @@
******************************************************************************/
void BTM_BleLoadLocalKeys(uint8_t key_type, tBTM_BLE_LOCAL_KEYS* p_key) {
tBTM_SEC_DEVCB* p_devcb = &btm_sec_cb.devcb;
- LOG_VERBOSE("type:%d", key_type);
+ log::verbose("type:{}", key_type);
if (p_key != NULL) {
switch (key_type) {
case BTM_BLE_KEY_TYPE_ID:
@@ -211,7 +214,7 @@
break;
default:
- LOG_ERROR("unknown key type:%d", key_type);
+ log::error("unknown key type:{}", key_type);
break;
}
}
@@ -245,8 +248,8 @@
void BTM_SecurityGrant(const RawAddress& bd_addr, uint8_t res) {
const tSMP_STATUS res_smp =
(res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_REPEATED_ATTEMPTS;
- LOG_VERBOSE("bd_addr:%s, res:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
- smp_status_text(res_smp).c_str());
+ log::verbose("bd_addr:{}, res:{}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ smp_status_text(res_smp).c_str());
BTM_LogHistory(kBtmLogTag, bd_addr, "Granted",
base::StringPrintf("passkey_status:%s",
smp_status_text(res_smp).c_str()));
@@ -271,9 +274,9 @@
void BTM_BlePasskeyReply(const RawAddress& bd_addr, uint8_t res,
uint32_t passkey) {
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
- LOG_VERBOSE("bd_addr:%s, res:%d", ADDRESS_TO_LOGGABLE_CSTR(bd_addr), res);
+ log::verbose("bd_addr:{}, res:{}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr), res);
if (p_dev_rec == NULL) {
- LOG_ERROR("Unknown device:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::error("Unknown device:{}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return;
}
@@ -302,9 +305,9 @@
******************************************************************************/
void BTM_BleConfirmReply(const RawAddress& bd_addr, uint8_t res) {
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
- LOG_VERBOSE("bd_addr:%s, res:%d", ADDRESS_TO_LOGGABLE_CSTR(bd_addr), res);
+ log::verbose("bd_addr:{}, res:{}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr), res);
if (p_dev_rec == NULL) {
- LOG_ERROR("Unknown device:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::error("Unknown device:{}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return;
}
const tSMP_STATUS res_smp =
@@ -339,7 +342,7 @@
uint8_t* p_data) {
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
if (p_dev_rec == NULL) {
- LOG_ERROR("Unknown device:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::error("Unknown device:{}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return;
}
@@ -370,7 +373,7 @@
uint8_t* p_c, uint8_t* p_r) {
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
if (p_dev_rec == NULL) {
- LOG_ERROR("Unknown device:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::error("Unknown device:{}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return;
}
@@ -416,8 +419,8 @@
uint16_t supervision_tout) {
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
- LOG_VERBOSE("min:%u,max:%u,latency:%u,tout:%u", min_conn_int, max_conn_int,
- peripheral_latency, supervision_tout);
+ log::verbose("min:{},max:{},latency:{},tout:{}", min_conn_int, max_conn_int,
+ peripheral_latency, supervision_tout);
if (BTM_BLE_ISVALID_PARAM(min_conn_int, BTM_BLE_CONN_INT_MIN,
BTM_BLE_CONN_INT_MAX) &&
@@ -456,10 +459,10 @@
}
} else {
- LOG_ERROR("Unknown Device, setting rejected");
+ log::error("Unknown Device, setting rejected");
}
} else {
- LOG_ERROR("Illegal Connection Parameters");
+ log::error("Illegal Connection Parameters");
}
}
@@ -490,7 +493,7 @@
*p_addr_type = p_inq_info->results.ble_addr_type;
} else {
/* unknown device, assume BR/EDR */
- LOG_VERBOSE("unknown device, BR/EDR assumed");
+ log::verbose("unknown device, BR/EDR assumed");
}
} else /* there is a security device record existing */
{
@@ -500,7 +503,7 @@
if (is_ble_addr_type_known(p_inq_info->results.ble_addr_type))
p_dev_rec->ble.SetAddressType(p_inq_info->results.ble_addr_type);
else
- LOG_WARN(
+ log::warn(
"Please do not update device record from anonymous le "
"advertisement");
}
@@ -516,15 +519,15 @@
if (p_dev_rec->device_type != BT_DEVICE_TYPE_UNKNOWN) {
*p_dev_type = p_dev_rec->device_type;
} else {
- LOG_WARN("device_type not set; assuming BR/EDR");
+ log::warn("device_type not set; assuming BR/EDR");
*p_dev_type = BT_DEVICE_TYPE_BREDR;
}
*p_addr_type = BLE_ADDR_PUBLIC;
}
}
- LOG_DEBUG("Determined device_type:%s addr_type:%s",
- DeviceTypeText(*p_dev_type).c_str(),
- AddressTypeText(*p_addr_type).c_str());
+ log::debug("Determined device_type:{} addr_type:{}",
+ DeviceTypeText(*p_dev_type).c_str(),
+ AddressTypeText(*p_addr_type).c_str());
}
/*******************************************************************************
@@ -573,16 +576,16 @@
tBTM_STATUS BTM_SetBleDataLength(const RawAddress& bd_addr,
uint16_t tx_pdu_length) {
if (!controller_get_interface()->SupportsBleDataPacketLengthExtension()) {
- LOG_INFO("Local controller does not support le packet extension");
+ log::info("Local controller does not support le packet extension");
return BTM_ILLEGAL_VALUE;
}
- LOG_INFO("bd_addr:%s, tx_pdu_length:%d", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
- tx_pdu_length);
+ log::info("bd_addr:{}, tx_pdu_length:{}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ tx_pdu_length);
auto p_dev_rec = btm_find_dev(bd_addr);
if (p_dev_rec == NULL) {
- LOG_ERROR("Device %s not found", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::error("Device {} not found", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return BTM_UNKNOWN_ADDR;
}
@@ -592,8 +595,8 @@
tx_pdu_length = BTM_BLE_DATA_SIZE_MIN;
if (p_dev_rec->get_suggested_tx_octets() >= tx_pdu_length) {
- LOG_INFO("Suggested TX octect already set to controller %d >= %d",
- p_dev_rec->get_suggested_tx_octets(), tx_pdu_length);
+ log::info("Suggested TX octect already set to controller {} >= {}",
+ p_dev_rec->get_suggested_tx_octets(), tx_pdu_length);
return BTM_SUCCESS;
}
@@ -604,7 +607,7 @@
tx_time = BTM_BLE_DATA_TX_TIME_MAX;
if (!BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) {
- LOG_INFO(
+ log::info(
"Unable to set data length because no le acl link connected to device");
return BTM_WRONG_MODE;
}
@@ -612,7 +615,7 @@
uint16_t hci_handle = BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE);
if (!acl_peer_supports_ble_packet_extension(hci_handle)) {
- LOG_INFO("Remote device unable to support le packet extension");
+ log::info("Remote device unable to support le packet extension");
return BTM_ILLEGAL_VALUE;
}
@@ -650,7 +653,7 @@
if (is_originator) {
if ((security_required & BTM_SEC_OUT_FLAGS) == 0 &&
(security_required & BTM_SEC_OUT_MITM) == 0) {
- LOG_INFO("No security required for outgoing connection");
+ log::info("No security required for outgoing connection");
return BTM_SEC_OK;
}
@@ -658,7 +661,7 @@
} else {
if ((security_required & BTM_SEC_IN_FLAGS) == 0 &&
(security_required & BTM_SEC_IN_MITM) == 0) {
- LOG_VERBOSE("No security required for incoming connection");
+ log::verbose("No security required for incoming connection");
return BTM_SEC_OK;
}
@@ -668,7 +671,7 @@
tBTM_BLE_SEC_REQ_ACT ble_sec_act = {BTM_BLE_SEC_REQ_ACT_NONE};
btm_ble_link_sec_check(bdaddr, auth_req, &ble_sec_act);
- LOG_VERBOSE("ble_sec_act %d", ble_sec_act);
+ log::verbose("ble_sec_act {}", ble_sec_act);
if (ble_sec_act == BTM_BLE_SEC_REQ_ACT_DISCARD) return BTM_SEC_ENC_PENDING;
@@ -723,7 +726,7 @@
/* If there is no application registered with this PSM do not allow connection
*/
if (!p_serv_rec) {
- LOG_WARN("PSM: %d no application registered", psm);
+ log::warn("PSM: {} no application registered", psm);
(*p_callback)(&bd_addr, BT_TRANSPORT_LE, p_ref_data, BTM_MODE_UNSUPPORTED);
return BTM_ILLEGAL_VALUE;
}
@@ -734,13 +737,13 @@
if (!is_originator) {
if ((p_serv_rec->security_flags & BTM_SEC_IN_ENCRYPT) && !is_encrypted) {
- LOG_ERROR("BTM_NOT_ENCRYPTED. service security_flags=0x%x",
- p_serv_rec->security_flags);
+ log::error("BTM_NOT_ENCRYPTED. service security_flags=0x{:x}",
+ p_serv_rec->security_flags);
return BTM_NOT_ENCRYPTED;
} else if ((p_serv_rec->security_flags & BTM_SEC_IN_AUTHENTICATE) &&
!(is_link_key_authed || is_authenticated)) {
- LOG_ERROR("BTM_NOT_AUTHENTICATED. service security_flags=0x%x",
- p_serv_rec->security_flags);
+ log::error("BTM_NOT_AUTHENTICATED. service security_flags=0x{:x}",
+ p_serv_rec->security_flags);
return BTM_NOT_AUTHENTICATED;
}
/* TODO: When security is required, then must check that the key size of our
@@ -754,27 +757,27 @@
switch (sec_act) {
case BTM_SEC_OK:
- LOG_DEBUG("Security met");
+ log::debug("Security met");
p_callback(&bd_addr, BT_TRANSPORT_LE, p_ref_data, BTM_SUCCESS);
break;
case BTM_SEC_ENCRYPT:
- LOG_DEBUG("Encryption needs to be done");
+ log::debug("Encryption needs to be done");
ble_sec_act = BTM_BLE_SEC_ENCRYPT;
break;
case BTM_SEC_ENCRYPT_MITM:
- LOG_DEBUG("Pairing with MITM needs to be done");
+ log::debug("Pairing with MITM needs to be done");
ble_sec_act = BTM_BLE_SEC_ENCRYPT_MITM;
break;
case BTM_SEC_ENCRYPT_NO_MITM:
- LOG_DEBUG("Pairing with No MITM needs to be done");
+ log::debug("Pairing with No MITM needs to be done");
ble_sec_act = BTM_BLE_SEC_ENCRYPT_NO_MITM;
break;
case BTM_SEC_ENC_PENDING:
- LOG_DEBUG("Ecryption pending");
+ log::debug("Ecryption pending");
break;
}
@@ -805,8 +808,8 @@
ble_keys.counter++;
}
- LOG_VERBOSE("local=%d local sign counter=%d peer sign counter=%d", local,
- ble_keys.local_counter, ble_keys.counter);
+ log::verbose("local={} local sign counter={} peer sign counter={}", local,
+ ble_keys.local_counter, ble_keys.counter);
}
/*******************************************************************************
@@ -822,7 +825,7 @@
bool btm_ble_get_enc_key_type(const RawAddress& bd_addr, uint8_t* p_key_types) {
tBTM_SEC_DEV_REC* p_dev_rec;
- LOG_VERBOSE("bd_addr:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::verbose("bd_addr:{}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
p_dev_rec = btm_find_dev(bd_addr);
if (p_dev_rec != NULL) {
@@ -851,7 +854,7 @@
status = true;
*p_div = p_dev_rec->sec_rec.ble_keys.div;
}
- LOG_VERBOSE("status=%d (1-OK) DIV=0x%x", status, *p_div);
+ log::verbose("status={} (1-OK) DIV=0x{:x}", status, *p_div);
return status;
}
@@ -874,8 +877,8 @@
tBTM_SEC_DEV_REC* p_rec;
tBTM_LE_EVT_DATA cb_data;
- LOG_VERBOSE("key_type=0x%x pass_to_application=%d", key_type,
- pass_to_application);
+ log::verbose("key_type=0x{:x} pass_to_application={}", key_type,
+ pass_to_application);
/* Store the updated key in the device database */
if ((p_rec = btm_find_dev(bd_addr)) != NULL &&
@@ -896,8 +899,8 @@
p_rec->sec_rec.sec_flags |= BTM_SEC_LE_LINK_KEY_AUTHED;
else
p_rec->sec_rec.sec_flags &= ~BTM_SEC_LE_LINK_KEY_AUTHED;
- LOG_VERBOSE(
- "BTM_LE_KEY_PENC key_type=0x%x sec_flags=0x%x sec_leve=0x%x",
+ log::verbose(
+ "BTM_LE_KEY_PENC key_type=0x{:x} sec_flags=0x{:x} sec_leve=0x{:x}",
p_rec->sec_rec.ble_keys.key_type, p_rec->sec_rec.sec_flags,
p_rec->sec_rec.ble_keys.sec_level);
break;
@@ -909,9 +912,9 @@
p_rec->ble.identity_address_with_type.type =
p_keys->pid_key.identity_addr_type;
p_rec->sec_rec.ble_keys.key_type |= BTM_LE_KEY_PID;
- LOG_VERBOSE(
- "BTM_LE_KEY_PID key_type=0x%x save peer IRK, change bd_addr=%s "
- "to id_addr=%s id_addr_type=0x%x",
+ log::verbose(
+ "BTM_LE_KEY_PID key_type=0x{:x} save peer IRK, change bd_addr={} "
+ "to id_addr={} id_addr_type=0x{:x}",
p_rec->sec_rec.ble_keys.key_type,
ADDRESS_TO_LOGGABLE_CSTR(p_rec->bd_addr),
ADDRESS_TO_LOGGABLE_CSTR(p_keys->pid_key.identity_addr),
@@ -933,9 +936,9 @@
else
p_rec->sec_rec.sec_flags &= ~BTM_SEC_LE_LINK_KEY_AUTHED;
- LOG_VERBOSE(
- "BTM_LE_KEY_PCSRK key_type=0x%x sec_flags=0x%x sec_level=0x%x "
- "peer_counter=%d",
+ log::verbose(
+ "BTM_LE_KEY_PCSRK key_type=0x{:x} sec_flags=0x{:x} "
+ "sec_level=0x{:x} peer_counter={}",
p_rec->sec_rec.ble_keys.key_type, p_rec->sec_rec.sec_flags,
p_rec->sec_rec.ble_keys.srk_sec_level,
p_rec->sec_rec.ble_keys.counter);
@@ -948,9 +951,9 @@
p_rec->sec_rec.ble_keys.key_size = p_keys->lenc_key.key_size;
p_rec->sec_rec.ble_keys.key_type |= BTM_LE_KEY_LENC;
- LOG_VERBOSE(
- "BTM_LE_KEY_LENC key_type=0x%x DIV=0x%x key_size=0x%x "
- "sec_level=0x%x",
+ log::verbose(
+ "BTM_LE_KEY_LENC key_type=0x{:x} DIV=0x{:x} key_size=0x{:x} "
+ "sec_level=0x{:x}",
p_rec->sec_rec.ble_keys.key_type, p_rec->sec_rec.ble_keys.div,
p_rec->sec_rec.ble_keys.key_size,
p_rec->sec_rec.ble_keys.sec_level);
@@ -963,9 +966,9 @@
p_keys->lcsrk_key.sec_level;
p_rec->sec_rec.ble_keys.local_counter = p_keys->lcsrk_key.counter;
p_rec->sec_rec.ble_keys.key_type |= BTM_LE_KEY_LCSRK;
- LOG_VERBOSE(
- "BTM_LE_KEY_LCSRK key_type=0x%x DIV=0x%x scrk_sec_level=0x%x "
- "local_counter=%d",
+ log::verbose(
+ "BTM_LE_KEY_LCSRK key_type=0x{:x} DIV=0x{:x} scrk_sec_level=0x{:x} "
+ "local_counter={}",
p_rec->sec_rec.ble_keys.key_type, p_rec->sec_rec.ble_keys.div,
p_rec->sec_rec.ble_keys.local_csrk_sec_level,
p_rec->sec_rec.ble_keys.local_counter);
@@ -975,12 +978,12 @@
p_rec->sec_rec.ble_keys.key_type |= BTM_LE_KEY_LID;
break;
default:
- LOG_WARN("btm_sec_save_le_key (Bad key_type 0x%02x)", key_type);
+ log::warn("btm_sec_save_le_key (Bad key_type 0x{:02x})", key_type);
return;
}
- LOG_VERBOSE("BLE key type 0x%x, updated for BDA:%s", key_type,
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::verbose("BLE key type 0x{:x}, updated for BDA:{}", key_type,
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
/* Notify the application that one of the BLE keys has been updated
If link key is in progress, it will get sent later.*/
@@ -993,11 +996,11 @@
return;
}
- LOG_WARN("BLE key type 0x%x, called for Unknown BDA or type:%s", key_type,
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::warn("BLE key type 0x{:x}, called for Unknown BDA or type:{}", key_type,
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
if (p_rec) {
- LOG_VERBOSE("sec_flags=0x%x", p_rec->sec_rec.sec_flags);
+ log::verbose("sec_flags=0x{:x}", p_rec->sec_rec.sec_flags);
}
}
@@ -1014,8 +1017,8 @@
uint8_t enc_key_size) {
tBTM_SEC_DEV_REC* p_rec;
- LOG_VERBOSE("bd_addr:%s, enc_key_size=%d", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
- enc_key_size);
+ log::verbose("bd_addr:{}, enc_key_size={}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ enc_key_size);
p_rec = btm_find_dev(bd_addr);
if (p_rec != NULL) {
@@ -1057,11 +1060,11 @@
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
uint8_t req_sec_level = SMP_SEC_NONE, cur_sec_level = SMP_SEC_NONE;
- LOG_VERBOSE("bd_addr:%s, auth_req=0x%x", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
- auth_req);
+ log::verbose("bd_addr:{}, auth_req=0x{:x}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ auth_req);
if (p_dev_rec == NULL) {
- LOG_ERROR("received for unknown device");
+ log::error("received for unknown device");
return;
}
@@ -1076,7 +1079,7 @@
req_sec_level = SMP_SEC_AUTHENTICATED;
}
- LOG_VERBOSE("dev_rec sec_flags=0x%x", p_dev_rec->sec_rec.sec_flags);
+ log::verbose("dev_rec sec_flags=0x{:x}", p_dev_rec->sec_rec.sec_flags);
/* currently encrpted */
if (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_ENCRYPTED) {
@@ -1103,8 +1106,8 @@
}
}
- LOG_VERBOSE("cur_sec_level=%d req_sec_level=%d sec_req_act=%d", cur_sec_level,
- req_sec_level, *p_sec_req_act);
+ log::verbose("cur_sec_level={} req_sec_level={} sec_req_act={}",
+ cur_sec_level, req_sec_level, *p_sec_req_act);
}
/*******************************************************************************
@@ -1129,11 +1132,11 @@
tBTM_LE_AUTH_REQ auth_req;
if (p_rec == NULL) {
- LOG_WARN("NULL device record!! sec_act=0x%x", sec_act);
+ log::warn("NULL device record!! sec_act=0x{:x}", sec_act);
return (BTM_WRONG_MODE);
}
- LOG_VERBOSE("sec_act=0x%x role_central=%d", sec_act, p_rec->role_central);
+ log::verbose("sec_act=0x{:x} role_central={}", sec_act, p_rec->role_central);
if (sec_act == BTM_BLE_SEC_ENCRYPT_MITM) {
p_rec->sec_rec.security_required |= BTM_SEC_IN_MITM;
@@ -1157,7 +1160,7 @@
btm_ble_link_sec_check(bd_addr, auth_req, &sec_req_act);
if (sec_req_act == BTM_BLE_SEC_REQ_ACT_NONE ||
sec_req_act == BTM_BLE_SEC_REQ_ACT_DISCARD) {
- LOG_VERBOSE("no action needed. Ignore");
+ log::verbose("no action needed. Ignore");
cmd = BTM_SUCCESS;
break;
}
@@ -1196,7 +1199,7 @@
tBTM_SEC_CB* p_cb = &btm_sec_cb;
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
- LOG_VERBOSE("handle:0x%x", handle);
+ log::verbose("handle:0x{:x}", handle);
p_cb->ediv = ediv;
@@ -1218,15 +1221,16 @@
tBTM_SEC_DEV_REC* p_rec = btm_find_dev(bda);
BT_OCTET8 dummy_rand = {0};
- LOG_VERBOSE("bd_addr:%s, use_stk:%d", ADDRESS_TO_LOGGABLE_CSTR(bda), use_stk);
+ log::verbose("bd_addr:{}, use_stk:{}", ADDRESS_TO_LOGGABLE_CSTR(bda),
+ use_stk);
if (!p_rec) {
- LOG_ERROR("Link is not active, can not encrypt!");
+ log::error("Link is not active, can not encrypt!");
return BTM_WRONG_MODE;
}
if (p_rec->sec_rec.is_security_state_encrypting()) {
- LOG_WARN("Link Encryption is active, Busy!");
+ log::warn("Link Encryption is active, Busy!");
return BTM_BUSY;
}
@@ -1239,7 +1243,7 @@
p_rec->ble_hci_handle, p_rec->sec_rec.ble_keys.rand,
p_rec->sec_rec.ble_keys.ediv, p_rec->sec_rec.ble_keys.pltk);
} else {
- LOG_ERROR("No key available to encrypt the link");
+ log::error("No key available to encrypt the link");
return BTM_ERR_KEY_MISSING;
}
@@ -1268,7 +1272,7 @@
if (!BTM_ReadRemoteVersion(bd_addr, &remote_lmp_version, nullptr,
nullptr) ||
remote_lmp_version == 0) {
- LOG_WARN("BLE Unable to determine remote version");
+ log::warn("BLE Unable to determine remote version");
}
if (remote_lmp_version == 0 ||
@@ -1297,11 +1301,11 @@
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
bool enc_cback;
- LOG_VERBOSE("bd_addr:%s, encr_enable=%d", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
- encr_enable);
+ log::verbose("bd_addr:{}, encr_enable={}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ encr_enable);
if (!p_dev_rec) {
- LOG_WARN("No Device Found!");
+ log::warn("No Device Found!");
return;
}
@@ -1309,8 +1313,8 @@
smp_link_encrypted(bd_addr, encr_enable);
- LOG_VERBOSE("p_dev_rec->sec_rec.sec_flags=0x%x",
- p_dev_rec->sec_rec.sec_flags);
+ log::verbose("p_dev_rec->sec_rec.sec_flags=0x{:x}",
+ p_dev_rec->sec_rec.sec_flags);
if (encr_enable && p_dev_rec->sec_rec.enc_key_size == 0)
p_dev_rec->sec_rec.enc_key_size = p_dev_rec->sec_rec.ble_keys.key_size;
@@ -1336,7 +1340,7 @@
(const char*)remote_name) &&
(btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_LE_ACTIVE) &&
btm_sec_cb.pairing_bda == p_dev_rec->ble.pseudo_addr) {
- LOG_INFO(
+ log::info(
"INTEROP_DELAY_ATT_TRAFFIC_DURING_PAIRING: Waiting for bonding to "
"complete to notify enc complete");
} else {
@@ -1360,17 +1364,17 @@
tBTM_SEC_DEV_REC* p_rec = btm_find_dev(bda);
tBTM_SEC_CB* p_cb = &btm_sec_cb;
- LOG_DEBUG("bd_addr:%s,use_stk:%d", ADDRESS_TO_LOGGABLE_CSTR(bda), use_stk);
+ log::debug("bd_addr:{},use_stk:{}", ADDRESS_TO_LOGGABLE_CSTR(bda), use_stk);
if (p_rec == NULL) {
- LOG_ERROR("unknown device");
+ log::error("unknown device");
return;
}
p_cb->enc_handle = p_rec->ble_hci_handle;
p_cb->key_size = p_rec->sec_rec.ble_keys.key_size;
- LOG_ERROR("key size=%d", p_rec->sec_rec.ble_keys.key_size);
+ log::error("key size={}", p_rec->sec_rec.ble_keys.key_size);
if (use_stk) {
btsnd_hcic_ble_ltk_req_reply(btm_sec_cb.enc_handle, stk);
return;
@@ -1388,7 +1392,7 @@
return;
}
- LOG_INFO("Found second sec_dev_rec for device that have LTK");
+ log::info("Found second sec_dev_rec for device that have LTK");
/* This can happen when remote established LE connection using RPA to this
* device, but then pair with us using Classing transport while still keeping
* LE connection. If remote attempts to encrypt the LE connection, we might
@@ -1415,8 +1419,8 @@
static uint8_t btm_ble_io_capabilities_req(tBTM_SEC_DEV_REC* p_dev_rec,
tBTM_LE_IO_REQ* p_data) {
uint8_t callback_rc = BTM_SUCCESS;
- LOG_VERBOSE("p_dev_rec->bd_addr:%s",
- ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr));
+ log::verbose("p_dev_rec->bd_addr:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr));
if (btm_sec_cb.api.p_le_callback) {
/* the callback function implementation may change the IO capability... */
callback_rc = (*btm_sec_cb.api.p_le_callback)(
@@ -1425,27 +1429,27 @@
if ((callback_rc == BTM_SUCCESS) || (BTM_OOB_UNKNOWN != p_data->oob_data)) {
p_data->auth_req &= BTM_LE_AUTH_REQ_MASK;
- LOG_VERBOSE("1:p_dev_rec->sec_rec.security_required=%d, auth_req:%d",
- p_dev_rec->sec_rec.security_required, p_data->auth_req);
- LOG_VERBOSE("2:i_keys=0x%x r_keys=0x%x (bit 0-LTK 1-IRK 2-CSRK)",
- p_data->init_keys, p_data->resp_keys);
+ log::verbose("1:p_dev_rec->sec_rec.security_required={}, auth_req:{}",
+ p_dev_rec->sec_rec.security_required, p_data->auth_req);
+ log::verbose("2:i_keys=0x{:x} r_keys=0x{:x} (bit 0-LTK 1-IRK 2-CSRK)",
+ p_data->init_keys, p_data->resp_keys);
/* if authentication requires MITM protection, put on the mask */
if (p_dev_rec->sec_rec.security_required & BTM_SEC_IN_MITM)
p_data->auth_req |= BTM_LE_AUTH_REQ_MITM;
if (!(p_data->auth_req & SMP_AUTH_BOND)) {
- LOG_VERBOSE("Non bonding: No keys should be exchanged");
+ log::verbose("Non bonding: No keys should be exchanged");
p_data->init_keys = 0;
p_data->resp_keys = 0;
}
- LOG_VERBOSE("3:auth_req:%d", p_data->auth_req);
- LOG_VERBOSE("4:i_keys=0x%x r_keys=0x%x", p_data->init_keys,
- p_data->resp_keys);
+ log::verbose("3:auth_req:{}", p_data->auth_req);
+ log::verbose("4:i_keys=0x{:x} r_keys=0x{:x}", p_data->init_keys,
+ p_data->resp_keys);
- LOG_VERBOSE("5:p_data->io_cap=%d auth_req:%d", p_data->io_cap,
- p_data->auth_req);
+ log::verbose("5:p_data->io_cap={} auth_req:{}", p_data->io_cap,
+ p_data->auth_req);
/* remove MITM protection requirement if IO cap does not allow it */
if ((p_data->io_cap == BTM_IO_CAP_NONE) && p_data->oob_data == SMP_OOB_NONE)
@@ -1455,15 +1459,15 @@
/* if Secure Connections are not supported then remove LK derivation,
** and keypress notifications.
*/
- LOG_VERBOSE(
+ log::verbose(
"SC not supported -> No LK derivation, no keypress notifications");
p_data->auth_req &= ~SMP_KP_SUPPORT_BIT;
p_data->init_keys &= ~SMP_SEC_KEY_TYPE_LK;
p_data->resp_keys &= ~SMP_SEC_KEY_TYPE_LK;
}
- LOG_VERBOSE("6:IO_CAP:%d oob_data:%d auth_req:0x%02x", p_data->io_cap,
- p_data->oob_data, p_data->auth_req);
+ log::verbose("6:IO_CAP:{} oob_data:{} auth_req:0x{:02x}", p_data->io_cap,
+ p_data->oob_data, p_data->auth_req);
}
return callback_rc;
}
@@ -1481,8 +1485,8 @@
static uint8_t btm_ble_br_keys_req(tBTM_SEC_DEV_REC* p_dev_rec,
tBTM_LE_IO_REQ* p_data) {
uint8_t callback_rc = BTM_SUCCESS;
- LOG_VERBOSE("p_dev_rec->bd_addr:%s",
- ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr));
+ log::verbose("p_dev_rec->bd_addr:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr));
*p_data = tBTM_LE_IO_REQ{
.io_cap = BTM_IO_CAP_UNKNOWN,
.oob_data = false,
@@ -1516,15 +1520,15 @@
bool can_read_discoverable_characteristics) {
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_or_alloc_dev(bda);
- LOG_INFO("Update timestamp for ble connection:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bda));
+ log::info("Update timestamp for ble connection:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bda));
// TODO() Why is timestamp a counter ?
p_dev_rec->timestamp = btm_sec_cb.dev_rec_count++;
if (is_ble_addr_type_known(addr_type))
p_dev_rec->ble.SetAddressType(addr_type);
else
- LOG_WARN(
+ log::warn(
"Please do not update device record from anonymous le advertisement");
p_dev_rec->ble.pseudo_addr = bda;
@@ -1550,8 +1554,8 @@
*****************************************************************************/
tBTM_STATUS btm_proc_smp_cback(tSMP_EVT event, const RawAddress& bd_addr,
const tSMP_EVT_DATA* p_data) {
- LOG_VERBOSE("bd_addr:%s, event=%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
- smp_evt_to_text(event).c_str());
+ log::verbose("bd_addr:{}, event={}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ smp_evt_to_text(event).c_str());
if (event == SMP_SC_LOC_OOB_DATA_UP_EVT) {
btm_sec_cr_loc_oob_data_cback_event(RawAddress{}, p_data->loc_oob_data);
@@ -1584,7 +1588,7 @@
case SMP_SEC_REQUEST_EVT:
if (event == SMP_SEC_REQUEST_EVT &&
btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) {
- LOG_VERBOSE("Ignoring SMP Security request");
+ log::verbose("Ignoring SMP Security request");
break;
}
btm_sec_cb.pairing_bda = bd_addr;
@@ -1598,8 +1602,8 @@
if (btm_sec_cb.api.p_le_callback) {
/* the callback function implementation may change the IO
* capability... */
- LOG_VERBOSE("btm_sec_cb.api.p_le_callback=0x%p",
- btm_sec_cb.api.p_le_callback);
+ log::verbose("btm_sec_cb.api.p_le_callback=0x{}",
+ fmt::ptr(btm_sec_cb.api.p_le_callback));
(*btm_sec_cb.api.p_le_callback)(static_cast<tBTM_LE_EVT>(event),
bd_addr, (tBTM_LE_EVT_DATA*)p_data);
}
@@ -1607,32 +1611,33 @@
if (event == SMP_COMPLT_EVT) {
p_dev_rec = btm_find_dev(bd_addr);
if (p_dev_rec == NULL) {
- LOG_ERROR("p_dev_rec is NULL");
+ log::error("p_dev_rec is NULL");
return BTM_SUCCESS;
}
- LOG_VERBOSE("before update sec_level=0x%x sec_flags=0x%x",
- p_data->cmplt.sec_level, p_dev_rec->sec_rec.sec_flags);
+ log::verbose("before update sec_level=0x{:x} sec_flags=0x{:x}",
+ p_data->cmplt.sec_level, p_dev_rec->sec_rec.sec_flags);
res = (p_data->cmplt.reason == SMP_SUCCESS) ? BTM_SUCCESS
: BTM_ERR_PROCESSING;
- LOG_VERBOSE("after update result=%d sec_level=0x%x sec_flags=0x%x",
- res, p_data->cmplt.sec_level,
- p_dev_rec->sec_rec.sec_flags);
+ log::verbose(
+ "after update result={} sec_level=0x{:x} sec_flags=0x{:x}", res,
+ p_data->cmplt.sec_level, p_dev_rec->sec_rec.sec_flags);
if (p_data->cmplt.is_pair_cancel &&
btm_sec_cb.api.p_bond_cancel_cmpl_callback) {
- LOG_VERBOSE("Pairing Cancel completed");
+ log::verbose("Pairing Cancel completed");
(*btm_sec_cb.api.p_bond_cancel_cmpl_callback)(BTM_SUCCESS);
}
if (res != BTM_SUCCESS && p_data->cmplt.reason != SMP_CONN_TOUT) {
- LOG_VERBOSE("Pairing failed - prepare to remove ACL");
+ log::verbose("Pairing failed - prepare to remove ACL");
l2cu_start_post_bond_timer(p_dev_rec->ble_hci_handle);
}
- LOG_VERBOSE(
- "btm_sec_cb.pairing_state=%x pairing_flags=%x pin_code_len=%x",
+ log::verbose(
+ "btm_sec_cb.pairing_state={:x} pairing_flags={:x} "
+ "pin_code_len={:x}",
btm_sec_cb.pairing_state, btm_sec_cb.pairing_flags,
btm_sec_cb.pin_code_len);
@@ -1654,9 +1659,9 @@
// At this point LTK should have been dropped by btif.
// Reset the flags here if LE is not connected (over BR),
// otherwise they would be reset on disconnected.
- LOG_DEBUG(
- "SMP over BR triggered by temporary bond has completed,"
- " resetting the LK flags");
+ log::debug(
+ "SMP over BR triggered by temporary bond has completed, "
+ "resetting the LK flags");
p_dev_rec->sec_rec.sec_flags &= ~(BTM_SEC_LE_LINK_KEY_KNOWN);
p_dev_rec->sec_rec.ble_keys.key_type = BTM_LE_KEY_NONE;
}
@@ -1666,7 +1671,7 @@
remote_name) &&
interop_match_name(INTEROP_SUSPEND_ATT_TRAFFIC_DURING_PAIRING,
(const char*)remote_name)) {
- LOG_DEBUG("Notifying encryption cmpl delayed due to IOP match");
+ log::debug("Notifying encryption cmpl delayed due to IOP match");
btm_ble_notify_enc_cmpl(p_dev_rec->ble.pseudo_addr, true);
}
@@ -1676,8 +1681,8 @@
case SMP_LE_ADDR_ASSOC_EVT:
if (btm_sec_cb.api.p_le_callback) {
- LOG_VERBOSE("btm_sec_cb.api.p_le_callback=0x%p",
- btm_sec_cb.api.p_le_callback);
+ log::verbose("btm_sec_cb.api.p_le_callback=0x{}",
+ fmt::ptr(btm_sec_cb.api.p_le_callback));
(*btm_sec_cb.api.p_le_callback)(static_cast<tBTM_LE_EVT>(event),
bd_addr, (tBTM_LE_EVT_DATA*)p_data);
}
@@ -1685,8 +1690,8 @@
case SMP_SIRK_VERIFICATION_REQ_EVT:
res = (*btm_sec_cb.api.p_sirk_verification_callback)(bd_addr);
- LOG_DEBUG("SMP SIRK verification result:%s",
- btm_status_text(res).c_str());
+ log::debug("SMP SIRK verification result:{}",
+ btm_status_text(res).c_str());
if (res != BTM_CMD_STARTED) {
return res;
}
@@ -1694,12 +1699,12 @@
break;
default:
- LOG_VERBOSE("unknown event=%s", smp_evt_to_text(event).c_str());
+ log::verbose("unknown event={}", smp_evt_to_text(event).c_str());
break;
}
} else {
- LOG_WARN("Unexpected event '%s' for unknown device.",
- smp_evt_to_text(event).c_str());
+ log::warn("Unexpected event '{}' for unknown device.",
+ smp_evt_to_text(event).c_str());
}
return BTM_SUCCESS;
@@ -1726,7 +1731,7 @@
tBTM_SEC_DEV_REC* p_rec = btm_find_dev(bd_addr);
if (p_rec == NULL) {
- LOG_ERROR("data signing can not be done from unknown device");
+ log::error("data signing can not be done from unknown device");
return false;
}
@@ -1748,14 +1753,12 @@
(uint16_t)(len + 4), BTM_CMAC_TLEN_SIZE, p_mac);
p_rec->sec_rec.increment_sign_counter(true);
- LOG_VERBOSE("p_mac = %p", p_mac);
- LOG_VERBOSE(
- "p_mac[0]=0x%02x p_mac[1]=0x%02x p_mac[2]=0x%02x p_mac[3]="
- "0x%02x",
+ log::verbose("p_mac = {}", fmt::ptr(p_mac));
+ log::verbose(
+ "p_mac[0]=0x{:02x} p_mac[1]=0x{:02x} p_mac[2]=0x{:02x} p_mac[3]=0x{:02x}",
*p_mac, *(p_mac + 1), *(p_mac + 2), *(p_mac + 3));
- LOG_VERBOSE(
- "p_mac[4]=0x%02x p_mac[5]=0x%02x p_mac[6]=0x%02x p_mac[7]="
- "0x%02x",
+ log::verbose(
+ "p_mac[4]=0x{:02x} p_mac[5]=0x{:02x} p_mac[6]=0x{:02x} p_mac[7]=0x{:02x}",
*(p_mac + 4), *(p_mac + 5), *(p_mac + 6), *(p_mac + 7));
osi_free(p_buf);
return true;
@@ -1784,14 +1787,14 @@
if (p_rec == NULL ||
(p_rec && !(p_rec->sec_rec.ble_keys.key_type & BTM_LE_KEY_PCSRK))) {
- LOG_ERROR("can not verify signature for unknown device");
+ log::error("can not verify signature for unknown device");
} else if (counter < p_rec->sec_rec.ble_keys.counter) {
- LOG_ERROR("signature received with out dated sign counter");
+ log::error("signature received with out dated sign counter");
} else if (p_orig == NULL) {
- LOG_ERROR("No signature to verify");
+ log::error("No signature to verify");
} else {
- LOG_VERBOSE("rcv_cnt=%d >= expected_cnt=%d", counter,
- p_rec->sec_rec.ble_keys.counter);
+ log::verbose("rcv_cnt={} >= expected_cnt={}", counter,
+ p_rec->sec_rec.ble_keys.counter);
crypto_toolbox::aes_cmac(p_rec->sec_rec.ble_keys.pcsrk, p_orig, len,
BTM_CMAC_TLEN_SIZE, p_mac);
@@ -1819,11 +1822,11 @@
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
tSMP_STATUS res_smp = (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_FAIL;
- LOG_INFO("bd_addr:%s, result:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
- smp_status_text(res_smp).c_str());
+ log::info("bd_addr:{}, result:{}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ smp_status_text(res_smp).c_str());
if (p_dev_rec == NULL) {
- LOG_ERROR("Confirmation of Unknown device");
+ log::error("Confirmation of Unknown device");
return;
}
@@ -1840,23 +1843,23 @@
static void btm_notify_new_key(uint8_t key_type) {
tBTM_BLE_LOCAL_KEYS* p_local_keys = NULL;
- LOG_VERBOSE("key_type=%d", key_type);
+ log::verbose("key_type={}", key_type);
if (btm_sec_cb.api.p_le_key_callback) {
switch (key_type) {
case BTM_BLE_KEY_TYPE_ID:
- LOG_VERBOSE("BTM_BLE_KEY_TYPE_ID");
+ log::verbose("BTM_BLE_KEY_TYPE_ID");
p_local_keys = (tBTM_BLE_LOCAL_KEYS*)&btm_sec_cb.devcb.id_keys;
break;
case BTM_BLE_KEY_TYPE_ER:
- LOG_VERBOSE("BTM_BLE_KEY_TYPE_ER");
+ log::verbose("BTM_BLE_KEY_TYPE_ER");
p_local_keys =
(tBTM_BLE_LOCAL_KEYS*)&btm_sec_cb.devcb.ble_encryption_key_value;
break;
default:
- LOG_ERROR("unknown key type: %d", key_type);
+ log::error("unknown key type: {}", key_type);
break;
}
if (p_local_keys != NULL)
@@ -1905,7 +1908,7 @@
/** This function is called to reset LE device identity. */
void btm_ble_reset_id(void) {
- LOG_VERBOSE("btm_ble_reset_id");
+ log::verbose("btm_ble_reset_id");
/* In order to reset identity, we need four random numbers. Make four nested
* calls to generate them first, then proceed to perform the actual reset in
@@ -1947,8 +1950,8 @@
tBLE_ADDR_TYPE* p_addr_type) {
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(hci_handle);
if (p_dev_rec == nullptr) {
- LOG_WARN("Unable to find security device record hci_handle:%hu",
- hci_handle);
+ log::warn("Unable to find security device record hci_handle:{}",
+ hci_handle);
// TODO Release acl resource
return false;
}
@@ -1972,8 +1975,8 @@
break;
default:
- LOG_WARN("Unable to find record with active address type:%d",
- p_dev_rec->ble.active_addr_type);
+ log::warn("Unable to find record with active address type:{}",
+ p_dev_rec->ble.active_addr_type);
st = false;
break;
}
diff --git a/system/stack/btm/btm_ble_sec.h b/system/stack/btm/btm_ble_sec.h
index 98edf6a..fde20ea 100644
--- a/system/stack/btm/btm_ble_sec.h
+++ b/system/stack/btm/btm_ble_sec.h
@@ -16,6 +16,8 @@
#pragma once
+#include <bluetooth/log.h>
+
#include <string>
#include "macros.h"
@@ -33,7 +35,8 @@
BTM_BLE_SEC_REQ_ACT_DISCARD = 3,
} tBTM_BLE_SEC_REQ_ACT;
-inline std::string btm_ble_sec_req_act_text(const tBTM_BLE_SEC_REQ_ACT action) {
+inline std::string btm_ble_sec_req_act_text(
+ const tBTM_BLE_SEC_REQ_ACT& action) {
switch (action) {
CASE_RETURN_TEXT(BTM_BLE_SEC_REQ_ACT_NONE);
CASE_RETURN_TEXT(BTM_BLE_SEC_REQ_ACT_ENCRYPT);
@@ -72,3 +75,9 @@
bool is_originator,
tBTM_SEC_CALLBACK* p_callback,
void* p_ref_data);
+
+namespace fmt {
+template <>
+struct formatter<tBTM_BLE_SEC_REQ_ACT>
+ : string_formatter<tBTM_BLE_SEC_REQ_ACT, &btm_ble_sec_req_act_text> {};
+} // namespace fmt
diff --git a/system/stack/btm/btm_client_interface.cc b/system/stack/btm/btm_client_interface.cc
index 5af0adc..b52cf08 100644
--- a/system/stack/btm/btm_client_interface.cc
+++ b/system/stack/btm/btm_client_interface.cc
@@ -13,9 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
#include "stack/include/btm_client_interface.h"
+#include <bluetooth/log.h>
+
#include "security_client_callbacks.h"
#include "stack/btm/btm_ble_int.h"
#include "stack/include/acl_api.h"
diff --git a/system/stack/btm/btm_dev.cc b/system/stack/btm/btm_dev.cc
index 33764d4..c45bda6 100644
--- a/system/stack/btm/btm_dev.cc
+++ b/system/stack/btm/btm_dev.cc
@@ -27,6 +27,7 @@
#include "stack/btm/btm_dev.h"
#include <android_bluetooth_flags.h>
+#include <bluetooth/log.h>
#include <string>
@@ -49,6 +50,8 @@
#include "stack/include/btm_log_history.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
extern tBTM_CB btm_cb;
void gatt_consolidate(const RawAddress& identity_addr, const RawAddress& rpa);
@@ -89,10 +92,11 @@
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
if (!p_dev_rec) {
p_dev_rec = btm_sec_allocate_dev_rec();
- LOG_DEBUG(
- "Caching new record from config file device:%s link_key_type:%x "
- "name:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), key_type, bd_name);
+ log::debug(
+ "Caching new record from config file device:{} link_key_type:{:x} "
+ "name:{}",
+ ADDRESS_TO_LOGGABLE_STR(bd_addr), key_type,
+ reinterpret_cast<const char*>(bd_name));
p_dev_rec->bd_addr = bd_addr;
p_dev_rec->hci_handle = BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_BR_EDR);
@@ -101,9 +105,9 @@
/* update conn params, use default value for background connection params */
memset(&p_dev_rec->conn_params, 0xff, sizeof(tBTM_LE_CONN_PRAMS));
} else {
- LOG_DEBUG(
- "Caching existing record from config file device:%s link_key_type:%x",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), key_type);
+ log::debug(
+ "Caching existing record from config file device:{} link_key_type:{:x}",
+ ADDRESS_TO_LOGGABLE_STR(bd_addr), key_type);
/* "Bump" timestamp for existing record */
p_dev_rec->timestamp = btm_sec_cb.dev_rec_count++;
@@ -122,15 +126,17 @@
memset(p_dev_rec->sec_bd_name, 0, sizeof(tBTM_BD_NAME));
if (bd_name && bd_name[0]) {
- LOG_DEBUG(" Remote name known for device:%s name:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), bd_name);
+ log::debug(" Remote name known for device:{} name:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ reinterpret_cast<const char*>(bd_name));
p_dev_rec->sec_rec.sec_flags |= BTM_SEC_NAME_KNOWN;
strlcpy((char*)p_dev_rec->sec_bd_name, (char*)bd_name,
BTM_MAX_REM_BD_NAME_LEN + 1);
}
if (p_link_key) {
- LOG_DEBUG(" Link key known for device:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::debug(" Link key known for device:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
p_dev_rec->sec_rec.sec_flags |= BTM_SEC_LINK_KEY_KNOWN;
p_dev_rec->sec_rec.link_key = *p_link_key;
p_dev_rec->sec_rec.link_key_type = key_type;
@@ -171,8 +177,8 @@
bool BTM_SecDeleteDevice(const RawAddress& bd_addr) {
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
if (p_dev_rec == NULL) {
- LOG_WARN("Unable to delete link key for unknown device %s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::warn("Unable to delete link key for unknown device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return true;
}
@@ -182,15 +188,15 @@
if (BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE) ||
BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_BR_EDR)) {
- LOG_WARN("FAILED: Cannot Delete when connection to %s is active",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::warn("FAILED: Cannot Delete when connection to {} is active",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return false;
}
RawAddress bda = p_dev_rec->bd_addr;
- LOG_INFO("Remove device %s from filter accept list before delete record",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::info("Remove device {} from filter accept list before delete record",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
if (bluetooth::common::init_flags::
use_unified_connection_manager_is_enabled()) {
bluetooth::connection::GetConnectionManager()
@@ -208,7 +214,7 @@
wipe_secrets_and_remove(p_dev_rec);
/* Tell controller to get rid of the link key, if it has one stored */
BTM_DeleteStoredLinkKey(&bda, NULL);
- LOG_INFO("%s complete", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::info("{} complete", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
BTM_LogHistory(kBtmLogTag, bd_addr, "Device removed",
base::StringPrintf("device_type:%s bond_type:%s",
DeviceTypeText(device_type).c_str(),
@@ -270,7 +276,8 @@
tBTM_SEC_DEV_REC* p_dev_rec = btm_sec_allocate_dev_rec();
- LOG_DEBUG("Allocated device record bd_addr:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::debug("Allocated device record bd_addr:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
/* Check with the BT manager if details about remote device are known */
/* outgoing connection */
@@ -282,7 +289,7 @@
if (is_ble_addr_type_known(p_inq_info->results.ble_addr_type))
p_dev_rec->ble.SetAddressType(p_inq_info->results.ble_addr_type);
else
- LOG_WARN(
+ log::warn(
"Please do not update device record from anonymous le advertisement");
} else if (bd_addr == btm_sec_cb.connecting_bda)
@@ -314,34 +321,33 @@
******************************************************************************/
bool btm_dev_support_role_switch(const RawAddress& bd_addr) {
if (BTM_IsScoActiveByBdaddr(bd_addr)) {
- LOG_VERBOSE("%s Role switch is not allowed if a SCO is up", __func__);
+ log::verbose("Role switch is not allowed if a SCO is up");
return false;
}
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
if (p_dev_rec == nullptr) {
- LOG_VERBOSE("%s Unknown address for role switch", __func__);
+ log::verbose("Unknown address for role switch");
return false;
}
if (!controller_get_interface()->SupportsRoleSwitch()) {
- LOG_VERBOSE("%s Local controller does not support role switch", __func__);
+ log::verbose("Local controller does not support role switch");
return false;
}
if (p_dev_rec->remote_supports_hci_role_switch) {
- LOG_VERBOSE("%s Peer controller supports role switch", __func__);
+ log::verbose("Peer controller supports role switch");
return true;
}
if (!p_dev_rec->remote_feature_received) {
- LOG_VERBOSE(
- "%s Unknown peer capabilities, assuming peer supports role switch",
- __func__);
+ log::verbose(
+ "Unknown peer capabilities, assuming peer supports role switch");
return true;
}
- LOG_VERBOSE("%s Peer controller does not support role switch", __func__);
+ log::verbose("Peer controller does not support role switch");
return false;
}
@@ -366,6 +372,8 @@
*
******************************************************************************/
tBTM_SEC_DEV_REC* btm_find_dev_by_handle(uint16_t handle) {
+ if (btm_sec_cb.sec_dev_rec == nullptr) return nullptr;
+
list_node_t* n =
list_foreach(btm_sec_cb.sec_dev_rec, is_handle_equal, &handle);
if (n) return static_cast<tBTM_SEC_DEV_REC*>(list_node(n));
@@ -443,7 +451,7 @@
void btm_consolidate_dev(tBTM_SEC_DEV_REC* p_target_rec) {
tBTM_SEC_DEV_REC temp_rec = *p_target_rec;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
list_node_t* end = list_end(btm_sec_cb.sec_dev_rec);
list_node_t* node = list_begin(btm_sec_cb.sec_dev_rec);
@@ -500,16 +508,16 @@
void btm_dev_consolidate_existing_connections(const RawAddress& bd_addr) {
tBTM_SEC_DEV_REC* p_target_rec = btm_find_dev(bd_addr);
if (!p_target_rec) {
- LOG_ERROR("No security record for just bonded device!?!?");
+ log::error("No security record for just bonded device!?!?");
return;
}
if (p_target_rec->ble_hci_handle != HCI_INVALID_HANDLE) {
- LOG_INFO("Not consolidating - already have LE connection");
+ log::info("Not consolidating - already have LE connection");
return;
}
- LOG_INFO("%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::info("{}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
list_node_t* end = list_end(btm_sec_cb.sec_dev_rec);
list_node_t* node = list_begin(btm_sec_cb.sec_dev_rec);
@@ -525,15 +533,17 @@
/* an RPA device entry is a duplicate of the target record */
if (btm_ble_addr_resolvable(p_dev_rec->bd_addr, p_target_rec)) {
if (p_dev_rec->ble_hci_handle == HCI_INVALID_HANDLE) {
- LOG_INFO("already disconnected - erasing entry %s",
- ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr));
+ log::info("already disconnected - erasing entry {}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr));
wipe_secrets_and_remove(p_dev_rec);
continue;
}
- LOG_INFO(
- "Found existing LE connection to just bonded device on %s handle 0x%04x",
- ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr), p_dev_rec->ble_hci_handle);
+ log::info(
+ "Found existing LE connection to just bonded device on {} handle "
+ "0x{:04x}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr),
+ p_dev_rec->ble_hci_handle);
RawAddress ble_conn_addr = p_dev_rec->bd_addr;
p_target_rec->ble_hci_handle = p_dev_rec->ble_hci_handle;
@@ -549,7 +559,7 @@
/* To avoid race conditions between central/peripheral starting encryption
* at same time, initiate it just from central. */
if (L2CA_GetBleConnRole(ble_conn_addr) == HCI_ROLE_CENTRAL) {
- LOG_INFO("Will encrypt existing connection");
+ log::info("Will encrypt existing connection");
BTM_SetEncryption(bd_addr, BT_TRANSPORT_LE, nullptr, nullptr,
BTM_BLE_SEC_ENCRYPT);
}
@@ -570,7 +580,7 @@
******************************************************************************/
tBTM_SEC_DEV_REC* btm_find_or_alloc_dev(const RawAddress& bd_addr) {
tBTM_SEC_DEV_REC* p_dev_rec;
- LOG_VERBOSE("btm_find_or_alloc_dev");
+ log::verbose("btm_find_or_alloc_dev");
p_dev_rec = btm_find_dev(bd_addr);
if (p_dev_rec == NULL) {
/* Allocate a new device record or reuse the oldest one */
@@ -640,7 +650,7 @@
tBTM_SEC_DEV_REC* p_dev_rec = NULL;
if (btm_sec_cb.sec_dev_rec == nullptr) {
- LOG_WARN(
+ log::warn(
"Unable to allocate device record with destructed device record list");
return nullptr;
}
@@ -747,8 +757,8 @@
if (p_dev_rec == NULL || (p_dev_rec->device_type & BT_DEVICE_TYPE_BLE) == 0)
return true;
- LOG_WARN("%s, device type not BLE: 0x%02x", ADDRESS_TO_LOGGABLE_CSTR(address),
- p_dev_rec->device_type);
+ log::warn("{}, device type not BLE: 0x{:02x}",
+ ADDRESS_TO_LOGGABLE_CSTR(address), p_dev_rec->device_type);
// bonded device with identity address known
if (!p_dev_rec->ble.identity_address_with_type.bda.IsEmpty()) {
@@ -761,8 +771,8 @@
return true;
}
- LOG_WARN("%s, the address type is 0x%02x", ADDRESS_TO_LOGGABLE_CSTR(address),
- p_dev_rec->ble.AddressType());
+ log::warn("{}, the address type is 0x{:02x}",
+ ADDRESS_TO_LOGGABLE_CSTR(address), p_dev_rec->ble.AddressType());
// Only Resolvable Private Address (RPA) is known, we don't allow it into
// the background connection procedure.
diff --git a/system/stack/btm/btm_devctl.cc b/system/stack/btm/btm_devctl.cc
index 3564d24..cb6a2b6 100644
--- a/system/stack/btm/btm_devctl.cc
+++ b/system/stack/btm/btm_devctl.cc
@@ -25,6 +25,7 @@
#define LOG_TAG "devctl"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
@@ -47,9 +48,12 @@
#include "stack/include/bt_types.h"
#include "stack/include/btm_api.h"
#include "stack/include/btm_ble_privacy.h"
+#include "stack/include/hcidefs.h"
#include "stack/include/l2cap_controller_interface.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
extern tBTM_CB btm_cb;
void btm_inq_db_reset(void);
@@ -206,7 +210,7 @@
btsnd_hcic_ble_set_rand_priv_addr_timeout(
btm_get_next_private_addrress_interval_ms() / 1000);
} else {
- LOG_INFO(
+ log::info(
"Le Address Resolving list disabled due to lack of controller support");
}
@@ -290,8 +294,8 @@
}
}
- LOG_VERBOSE("Local supported SCO packet types: 0x%04x",
- btm_cb.btm_sco_pkt_types_supported);
+ log::verbose("Local supported SCO packet types: 0x{:04x}",
+ btm_cb.btm_sco_pkt_types_supported);
BTM_acl_after_controller_started(controller_get_interface());
btm_sec_dev_reset();
@@ -451,8 +455,7 @@
******************************************************************************/
void BTM_VendorSpecificCommand(uint16_t opcode, uint8_t param_len,
uint8_t* p_param_buf, tBTM_VSC_CMPL_CB* p_cb) {
- LOG_VERBOSE("BTM: %s: Opcode: 0x%04X, ParamLen: %i.", __func__, opcode,
- param_len);
+ log::verbose("BTM: Opcode: 0x{:04X}, ParamLen: {}.", opcode, param_len);
/* Send the HCI command (opcode will be OR'd with HCI_GRP_VENDOR_SPECIFIC) */
btsnd_hcic_vendor_spec_cmd(opcode, param_len, p_param_buf, p_cb);
@@ -486,7 +489,7 @@
/* Found callback in lookup table. If deregistering, clear the entry. */
if (!is_register) {
btm_cb.devcb.p_vend_spec_cb[i] = NULL;
- LOG_VERBOSE("BTM Deregister For VSEvents is successfully");
+ log::verbose("BTM Deregister For VSEvents is successfully");
}
return (BTM_SUCCESS);
}
@@ -496,10 +499,10 @@
if (is_register) {
if (free_idx < BTM_MAX_VSE_CALLBACKS) {
btm_cb.devcb.p_vend_spec_cb[free_idx] = p_cb;
- LOG_VERBOSE("BTM Register For VSEvents is successfully");
+ log::verbose("BTM Register For VSEvents is successfully");
} else {
/* No free entries available */
- LOG_ERROR("BTM_RegisterForVSEvents: too many callbacks registered");
+ log::error("BTM_RegisterForVSEvents: too many callbacks registered");
retval = BTM_NO_RESOURCES;
}
@@ -512,39 +515,25 @@
*
* Function btm_vendor_specific_evt
*
- * Description Process event HCI_VENDOR_SPECIFIC_EVT
+ * Description Process event HCI_VENDOR_SPECIFIC_EVT (BQR)
*
* Returns void
*
******************************************************************************/
void btm_vendor_specific_evt(const uint8_t* p, uint8_t evt_len) {
- uint8_t i;
+ uint8_t sub_event_code = HCI_VSE_SUBCODE_BQR_SUB_EVT;
+ uint8_t bqr_parameter_length = evt_len;
+ const uint8_t* p_bqr_event = p;
- LOG_VERBOSE("BTM Event: Vendor Specific event from controller");
+ log::verbose("BTM Event: Vendor Specific event from controller");
- // Handle BQR events
- const uint8_t* bqr_ptr = p;
- uint8_t event_code;
- uint8_t len;
-
- if (evt_len >= 2) {
- STREAM_TO_UINT8(event_code, bqr_ptr);
- STREAM_TO_UINT8(len, bqr_ptr);
- // Check if there's at least a subevent code
- if (len > 1 && evt_len >= 2 + 1 && event_code == HCI_VENDOR_SPECIFIC_EVT) {
- uint8_t sub_event_code;
- STREAM_TO_UINT8(sub_event_code, bqr_ptr);
- if (sub_event_code == HCI_VSE_SUBCODE_BQR_SUB_EVT) {
- // Excluding the HCI Event packet header and 1 octet sub-event code
- int16_t bqr_parameter_length = evt_len - HCIE_PREAMBLE_SIZE - 1;
- const uint8_t* p_bqr_event = bqr_ptr;
// The stream currently points to the BQR sub-event parameters
switch (sub_event_code) {
case bluetooth::bqr::QUALITY_REPORT_ID_LMP_LL_MESSAGE_TRACE:
if (bqr_parameter_length >= bluetooth::bqr::kLogDumpParamTotalLen) {
bluetooth::bqr::DumpLmpLlMessage(bqr_parameter_length, p_bqr_event);
} else {
- LOG_INFO("Malformed LMP event of length %hd", bqr_parameter_length);
+ log::info("Malformed LMP event of length {}", bqr_parameter_length);
}
break;
@@ -553,21 +542,29 @@
if (bqr_parameter_length >= bluetooth::bqr::kLogDumpParamTotalLen) {
bluetooth::bqr::DumpBtScheduling(bqr_parameter_length, p_bqr_event);
} else {
- LOG_INFO("Malformed TRACE event of length %hd",
- bqr_parameter_length);
+ log::info("Malformed TRACE event of length {}",
+ bqr_parameter_length);
}
break;
default:
- LOG_INFO("Unhandled BQR subevent 0x%02hxx", sub_event_code);
+ log::info("Unhandled BQR subevent 0x{:02x}x", sub_event_code);
}
- }
- }
- }
+
+ uint8_t i;
+ std::vector<uint8_t> reconstructed_event;
+ reconstructed_event.reserve(4 + bqr_parameter_length);
+ reconstructed_event[0] = HCI_VENDOR_SPECIFIC_EVT;
+ reconstructed_event[1] = 3 + bqr_parameter_length; // event size
+ reconstructed_event[2] = HCI_VSE_SUBCODE_BQR_SUB_EVT;
+ for (i = 0; i < bqr_parameter_length; i++) {
+ reconstructed_event.emplace_back(p[i]);
+ }
for (i = 0; i < BTM_MAX_VSE_CALLBACKS; i++) {
if (btm_cb.devcb.p_vend_spec_cb[i])
- (*btm_cb.devcb.p_vend_spec_cb[i])(evt_len, p);
+ (*btm_cb.devcb.p_vend_spec_cb[i])(reconstructed_event.size(),
+ reconstructed_event.data());
}
}
@@ -579,7 +576,7 @@
*
******************************************************************************/
void BTM_WritePageTimeout(uint16_t timeout) {
- LOG_VERBOSE("BTM: BTM_WritePageTimeout: Timeout: %d.", timeout);
+ log::verbose("BTM: BTM_WritePageTimeout: Timeout: {}.", timeout);
/* Send the HCI command */
btsnd_hcic_write_page_tout(timeout);
@@ -594,7 +591,7 @@
*
******************************************************************************/
void BTM_WriteVoiceSettings(uint16_t settings) {
- LOG_VERBOSE("BTM: BTM_WriteVoiceSettings: Settings: 0x%04x.", settings);
+ log::verbose("BTM: BTM_WriteVoiceSettings: Settings: 0x{:04x}.", settings);
/* Send the HCI command */
btsnd_hcic_write_voice_settings((uint16_t)(settings & 0x03ff));
@@ -618,7 +615,7 @@
tBTM_STATUS BTM_EnableTestMode(void) {
uint8_t cond;
- LOG_VERBOSE("BTM: BTM_EnableTestMode");
+ log::verbose("BTM: BTM_EnableTestMode");
/* set auto accept connection as this is needed during test mode */
/* Allocate a buffer to hold HCI command */
@@ -669,8 +666,8 @@
bool delete_all_flag = !bd_addr;
- LOG_VERBOSE("BTM: BTM_DeleteStoredLinkKey: delete_all_flag: %s",
- delete_all_flag ? "true" : "false");
+ log::verbose("BTM: BTM_DeleteStoredLinkKey: delete_all_flag: {}",
+ delete_all_flag ? "true" : "false");
btm_sec_cb.devcb.p_stored_link_key_cmpl_cb = p_cb;
if (!bd_addr) {
@@ -709,7 +706,7 @@
result.event = BTM_CB_EVT_DELETE_STORED_LINK_KEYS;
if (evt_len < 3) {
- LOG(ERROR) << __func__ << "Malformatted event packet, too short";
+ log::error("Malformatted event packet, too short");
return;
}
@@ -739,7 +736,7 @@
static void BTM_BT_Quality_Report_VSE_CBack(uint8_t length,
const uint8_t* p_stream) {
if (length == 0) {
- LOG(WARNING) << __func__ << ": Lengths of all of the parameters are zero.";
+ log::warn("Lengths of all of the parameters are zero.");
return;
}
@@ -749,7 +746,7 @@
if (sub_event == HCI_VSE_SUBCODE_BQR_SUB_EVT) {
if (btm_cb.p_bqr_report_receiver == nullptr) {
- LOG(WARNING) << __func__ << ": No registered report receiver.";
+ log::warn("No registered report receiver.");
return;
}
@@ -775,8 +772,8 @@
BTM_RegisterForVSEvents(BTM_BT_Quality_Report_VSE_CBack, is_register);
if (retval != BTM_SUCCESS) {
- LOG(WARNING) << __func__ << ": Fail to (un)register VSEvents: " << retval
- << ", is_register: " << logbool(is_register);
+ log::warn("Fail to (un)register VSEvents: {}, is_register: {}", retval,
+ logbool(is_register));
return retval;
}
@@ -786,7 +783,7 @@
btm_cb.p_bqr_report_receiver = nullptr;
}
- LOG(INFO) << __func__ << ": Success to (un)register VSEvents."
- << " is_register: " << logbool(is_register);
+ log::info("Success to (un)register VSEvents. is_register: {}",
+ logbool(is_register));
return retval;
}
diff --git a/system/stack/btm/btm_inq.cc b/system/stack/btm/btm_inq.cc
index 2751bfb..c0d4181 100644
--- a/system/stack/btm/btm_inq.cc
+++ b/system/stack/btm/btm_inq.cc
@@ -28,6 +28,7 @@
#define LOG_TAG "bluetooth"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
@@ -41,6 +42,7 @@
#include "common/time_util.h"
#include "device/include/controller.h"
#include "hci/controller_interface.h"
+#include "hci/event_checkers.h"
#include "hci/hci_layer.h"
#include "include/check.h"
#include "internal_include/bt_target.h"
@@ -127,6 +129,7 @@
tBTM_STATUS btm_ble_start_inquiry(uint8_t duration);
void btm_ble_stop_inquiry(void);
+using namespace bluetooth;
using bluetooth::Uuid;
/* 3 second timeout waiting for responses */
@@ -249,6 +252,7 @@
btsnd_hcic_rmt_name_req(raw_address, HCI_PAGE_SCAN_REP_MODE_R1,
HCI_MANDATARY_PAGE_SCAN_MODE, 0);
}
+static void btm_process_cancel_complete(tHCI_STATUS status, uint8_t mode);
/*******************************************************************************
*
* Function BTM_SetDiscoverability
@@ -274,7 +278,7 @@
bool is_limited;
bool cod_limited;
- LOG_VERBOSE("");
+ log::verbose("");
if (controller_get_interface()->SupportsBle()) {
if (btm_ble_set_discoverability((uint16_t)(inq_mode)) == BTM_SUCCESS) {
btm_cb.btm_inq_vars.discoverable_mode &= (~BTM_BLE_DISCOVERABLE_MASK);
@@ -291,7 +295,7 @@
if (!controller_get_interface()->get_is_ready()) return (BTM_DEV_RESET);
/* If the window and/or interval is '0', set to default values */
- LOG_VERBOSE("mode %d [NonDisc-0, Lim-1, Gen-2]", inq_mode);
+ log::verbose("mode {} [NonDisc-0, Lim-1, Gen-2]", inq_mode);
(inq_mode != BTM_NON_DISCOVERABLE)
? power_telemetry::GetInstance().LogInqScanStarted()
: power_telemetry::GetInstance().LogInqScanStopped();
@@ -353,7 +357,7 @@
}
void BTM_EnableInterlacedInquiryScan() {
- LOG_VERBOSE("");
+ log::verbose("");
uint16_t inq_scan_type =
osi_property_get_int32(PROPERTY_INQ_SCAN_TYPE, BTM_SCAN_TYPE_INTERLACED);
@@ -369,7 +373,7 @@
}
void BTM_EnableInterlacedPageScan() {
- LOG_VERBOSE("");
+ log::verbose("");
uint16_t page_scan_type =
osi_property_get_int32(PROPERTY_PAGE_SCAN_TYPE, BTM_SCAN_TYPE_INTERLACED);
@@ -400,7 +404,7 @@
*
******************************************************************************/
tBTM_STATUS BTM_SetInquiryMode(uint8_t mode) {
- LOG_VERBOSE("");
+ log::verbose("");
if (mode == BTM_INQ_RESULT_STANDARD) {
/* mandatory mode */
} else if (mode == BTM_INQ_RESULT_WITH_RSSI) {
@@ -463,8 +467,8 @@
const uint16_t interval = osi_property_get_int32(PROPERTY_PAGE_SCAN_INTERVAL,
BTM_DEFAULT_CONN_INTERVAL);
- LOG_VERBOSE("mode=%d [NonConn-0, Conn-1], page scan interval=(%d * 0.625)ms",
- page_mode, interval);
+ log::verbose("mode={} [NonConn-0, Conn-1], page scan interval=({} * 0.625)ms",
+ page_mode, interval);
if ((window != btm_cb.btm_inq_vars.page_scan_window) ||
(interval != btm_cb.btm_inq_vars.page_scan_period)) {
@@ -496,7 +500,7 @@
*
******************************************************************************/
uint16_t BTM_IsInquiryActive(void) {
- LOG_VERBOSE("");
+ log::verbose("");
return (btm_cb.btm_inq_vars.inq_active);
}
@@ -509,7 +513,7 @@
*
******************************************************************************/
void BTM_CancelInquiry(void) {
- LOG_VERBOSE("");
+ log::verbose("");
CHECK(BTM_IsDeviceUp());
@@ -552,7 +556,14 @@
btm_cb.btm_inq_vars.p_inq_cmpl_cb = NULL; /* Do not notify caller anymore */
if ((btm_cb.btm_inq_vars.inqparms.mode & BTM_BR_INQUIRY_MASK) != 0) {
- bluetooth::legacy::hci::GetInterface().InquiryCancel();
+ bluetooth::shim::GetHciLayer()->EnqueueCommand(
+ bluetooth::hci::InquiryCancelBuilder::Create(),
+ get_main_thread()->BindOnce(
+ [](bluetooth::hci::CommandCompleteView complete_view) {
+ bluetooth::hci::check_complete<
+ bluetooth::hci::InquiryCancelCompleteView>(complete_view);
+ btm_process_cancel_complete(HCI_SUCCESS, BTM_BR_INQUIRY_MASK);
+ }));
}
if (!bluetooth::shim::is_classic_discovery_only_enabled()) {
@@ -613,9 +624,9 @@
/* Only one active inquiry is allowed in this implementation.
Also do not allow an inquiry if the inquiry filter is being updated */
if (btm_cb.btm_inq_vars.inq_active) {
- LOG_WARN(
- "Active device discovery already in progress inq_active:0x%02x"
- " state:%hhu counter:%u",
+ log::warn(
+ "Active device discovery already in progress inq_active:0x{:02x} "
+ "state:{} counter:{}",
btm_cb.btm_inq_vars.inq_active, btm_cb.btm_inq_vars.state,
btm_cb.btm_inq_vars.inq_counter);
btm_cb.neighbor.inquiry_history_->Push({
@@ -626,7 +637,7 @@
/*** Make sure the device is ready ***/
if (!BTM_IsDeviceUp()) {
- LOG_ERROR("adapter is not up");
+ log::error("adapter is not up");
btm_cb.neighbor.inquiry_history_->Push({
.status = tBTM_INQUIRY_CMPL::NOT_STARTED,
});
@@ -661,8 +672,8 @@
.results = 0,
};
- LOG_DEBUG("Starting device discovery inq_active:0x%02x",
- btm_cb.btm_inq_vars.inq_active);
+ log::debug("Starting device discovery inq_active:0x{:02x}",
+ btm_cb.btm_inq_vars.inq_active);
// Also do BLE scanning here if we aren't limiting discovery to classic only.
// This path does not play nicely with GD BLE scanning and may cause issues
@@ -671,13 +682,13 @@
if (controller_get_interface()->SupportsBle()) {
btm_ble_start_inquiry(btm_cb.btm_inq_vars.inqparms.duration);
} else {
- LOG_WARN("Trying to do LE scan on a non-LE adapter");
+ log::warn("Trying to do LE scan on a non-LE adapter");
btm_cb.btm_inq_vars.inqparms.mode &= ~BTM_BLE_INQUIRY_MASK;
}
}
if (btm_cb.btm_inq_vars.inq_active & BTM_SSP_INQUIRY_ACTIVE) {
- LOG_INFO("Not starting inquiry as SSP is in progress");
+ log::info("Not starting inquiry as SSP is in progress");
// Report the status here because inq_complete will cancel it below
BTIF_dm_report_inquiry_status_change(
tBTM_INQUIRY_STATE::BTM_INQUIRY_STARTED);
@@ -706,8 +717,8 @@
BTIF_dm_report_inquiry_status_change(
tBTM_INQUIRY_STATE::BTM_INQUIRY_STARTED);
} else {
- LOG_INFO("Inquiry failed to start status: %s",
- bluetooth::hci::ErrorCodeText(status).c_str());
+ log::info("Inquiry failed to start status: {}",
+ bluetooth::hci::ErrorCodeText(status).c_str());
}
}));
@@ -752,7 +763,7 @@
tBTM_STATUS BTM_ReadRemoteDeviceName(const RawAddress& remote_bda,
tBTM_NAME_CMPL_CB* p_cb,
tBT_TRANSPORT transport) {
- VLOG(1) << __func__ << ": bd addr " << remote_bda;
+ log::verbose("bd addr {}", ADDRESS_TO_LOGGABLE_STR(remote_bda));
/* Use LE transport when LE is the only available option */
if (transport == BT_TRANSPORT_LE) {
return btm_ble_read_remote_name(remote_bda, p_cb);
@@ -781,7 +792,7 @@
*
******************************************************************************/
tBTM_STATUS BTM_CancelRemoteDeviceName(void) {
- LOG_VERBOSE("");
+ log::verbose("");
/* Make sure there is not already one in progress */
if (btm_cb.btm_inq_vars.remname_active) {
@@ -940,7 +951,7 @@
uint8_t num_responses;
uint8_t temp_inq_active;
- LOG_DEBUG("Resetting inquiry database");
+ log::debug("Resetting inquiry database");
/* If an inquiry or periodic inquiry is active, reset the mode to inactive */
if (btm_cb.btm_inq_vars.inq_active != BTM_INQUIRY_INACTIVE) {
@@ -1029,16 +1040,23 @@
uint8_t normal_active = (BTM_GENERAL_INQUIRY_ACTIVE);
#if (BTM_INQ_DEBUG == TRUE)
- LOG_VERBOSE("btm_inq_stop_on_ssp: no_inc_ssp=%d inq_active:0x%x state:%d ",
- btm_cb.btm_inq_vars.no_inc_ssp, btm_cb.btm_inq_vars.inq_active,
- btm_cb.btm_inq_vars.state);
+ log::verbose("btm_inq_stop_on_ssp: no_inc_ssp={} inq_active:0x{:x} state:{} ",
+ btm_cb.btm_inq_vars.no_inc_ssp, btm_cb.btm_inq_vars.inq_active,
+ btm_cb.btm_inq_vars.state);
#endif
if (btm_cb.btm_inq_vars.no_inc_ssp) {
if (btm_cb.btm_inq_vars.state == BTM_INQ_ACTIVE_STATE) {
if (btm_cb.btm_inq_vars.inq_active & normal_active) {
/* can not call BTM_CancelInquiry() here. We need to report inquiry
* complete evt */
- bluetooth::legacy::hci::GetInterface().InquiryCancel();
+ bluetooth::shim::GetHciLayer()->EnqueueCommand(
+ bluetooth::hci::InquiryCancelBuilder::Create(),
+ get_main_thread()->BindOnce(
+ [](bluetooth::hci::CommandCompleteView complete_view) {
+ bluetooth::hci::check_complete<
+ bluetooth::hci::InquiryCancelCompleteView>(complete_view);
+ btm_process_cancel_complete(HCI_SUCCESS, BTM_BR_INQUIRY_MASK);
+ }));
}
}
/* do not allow inquiry to start */
@@ -1076,8 +1094,8 @@
uint16_t xx;
#if (BTM_INQ_DEBUG == TRUE)
- LOG_VERBOSE("btm_clr_inq_db: inq_active:0x%x state:%d",
- btm_cb.btm_inq_vars.inq_active, btm_cb.btm_inq_vars.state);
+ log::verbose("btm_clr_inq_db: inq_active:0x{:x} state:{}",
+ btm_cb.btm_inq_vars.inq_active, btm_cb.btm_inq_vars.state);
#endif
std::lock_guard<std::mutex> lock(inq_db_lock_);
tINQ_DB_ENT* p_ent = inq_db_;
@@ -1090,8 +1108,8 @@
}
}
#if (BTM_INQ_DEBUG == TRUE)
- LOG_VERBOSE("inq_active:0x%x state:%d", btm_cb.btm_inq_vars.inq_active,
- btm_cb.btm_inq_vars.state);
+ log::verbose("inq_active:0x{:x} state:{}", btm_cb.btm_inq_vars.inq_active,
+ btm_cb.btm_inq_vars.state);
#endif
}
@@ -1109,7 +1127,7 @@
std::lock_guard<std::mutex> lock(bd_db_lock_);
if (p_bd_db_ != nullptr) {
- LOG_ERROR("Memory leak with bluetooth device database");
+ log::error("Memory leak with bluetooth device database");
}
/* Allocate memory to hold bd_addrs responding */
@@ -1120,7 +1138,7 @@
void btm_clr_inq_result_flt(void) {
std::lock_guard<std::mutex> lock(bd_db_lock_);
if (p_bd_db_ == nullptr) {
- LOG_WARN("Memory being reset multiple times");
+ log::warn("Memory being reset multiple times");
}
osi_free_and_reset((void**)&p_bd_db_);
@@ -1273,12 +1291,12 @@
uint16_t clock_offset;
const uint8_t* p_eir_data = NULL;
- LOG_DEBUG("Received inquiry result inq_active:0x%x state:%d",
- btm_cb.btm_inq_vars.inq_active, btm_cb.btm_inq_vars.state);
+ log::debug("Received inquiry result inq_active:0x{:x} state:{}",
+ btm_cb.btm_inq_vars.inq_active, btm_cb.btm_inq_vars.state);
/* Only process the results if the BR inquiry is still active */
if (!(btm_cb.btm_inq_vars.inq_active & BTM_BR_INQ_ACTIVE_MASK)) {
- LOG_INFO("Inquiry is inactive so dropping inquiry result");
+ log::info("Inquiry is inactive so dropping inquiry result");
return;
}
@@ -1286,20 +1304,20 @@
if (inq_res_mode == BTM_INQ_RESULT_EXTENDED) {
if (num_resp > 1) {
- LOG_ERROR("extended results (%d) > 1", num_resp);
+ log::error("extended results ({}) > 1", num_resp);
return;
}
constexpr uint16_t extended_inquiry_result_size = 254;
if (hci_evt_len - 1 != extended_inquiry_result_size) {
- LOG_ERROR("can't fit %d results in %d bytes", num_resp, hci_evt_len);
+ log::error("can't fit {} results in {} bytes", num_resp, hci_evt_len);
return;
}
} else if (inq_res_mode == BTM_INQ_RESULT_STANDARD ||
inq_res_mode == BTM_INQ_RESULT_WITH_RSSI) {
constexpr uint16_t inquiry_result_size = 14;
if (hci_evt_len < num_resp * inquiry_result_size) {
- LOG_ERROR("can't fit %d results in %d bytes", num_resp, hci_evt_len);
+ log::error("can't fit {} results in {} bytes", num_resp, hci_evt_len);
return;
}
}
@@ -1326,7 +1344,7 @@
/* Check if this address has already been processed for this inquiry */
if (btm_inq_find_bdaddr(bda)) {
- /* LOG_VERBOSE("BDA seen before %s", ADDRESS_TO_LOGGABLE_CSTR(bda));
+ /* log::verbose("BDA seen before {}", ADDRESS_TO_LOGGABLE_CSTR(bda));
*/
/* By default suppose no update needed */
@@ -1340,7 +1358,7 @@
||
(p_i->inq_info.results.device_type & BT_DEVICE_TYPE_BREDR) != 0)) {
p_cur = &p_i->inq_info.results;
- LOG_VERBOSE("update RSSI new:%d, old:%d", i_rssi, p_cur->rssi);
+ log::verbose("update RSSI new:{}, old:{}", i_rssi, p_cur->rssi);
p_cur->rssi = i_rssi;
update = true;
}
@@ -1436,7 +1454,7 @@
(p_inq_results_cb)((tBTM_INQ_RESULTS*)p_cur, p_eir_data,
HCI_EXT_INQ_RESPONSE_LEN);
} else {
- LOG_WARN("No callback is registered for inquiry result");
+ log::warn("No callback is registered for inquiry result");
}
}
}
@@ -1501,8 +1519,8 @@
tBTM_INQUIRY_STATE::BTM_INQUIRY_COMPLETE);
if (status != HCI_SUCCESS) {
- LOG_WARN("Received unexpected hci status:%s",
- hci_error_code_text(status).c_str());
+ log::warn("Received unexpected hci status:{}",
+ hci_error_code_text(status).c_str());
}
/* Ignore any stray or late complete messages if the inquiry is not active */
@@ -1529,7 +1547,7 @@
(btm_cb.btm_inq_vars.p_inq_cmpl_cb)(
(tBTM_INQUIRY_CMPL*)&btm_cb.btm_inq_vars.inq_cmpl_info);
} else {
- LOG_WARN("No callback to return inquiry result");
+ log::warn("No callback to return inquiry result");
}
btm_cb.neighbor.inquiry_history_->Push({
@@ -1570,12 +1588,12 @@
btm_cb.btm_inq_vars.p_inq_cmpl_cb = NULL;
} else {
- LOG_INFO(
- "Inquiry params is not clear so not sending callback inq_parms:%u",
+ log::info(
+ "Inquiry params is not clear so not sending callback inq_parms:{}",
btm_cb.btm_inq_vars.inqparms.mode);
}
} else {
- LOG_ERROR("Received inquiry complete when no inquiry was active");
+ log::error("Received inquiry complete when no inquiry was active");
}
}
@@ -1591,7 +1609,7 @@
* Returns void
*
******************************************************************************/
-void btm_process_cancel_complete(tHCI_STATUS status, uint8_t mode) {
+static void btm_process_cancel_complete(tHCI_STATUS status, uint8_t mode) {
BTIF_dm_report_inquiry_status_change(
tBTM_INQUIRY_STATE::BTM_INQUIRY_CANCELLED);
btm_process_inq_complete(status, mode);
@@ -1694,10 +1712,11 @@
rem_name.bd_addr = RawAddress::kEmpty;
}
- LOG_INFO("btm_process_remote_name for %s",
- ADDRESS_TO_LOGGABLE_CSTR(rem_name.bd_addr));
+ log::info("btm_process_remote_name for {}",
+ ADDRESS_TO_LOGGABLE_CSTR(rem_name.bd_addr));
- VLOG(2) << "Inquire BDA " << btm_cb.btm_inq_vars.remname_bda;
+ log::verbose("Inquire BDA {}",
+ ADDRESS_TO_LOGGABLE_CSTR(btm_cb.btm_inq_vars.remname_bda));
/* If the inquire BDA and remote DBA are the same, then stop the timer and set
* the active to false */
@@ -1761,7 +1780,7 @@
*
******************************************************************************/
void btm_inq_rmt_name_failed_cancelled(void) {
- LOG_ERROR("remname_active=%d", btm_cb.btm_inq_vars.remname_active);
+ log::error("remname_active={}", btm_cb.btm_inq_vars.remname_active);
if (btm_cb.btm_inq_vars.remname_active) {
btm_process_remote_name(&btm_cb.btm_inq_vars.remname_bda, NULL, 0,
@@ -1786,7 +1805,7 @@
******************************************************************************/
tBTM_STATUS BTM_WriteEIR(BT_HDR* p_buff) {
if (bluetooth::shim::GetController()->SupportsExtendedInquiryResponse()) {
- LOG_VERBOSE("Write Extended Inquiry Response to controller");
+ log::verbose("Write Extended Inquiry Response to controller");
btsnd_hcic_write_ext_inquiry_response(p_buff, BTM_EIR_DEFAULT_FEC_REQUIRED);
return BTM_SUCCESS;
} else {
@@ -1962,22 +1981,22 @@
}
if (*p_num_uuid > max_num_uuid) {
- LOG_WARN("number of uuid in EIR = %d, size of uuid list = %d", *p_num_uuid,
- max_num_uuid);
+ log::warn("number of uuid in EIR = {}, size of uuid list = {}", *p_num_uuid,
+ max_num_uuid);
*p_num_uuid = max_num_uuid;
}
- LOG_VERBOSE("type = %02X, number of uuid = %d", type, *p_num_uuid);
+ log::verbose("type = {:02X}, number of uuid = {}", type, *p_num_uuid);
if (uuid_size == Uuid::kNumBytes16) {
for (yy = 0; yy < *p_num_uuid; yy++) {
STREAM_TO_UINT16(*(p_uuid16 + yy), p_uuid_data);
- LOG_VERBOSE(" 0x%04X", *(p_uuid16 + yy));
+ log::verbose(" 0x{:04X}", *(p_uuid16 + yy));
}
} else if (uuid_size == Uuid::kNumBytes32) {
for (yy = 0; yy < *p_num_uuid; yy++) {
STREAM_TO_UINT32(*(p_uuid32 + yy), p_uuid_data);
- LOG_VERBOSE(" 0x%08X", *(p_uuid32 + yy));
+ log::verbose(" 0x{:08X}", *(p_uuid32 + yy));
}
} else if (uuid_size == Uuid::kNumBytes128) {
for (yy = 0; yy < *p_num_uuid; yy++) {
@@ -1985,7 +2004,7 @@
for (xx = 0; xx < Uuid::kNumBytes128; xx++)
snprintf(buff + xx * 2, sizeof(buff) - xx * 2, "%02X",
*(p_uuid_list + yy * Uuid::kNumBytes128 + xx));
- LOG_VERBOSE(" 0x%s", buff);
+ log::verbose(" 0x{}", buff);
}
}
@@ -2098,7 +2117,7 @@
}
break;
default:
- LOG_WARN("btm_convert_uuid_to_uuid16 invalid uuid size");
+ log::warn("btm_convert_uuid_to_uuid16 invalid uuid size");
break;
}
@@ -2134,7 +2153,7 @@
p_results->eir_complete_list = false;
}
- LOG_VERBOSE("eir_complete_list=0x%02X", p_results->eir_complete_list);
+ log::verbose("eir_complete_list=0x{:02X}", p_results->eir_complete_list);
if (p_uuid_data) {
for (yy = 0; yy < num_uuid; yy++) {
diff --git a/system/stack/btm/btm_iot_config.cc b/system/stack/btm/btm_iot_config.cc
index 7f2e0e1..c6ea9d8 100644
--- a/system/stack/btm/btm_iot_config.cc
+++ b/system/stack/btm/btm_iot_config.cc
@@ -18,6 +18,8 @@
#define LOG_TAG "btm_iot"
+#include <bluetooth/log.h>
+
#include "btif/include/btif_storage.h"
#include "btm_ble_api.h"
#include "device/include/device_iot_config.h"
@@ -25,6 +27,8 @@
#include "os/log.h"
#include "stack/acl/acl.h"
+using namespace bluetooth;
+
/*******************************************************************************
*
* Function btm_iot_save_remote_properties
@@ -53,9 +57,9 @@
sizeof(cod), &cod);
if (btif_storage_get_remote_device_property(&p_acl_cb->remote_addr,
&prop_name) == BT_STATUS_SUCCESS)
- LOG_VERBOSE("%s cod retrieved from storage is 0x%06x", __func__, cod);
+ log::verbose("cod retrieved from storage is 0x{:06x}", cod);
if (cod == 0) {
- LOG_VERBOSE("%s cod is 0, set as unclassified", __func__);
+ log::verbose("cod is 0, set as unclassified");
cod = (0x1F) << 8;
}
diff --git a/system/stack/btm/btm_iso_impl.h b/system/stack/btm/btm_iso_impl.h
index 950385e..8687e77 100644
--- a/system/stack/btm/btm_iso_impl.h
+++ b/system/stack/btm/btm_iso_impl.h
@@ -94,11 +94,11 @@
iso_impl() {
iso_credits_ = controller_get_interface()->get_iso_buffer_count();
iso_buffer_size_ = controller_get_interface()->get_iso_data_size();
- LOG_INFO("%p created, iso credits: %d, buffer size: %d.", this,
- iso_credits_.load(), iso_buffer_size_);
+ log::info("{} created, iso credits: {}, buffer size: {}.", fmt::ptr(this),
+ iso_credits_.load(), iso_buffer_size_);
}
- ~iso_impl() { LOG_INFO("%p removed.", this); }
+ ~iso_impl() { log::info("{} removed.", fmt::ptr(this)); }
void handle_register_cis_callbacks(CigCallbacks* callbacks) {
LOG_ASSERT(callbacks != nullptr) << "Invalid CIG callbacks";
@@ -253,7 +253,7 @@
if (!force) {
LOG_ASSERT(IsCigKnown(cig_id)) << "No such cig: " << +cig_id;
} else {
- LOG_WARN("Forcing to remove CIG %d", cig_id);
+ log::warn("Forcing to remove CIG {}", cig_id);
}
btsnd_hcic_remove_cig(cig_id, base::BindOnce(&iso_impl::on_remove_cig,
@@ -347,7 +347,7 @@
if (iso == nullptr) {
/* That can happen when ACL has been disconnected while ISO patch was
* creating */
- LOG(WARNING) << __func__ << "Invalid connection handle: " << +conn_handle;
+ log::warn("Invalid connection handle: {}", +conn_handle);
return;
}
@@ -398,7 +398,7 @@
uint16_t conn_handle;
if (len < 3) {
- LOG(WARNING) << __func__ << "Malformatted packet received";
+ log::warn("Malformatted packet received");
return;
}
STREAM_TO_UINT8(status, stream);
@@ -408,7 +408,7 @@
if (iso == nullptr) {
/* That could happen when ACL has been disconnected while removing data
* path */
- LOG(WARNING) << __func__ << "Invalid connection handle: " << +conn_handle;
+ log::warn("Invalid connection handle: {}", +conn_handle);
return;
}
@@ -460,14 +460,13 @@
// 1 + 2 + 4 * 7
#define ISO_LINK_QUALITY_SIZE 31
if (len < ISO_LINK_QUALITY_SIZE) {
- LOG(ERROR) << "Malformated link quality format, len=" << len;
+ log::error("Malformated link quality format, len={}", len);
return;
}
STREAM_TO_UINT8(status, stream);
if (status != HCI_SUCCESS) {
- LOG(ERROR) << "Failed to Read ISO Link Quality, status: "
- << loghex(status);
+ log::error("Failed to Read ISO Link Quality, status: {}", loghex(status));
return;
}
@@ -477,7 +476,7 @@
if (iso == nullptr) {
/* That could happen when ACL has been disconnected while waiting on the
* read respose */
- LOG(WARNING) << __func__ << "Invalid connection handle: " << +conn_handle;
+ log::warn("Invalid connection handle: {}", +conn_handle);
return;
}
@@ -499,7 +498,7 @@
void read_iso_link_quality(uint16_t iso_handle) {
iso_base* iso = GetIsoIfKnown(iso_handle);
if (iso == nullptr) {
- LOG(ERROR) << __func__ << "No such iso connection: " << loghex(iso_handle);
+ log::error("No such iso connection: {}", loghex(iso_handle));
return;
}
@@ -539,14 +538,13 @@
if (!(iso->state_flags & kStateFlagIsBroadcast)) {
if (!(iso->state_flags & kStateFlagIsConnected)) {
- LOG(WARNING) << __func__ << "Cis handle: " << loghex(iso_handle)
- << " not established";
+ log::warn("Cis handle: {} not established", loghex(iso_handle));
return;
}
}
if (!(iso->state_flags & kStateFlagHasDataPathSet)) {
- LOG_WARN("Data path not set for handle: 0x%04x", iso_handle);
+ log::warn("Data path not set for handle: 0x{:04x}", iso_handle);
return;
}
@@ -562,10 +560,10 @@
iso->cr_stats.credits_last_underflow_us =
bluetooth::common::time_get_os_boottime_us();
- LOG(WARNING) << __func__ << ", dropping ISO packet, len: "
- << static_cast<int>(data_len)
- << ", iso credits: " << static_cast<int>(iso_credits_)
- << ", iso handle: " << loghex(iso_handle);
+ log::warn(
+ ", dropping ISO packet, len: {}, iso credits: {}, iso handle: {}",
+ static_cast<int>(data_len), static_cast<int>(iso_credits_),
+ loghex(iso_handle));
return;
}
@@ -631,7 +629,7 @@
LOG_ASSERT(cig_callbacks_ != nullptr) << "Invalid CIG callbacks";
- LOG_INFO("%s flags: %d", __func__, +cis->state_flags);
+ log::info("flags: {}", +cis->state_flags);
BTM_LogHistory(
kBtmLogTag, cis_hdl_to_addr[handle], "CIS disconnected",
@@ -732,7 +730,7 @@
uint16_t conn_handle;
STREAM_TO_UINT16(conn_handle, data);
evt.conn_handles.push_back(conn_handle);
- LOG_INFO(" received BIS conn_hdl %d", +conn_handle);
+ log::info(" received BIS conn_hdl {}", +conn_handle);
if (evt.status == HCI_SUCCESS) {
auto bis = std::unique_ptr<iso_bis>(new iso_bis());
@@ -793,7 +791,7 @@
<< "Invalid big - already exists: " << +big_id;
if (stack_config_get_interface()->get_pts_unencrypt_broadcast()) {
- LOG_INFO("Force create broadcst without encryption for PTS test");
+ log::info("Force create broadcst without encryption for PTS test");
big_params.enc = 0;
big_params.enc_code = {0};
}
@@ -833,7 +831,7 @@
/* Not supported */
break;
default:
- LOG_ERROR("Unhandled event code %d", +code);
+ log::error("Unhandled event code {}", +code);
}
}
@@ -854,7 +852,7 @@
iso_base* iso = GetCisIfKnown(evt.cis_conn_hdl);
if (iso == nullptr) {
- LOG(ERROR) << __func__ << ", received data for the non-registered CIS!";
+ log::error(", received data for the non-registered CIS!");
return;
}
@@ -876,7 +874,7 @@
iso->evt_stats.evt_last_lost_us =
bluetooth::common::time_get_os_boottime_us();
- LOG(WARNING) << evt.evt_lost << " packets lost.";
+ log::warn("{} packets lost.", evt.evt_lost);
iso->evt_stats.seq_nb_mismatch_count++;
}
diff --git a/system/stack/btm/btm_main.cc b/system/stack/btm/btm_main.cc
index 9bd9a93..1439dd5 100644
--- a/system/stack/btm/btm_main.cc
+++ b/system/stack/btm/btm_main.cc
@@ -22,6 +22,8 @@
*
******************************************************************************/
+#include <bluetooth/log.h>
+
#include <memory>
#include <string>
@@ -35,6 +37,8 @@
#include "stack/include/inq_hci_link_interface.h" // btm_inq_db_set_inq_by_rssi
#endif // TARGET_FLOSS
+using namespace bluetooth;
+
/* Global BTM control block structure
*/
tBTM_CB btm_cb;
@@ -74,7 +78,8 @@
static void btm_log_history(const std::string& tag, const char* addr,
const std::string& msg, const std::string& extra) {
if (btm_cb.history_ == nullptr) {
- LOG_ERROR("BTM_LogHistory has not been constructed or already destroyed !");
+ log::error(
+ "BTM_LogHistory has not been constructed or already destroyed !");
return;
}
diff --git a/system/stack/btm/btm_sco.cc b/system/stack/btm/btm_sco.cc
index e87498e..a0dca7b 100644
--- a/system/stack/btm/btm_sco.cc
+++ b/system/stack/btm/btm_sco.cc
@@ -29,6 +29,7 @@
#include <base/logging.h>
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <cstdint>
#include <cstring>
@@ -87,6 +88,7 @@
}; // namespace
+using namespace bluetooth;
using bluetooth::legacy::hci::GetInterface;
// forward declaration for dequeueing packets
@@ -110,12 +112,12 @@
auto packet = hci_sco_queue_end->TryDequeue();
ASSERT(packet != nullptr);
if (!packet->IsValid()) {
- LOG_INFO("Dropping invalid packet of size %zu", packet->size());
+ log::info("Dropping invalid packet of size {}", packet->size());
return;
}
if (do_in_main_thread(FROM_HERE, base::Bind(&btm_route_sco_data, *packet)) !=
BT_STATUS_SUCCESS) {
- LOG_ERROR("do_in_main_thread failed from sco_data_callback");
+ log::error("do_in_main_thread failed from sco_data_callback");
}
}
static void register_for_sco() {
@@ -270,10 +272,10 @@
->supports_enhanced_setup_synchronous_connection() &&
!osi_property_get_bool(kPropertyDisableEnhancedConnection,
kDefaultDisableEnhancedConnection)) {
- LOG_VERBOSE(
- "%s: txbw 0x%x, rxbw 0x%x, lat 0x%x, retrans 0x%02x, "
- "pkt 0x%04x, path %u",
- __func__, p_setup->transmit_bandwidth, p_setup->receive_bandwidth,
+ log::verbose(
+ "txbw 0x{:x}, rxbw 0x{:x}, lat 0x{:x}, retrans 0x{:02x}, pkt "
+ "0x{:04x}, path {}",
+ p_setup->transmit_bandwidth, p_setup->receive_bandwidth,
p_setup->max_latency_ms, p_setup->retransmission_effort,
p_setup->packet_types, p_setup->input_data_path);
@@ -318,19 +320,19 @@
static void btm_route_sco_data(bluetooth::hci::ScoView valid_packet) {
uint16_t handle = valid_packet.GetHandle();
if (handle > HCI_HANDLE_MAX) {
- LOG_ERROR("Dropping SCO data with invalid handle: 0x%X > 0x%X, ", handle,
- HCI_HANDLE_MAX);
+ log::error("Dropping SCO data with invalid handle: 0x{:X} > 0x{:X}, ",
+ handle, HCI_HANDLE_MAX);
return;
}
tSCO_CONN* active_sco = btm_get_active_sco();
if (active_sco == nullptr) {
- LOG_ERROR("Received SCO data when there is no active SCO connection");
+ log::error("Received SCO data when there is no active SCO connection");
return;
}
if (active_sco->hci_handle != handle) {
- LOG_ERROR("Dropping packet with handle(0x%X) != active handle(0x%X)",
- handle, active_sco->hci_handle);
+ log::error("Dropping packet with handle(0x{:X}) != active handle(0x{:X})",
+ handle, active_sco->hci_handle);
return;
}
@@ -345,15 +347,15 @@
auto status = valid_packet.GetPacketStatusFlag();
if (status != bluetooth::hci::PacketStatusFlag::CORRECTLY_RECEIVED) {
- LOG_DEBUG("%s packet corrupted with status(%s)", codec.c_str(),
- PacketStatusFlagText(status).c_str());
+ log::debug("{} packet corrupted with status({})", codec.c_str(),
+ PacketStatusFlagText(status).c_str());
}
auto enqueue_packet = codec_type == BTM_SCO_CODEC_LC3
? &bluetooth::audio::sco::swb::enqueue_packet
: &bluetooth::audio::sco::wbs::enqueue_packet;
rc = enqueue_packet(
data, status != bluetooth::hci::PacketStatusFlag::CORRECTLY_RECEIVED);
- if (!rc) LOG_DEBUG("Failed to enqueue %s packet", codec.c_str());
+ if (!rc) log::debug("Failed to enqueue {} packet", codec.c_str());
while (rc) {
auto decode = codec_type == BTM_SCO_CODEC_LC3
@@ -387,9 +389,9 @@
(unsigned long)(BTM_SCO_DATA_SIZE_MAX -
btm_pcm_buf_write_offset));
- LOG_INFO(
- "Requested to read %lu bytes of %s data but got %lu bytes of "
- "PCM data from audio server: WriteOffset:%lu ReadOffset:%lu",
+ log::info(
+ "Requested to read {} bytes of {} data but got {} bytes of PCM "
+ "data from audio server: WriteOffset:{} ReadOffset:{}",
(unsigned long)to_read, codec.c_str(), (unsigned long)read,
(unsigned long)btm_pcm_buf_write_offset,
(unsigned long)btm_pcm_buf_read_offset);
@@ -400,8 +402,8 @@
} else {
/* We don't break here so that we can still decode the data in the
* buffer to spare the buffer space when the buffer is full */
- LOG_WARN(
- "Buffer is full when we try to read %s packet from audio server",
+ log::warn(
+ "Buffer is full when we try to read {} packet from audio server",
codec.c_str());
ASSERT_LOG(btm_pcm_buf_write_offset - btm_pcm_buf_read_offset >=
(codec_type == BTM_SCO_CODEC_MSBC ? BTM_MSBC_CODE_SIZE
@@ -423,9 +425,9 @@
btm_pcm_buf_write_offset - btm_pcm_buf_read_offset);
if (!rc)
- LOG_DEBUG(
- "Failed to encode %s data starting at ReadOffset:%lu to "
- "WriteOffset:%lu",
+ log::debug(
+ "Failed to encode {} data starting at ReadOffset:{} to "
+ "WriteOffset:{}",
codec.c_str(), (unsigned long)btm_pcm_buf_read_offset,
(unsigned long)btm_pcm_buf_write_offset);
@@ -456,10 +458,10 @@
(uint8_t*)btm_pcm_buf,
written < BTM_SCO_DATA_SIZE_MAX ? written : BTM_SCO_DATA_SIZE_MAX);
if (read == 0) {
- LOG_INFO("Failed to read %lu bytes of PCM data from audio server",
- (unsigned long)(written < BTM_SCO_DATA_SIZE_MAX
- ? written
- : BTM_SCO_DATA_SIZE_MAX));
+ log::info("Failed to read {} bytes of PCM data from audio server",
+ (unsigned long)(written < BTM_SCO_DATA_SIZE_MAX
+ ? written
+ : BTM_SCO_DATA_SIZE_MAX));
break;
}
written -= read;
@@ -510,8 +512,7 @@
enh_esco_params_t* p_setup) {
/* Send connect request depending on version of spec */
if (!btm_cb.sco_cb.esco_supported) {
- LOG(INFO) << __func__ << ": sending non-eSCO request for handle="
- << unsigned(acl_handle);
+ log::info("sending non-eSCO request for handle={}", unsigned(acl_handle));
btsnd_hcic_add_SCO_conn(acl_handle, BTM_ESCO_2_SCO(p_setup->packet_types));
} else {
/* Save the previous values in case command fails */
@@ -534,17 +535,17 @@
const RawAddress bd_addr = acl_address_from_handle(acl_handle);
if (bd_addr != RawAddress::kEmpty) {
if (!btm_peer_supports_esco_2m_phy(bd_addr)) {
- LOG_VERBOSE("BTM Remote does not support 2-EDR eSCO");
+ log::verbose("BTM Remote does not support 2-EDR eSCO");
temp_packet_types |=
(ESCO_PKT_TYPES_MASK_NO_2_EV3 | ESCO_PKT_TYPES_MASK_NO_2_EV5);
}
if (!btm_peer_supports_esco_3m_phy(bd_addr)) {
- LOG_VERBOSE("BTM Remote does not support 3-EDR eSCO");
+ log::verbose("BTM Remote does not support 3-EDR eSCO");
temp_packet_types |=
(ESCO_PKT_TYPES_MASK_NO_3_EV3 | ESCO_PKT_TYPES_MASK_NO_3_EV5);
}
if (!btm_peer_supports_esco_ev3(bd_addr)) {
- LOG_VERBOSE("BTM Remote does not support EV3 eSCO");
+ log::verbose("BTM Remote does not support EV3 eSCO");
// If EV3 is not supported, EV4 and EV% are not supported, either.
temp_packet_types &= ~BTM_ESCO_LINK_ONLY_MASK;
p_setup->retransmission_effort = ESCO_RETRANSMISSION_OFF;
@@ -562,36 +563,36 @@
if (local_supports_sc && remote_supports_sc) {
temp_packet_types &= ~(BTM_SCO_PKT_TYPE_MASK);
if (temp_packet_types == 0) {
- LOG_ERROR(
+ log::error(
"SCO connection cannot support any packet types for "
- "acl_handle:0x%04x",
+ "acl_handle:0x{:04x}",
acl_handle);
return BTM_WRONG_MODE;
}
- LOG_DEBUG(
+ log::debug(
"Both local and remote controllers support SCO secure connections "
- "handle:0x%04x pkt_types:0x%04x",
+ "handle:0x{:04x} pkt_types:0x{:04x}",
acl_handle, temp_packet_types);
} else if (!local_supports_sc && !remote_supports_sc) {
- LOG_DEBUG(
+ log::debug(
"Both local and remote controllers do not support secure "
- "connections for handle:0x%04x",
+ "connections for handle:0x{:04x}",
acl_handle);
} else if (remote_supports_sc) {
- LOG_DEBUG(
+ log::debug(
"Only remote controller supports secure connections for "
- "handle:0x%04x",
+ "handle:0x{:04x}",
acl_handle);
} else {
- LOG_DEBUG(
+ log::debug(
"Only local controller supports secure connections for "
- "handle:0x%04x",
+ "handle:0x{:04x}",
acl_handle);
}
} else {
- LOG_ERROR("Received SCO connect from unknown peer:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::error("Received SCO connect from unknown peer:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
}
p_setup->packet_types = temp_packet_types;
@@ -601,31 +602,32 @@
->supports_enhanced_setup_synchronous_connection() &&
!osi_property_get_bool(kPropertyDisableEnhancedConnection,
kDefaultDisableEnhancedConnection)) {
- LOG_INFO("Sending enhanced SCO connect request over handle:0x%04x",
- acl_handle);
- LOG(INFO) << __func__ << std::hex << ": enhanced parameter list"
- << " txbw=0x" << unsigned(p_setup->transmit_bandwidth)
- << ", rxbw=0x" << unsigned(p_setup->receive_bandwidth)
- << ", latency_ms=0x" << unsigned(p_setup->max_latency_ms)
- << ", retransmit_effort=0x"
- << unsigned(p_setup->retransmission_effort) << ", pkt_type=0x"
- << unsigned(p_setup->packet_types) << ", path=0x"
- << unsigned(p_setup->input_data_path);
+ log::info("Sending enhanced SCO connect request over handle:0x{:04x}",
+ acl_handle);
+ log::info(
+ "enhanced parameter list txbw=0x{:x}, rxbw=0x{}, latency_ms=0x{}, "
+ "retransmit_effort=0x{}, pkt_type=0x{}, path=0x{}",
+ unsigned(p_setup->transmit_bandwidth),
+ unsigned(p_setup->receive_bandwidth),
+ unsigned(p_setup->max_latency_ms),
+ unsigned(p_setup->retransmission_effort),
+ unsigned(p_setup->packet_types), unsigned(p_setup->input_data_path));
btsnd_hcic_enhanced_set_up_synchronous_connection(acl_handle, p_setup);
p_setup->packet_types = saved_packet_types;
p_setup->retransmission_effort = saved_retransmission_effort;
p_setup->max_latency_ms = saved_max_latency_ms;
} else { /* Use older command */
- LOG_INFO("Sending eSCO connect request over handle:0x%04x", acl_handle);
+ log::info("Sending eSCO connect request over handle:0x{:04x}",
+ acl_handle);
uint16_t voice_content_format = btm_sco_voice_settings_to_legacy(p_setup);
- LOG(INFO) << __func__ << std::hex << ": legacy parameter list"
- << " txbw=0x" << unsigned(p_setup->transmit_bandwidth)
- << ", rxbw=0x" << unsigned(p_setup->receive_bandwidth)
- << ", latency_ms=0x" << unsigned(p_setup->max_latency_ms)
- << ", retransmit_effort=0x"
- << unsigned(p_setup->retransmission_effort)
- << ", voice_content_format=0x" << unsigned(voice_content_format)
- << ", pkt_type=0x" << unsigned(p_setup->packet_types);
+ log::info(
+ "legacy parameter list txbw=0x{:x}, rxbw=0x{}, latency_ms=0x{}, "
+ "retransmit_effort=0x{}, voice_content_format=0x{}, pkt_type=0x{}",
+ unsigned(p_setup->transmit_bandwidth),
+ unsigned(p_setup->receive_bandwidth),
+ unsigned(p_setup->max_latency_ms),
+ unsigned(p_setup->retransmission_effort),
+ unsigned(voice_content_format), unsigned(p_setup->packet_types));
btsnd_hcic_setup_esco_conn(
acl_handle, p_setup->transmit_bandwidth, p_setup->receive_bandwidth,
p_setup->max_latency_ms, voice_content_format,
@@ -673,13 +675,13 @@
if (is_orig) {
if (!remote_bda) {
- LOG(ERROR) << __func__ << ": remote_bda is null";
+ log::error("remote_bda is null");
return BTM_ILLEGAL_VALUE;
}
acl_handle = BTM_GetHCIConnHandle(*remote_bda, BT_TRANSPORT_BR_EDR);
if (acl_handle == HCI_INVALID_HANDLE) {
- LOG(ERROR) << __func__ << ": cannot find ACL handle for remote device "
- << remote_bda;
+ log::error("cannot find ACL handle for remote device {}",
+ ADDRESS_TO_LOGGABLE_STR(*remote_bda));
return BTM_UNKNOWN_ADDR;
}
}
@@ -690,8 +692,8 @@
if (((p->state == SCO_ST_CONNECTING) || (p->state == SCO_ST_LISTENING) ||
(p->state == SCO_ST_PEND_UNPARK)) &&
(p->esco.data.bd_addr == *remote_bda)) {
- LOG(ERROR) << __func__ << ": a sco connection is already going on for "
- << *remote_bda << ", at state " << unsigned(p->state);
+ log::error("a sco connection is already going on for {}, at state {}",
+ ADDRESS_TO_LOGGABLE_STR(*remote_bda), unsigned(p->state));
return BTM_BUSY;
}
}
@@ -699,9 +701,8 @@
/* Support only 1 wildcard BD address at a time */
for (xx = 0; xx < BTM_MAX_SCO_LINKS; xx++, p++) {
if ((p->state == SCO_ST_LISTENING) && (!p->rem_bd_known)) {
- LOG(ERROR)
- << __func__
- << ": remote_bda is null and not known and we are still listening";
+ log::error(
+ "remote_bda is null and not known and we are still listening");
return BTM_BUSY;
}
}
@@ -718,17 +719,16 @@
if (BTM_ReadPowerMode(*remote_bda, &state)) {
if (state == BTM_PM_ST_SNIFF || state == BTM_PM_ST_PARK ||
state == BTM_PM_ST_PENDING) {
- LOG(INFO) << __func__ << ": " << *remote_bda
- << " in sniff, park or pending mode "
- << unsigned(state);
+ log::info("{} in sniff, park or pending mode {}",
+ ADDRESS_TO_LOGGABLE_STR(*remote_bda), unsigned(state));
if (!BTM_SetLinkPolicyActiveMode(*remote_bda)) {
- LOG_WARN("Unable to set link policy active");
+ log::warn("Unable to set link policy active");
}
p->state = SCO_ST_PEND_UNPARK;
}
} else {
- LOG(ERROR) << __func__ << ": failed to read power mode for "
- << *remote_bda;
+ log::error("failed to read power mode for {}",
+ ADDRESS_TO_LOGGABLE_STR(*remote_bda));
}
}
p->esco.data.bd_addr = *remote_bda;
@@ -760,8 +760,8 @@
/* If role change is in progress, do not proceed with SCO setup
* Wait till role change is complete */
if (!acl_is_switch_role_idle(*remote_bda, BT_TRANSPORT_BR_EDR)) {
- LOG_VERBOSE("Role Change is in progress for ACL handle 0x%04x",
- acl_handle);
+ log::verbose("Role Change is in progress for ACL handle 0x{:04x}",
+ acl_handle);
p->state = SCO_ST_PEND_ROLECHANGE;
}
}
@@ -770,24 +770,25 @@
if (p->state != SCO_ST_PEND_UNPARK &&
p->state != SCO_ST_PEND_ROLECHANGE) {
if (is_orig) {
- LOG_DEBUG("Initiating (e)SCO link for ACL handle:0x%04x", acl_handle);
+ log::debug("Initiating (e)SCO link for ACL handle:0x{:04x}",
+ acl_handle);
if ((btm_send_connect_request(acl_handle, p_setup)) !=
BTM_CMD_STARTED) {
- LOG(ERROR) << __func__ << ": failed to send connect request for "
- << *remote_bda;
+ log::error("failed to send connect request for {}",
+ ADDRESS_TO_LOGGABLE_STR(*remote_bda));
return (BTM_NO_RESOURCES);
}
p->state = SCO_ST_CONNECTING;
} else {
- LOG_DEBUG("Listening for (e)SCO on ACL handle:0x%04x", acl_handle);
+ log::debug("Listening for (e)SCO on ACL handle:0x{:04x}", acl_handle);
p->state = SCO_ST_LISTENING;
}
}
*p_sco_inx = xx;
- LOG_DEBUG("SCO connection successfully requested");
+ log::debug("SCO connection successfully requested");
if (p->state == SCO_ST_CONNECTING) {
BTM_LogHistory(
kBtmLogTag, *remote_bda, "Connecting",
@@ -798,7 +799,7 @@
}
/* If here, all SCO blocks in use */
- LOG(ERROR) << __func__ << ": all SCO control blocks are in use";
+ log::error("all SCO control blocks are in use");
return BTM_NO_RESOURCES;
}
@@ -819,16 +820,17 @@
uint16_t acl_handle =
BTM_GetHCIConnHandle(p->esco.data.bd_addr, BT_TRANSPORT_BR_EDR);
if ((p->state == SCO_ST_PEND_UNPARK) && (acl_handle == hci_handle)) {
- LOG(INFO) << __func__ << ": " << p->esco.data.bd_addr
- << " unparked, sending connection request, acl_handle="
- << unsigned(acl_handle)
- << ", hci_status=" << unsigned(hci_status);
+ log::info(
+ "{} unparked, sending connection request, acl_handle={}, "
+ "hci_status={}",
+ ADDRESS_TO_LOGGABLE_STR(p->esco.data.bd_addr), unsigned(acl_handle),
+ unsigned(hci_status));
if (btm_send_connect_request(acl_handle, &p->esco.setup) ==
BTM_CMD_STARTED) {
p->state = SCO_ST_CONNECTING;
} else {
- LOG(ERROR) << __func__ << ": failed to send connection request for "
- << p->esco.data.bd_addr;
+ log::error("failed to send connection request for {}",
+ ADDRESS_TO_LOGGABLE_STR(p->esco.data.bd_addr));
}
}
}
@@ -856,8 +858,8 @@
p->esco.data.bd_addr, BT_TRANSPORT_BR_EDR)) == hci_handle))
{
- LOG_VERBOSE(
- "btm_sco_chk_pend_rolechange -> (e)SCO Link for ACL handle 0x%04x",
+ log::verbose(
+ "btm_sco_chk_pend_rolechange -> (e)SCO Link for ACL handle 0x{:04x}",
acl_handle);
if ((btm_send_connect_request(acl_handle, &p->esco.setup)) ==
@@ -881,9 +883,9 @@
void btm_sco_disc_chk_pend_for_modechange(uint16_t hci_handle) {
tSCO_CONN* p = &btm_cb.sco_cb.sco_db[0];
- LOG_DEBUG(
- "Checking for SCO pending mode change events hci_handle:0x%04x "
- "p->state:%s",
+ log::debug(
+ "Checking for SCO pending mode change events hci_handle:0x{:04x} "
+ "p->state:{}",
hci_handle, sco_state_text(p->state).c_str());
for (uint16_t xx = 0; xx < BTM_MAX_SCO_LINKS; xx++, p++) {
@@ -892,7 +894,7 @@
hci_handle)
{
- LOG_DEBUG("Removing SCO Link handle 0x%04x", p->hci_handle);
+ log::debug("Removing SCO Link handle 0x{:04x}", p->hci_handle);
BTM_RemoveSco(xx);
}
}
@@ -966,7 +968,7 @@
}
/* If here, no one wants the SCO connection. Reject it */
- LOG_WARN("%s: rejecting SCO for %s", __func__, ADDRESS_TO_LOGGABLE_CSTR(bda));
+ log::warn("rejecting SCO for {}", ADDRESS_TO_LOGGABLE_CSTR(bda));
btm_esco_conn_rsp(BTM_MAX_SCO_LINKS, HCI_ERR_HOST_REJECT_RESOURCES, bda,
nullptr);
}
@@ -1007,8 +1009,8 @@
BTM_LogHistory(kBtmLogTag, bda, "Connection success",
base::StringPrintf("handle:0x%04x %s", hci_handle,
(spt) ? "listener" : "initiator"));
- LOG_DEBUG("Connected SCO link handle:0x%04x peer:%s", hci_handle,
- ADDRESS_TO_LOGGABLE_CSTR(bda));
+ log::debug("Connected SCO link handle:0x{:04x} peer:{}", hci_handle,
+ ADDRESS_TO_LOGGABLE_CSTR(bda));
if (!btm_cb.sco_cb.esco_supported) {
p->esco.data.link_type = BTM_LINK_TYPE_SCO;
@@ -1075,8 +1077,8 @@
(p->esco.data.bd_addr == bda || bda == RawAddress::kEmpty)) {
/* Report the error if originator, otherwise remain in Listen mode */
if (p->is_orig) {
- LOG_DEBUG("SCO initiating connection failed handle:0x%04x reason:%s",
- hci_handle, hci_error_code_text(hci_status).c_str());
+ log::debug("SCO initiating connection failed handle:0x{:04x} reason:{}",
+ hci_handle, hci_error_code_text(hci_status).c_str());
switch (hci_status) {
case HCI_ERR_ROLE_SWITCH_PENDING:
/* If role switch is pending, we need try again after role switch
@@ -1098,8 +1100,9 @@
hci_reason_code_text(static_cast<tHCI_REASON>(hci_status))
.c_str()));
} else {
- LOG_DEBUG("SCO terminating connection failed handle:0x%04x reason:%s",
- hci_handle, hci_error_code_text(hci_status).c_str());
+ log::debug(
+ "SCO terminating connection failed handle:0x{:04x} reason:{}",
+ hci_handle, hci_error_code_text(hci_status).c_str());
if (p->state == SCO_ST_CONNECTING) {
p->state = SCO_ST_UNUSED;
(*p->p_disc_cb)(xx);
@@ -1134,7 +1137,7 @@
tSCO_CONN* p = &btm_cb.sco_cb.sco_db[sco_inx];
tBTM_PM_STATE state = BTM_PM_ST_INVALID;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
if (BTM_MAX_SCO_LINKS == 0) {
return BTM_NO_RESOURCES;
@@ -1154,8 +1157,8 @@
if (BTM_ReadPowerMode(p->esco.data.bd_addr, &state) &&
(state == BTM_PM_ST_PENDING)) {
- LOG_VERBOSE("%s: BTM_PM_ST_PENDING for ACL mapped with SCO Link 0x%04x",
- __func__, p->hci_handle);
+ log::verbose("BTM_PM_ST_PENDING for ACL mapped with SCO Link 0x{:04x}",
+ p->hci_handle);
p->state = SCO_ST_PEND_MODECHANGE;
return (BTM_CMD_STARTED);
}
@@ -1165,8 +1168,8 @@
GetInterface().Disconnect(p->Handle(), HCI_ERR_PEER_USER);
- LOG_DEBUG("Disconnecting link sco_handle:0x%04x peer:%s", p->Handle(),
- ADDRESS_TO_LOGGABLE_CSTR(p->esco.data.bd_addr));
+ log::debug("Disconnecting link sco_handle:0x{:04x} peer:{}", p->Handle(),
+ ADDRESS_TO_LOGGABLE_CSTR(p->esco.data.bd_addr));
BTM_LogHistory(
kBtmLogTag, p->esco.data.bd_addr, "Disconnecting",
base::StringPrintf("local initiated handle:0x%04x previous_state:%s",
@@ -1217,8 +1220,8 @@
hfp_hal_interface::esco_coding_to_codec(
p->esco.setup.transmit_coding_format.coding_format));
- LOG_DEBUG("Disconnected SCO link handle:%hu reason:%s", hci_handle,
- hci_reason_code_text(reason).c_str());
+ log::debug("Disconnected SCO link handle:{} reason:{}", hci_handle,
+ hci_reason_code_text(reason).c_str());
return true;
}
}
@@ -1228,19 +1231,19 @@
void btm_sco_on_disconnected(uint16_t hci_handle, tHCI_REASON reason) {
tSCO_CONN* p_sco = btm_cb.sco_cb.get_sco_connection_from_handle(hci_handle);
if (p_sco == nullptr) {
- LOG_DEBUG("Unable to find sco connection");
+ log::debug("Unable to find sco connection");
return;
}
if (!p_sco->is_active()) {
- LOG_INFO("Connection is not active handle:0x%04x reason:%s", hci_handle,
- hci_reason_code_text(reason).c_str());
+ log::info("Connection is not active handle:0x{:04x} reason:{}", hci_handle,
+ hci_reason_code_text(reason).c_str());
return;
}
if (p_sco->state == SCO_ST_LISTENING) {
- LOG_INFO("Connection is in listening state handle:0x%04x reason:%s",
- hci_handle, hci_reason_code_text(reason).c_str());
+ log::info("Connection is in listening state handle:0x{:04x} reason:{}",
+ hci_handle, hci_reason_code_text(reason).c_str());
return;
}
@@ -1251,8 +1254,8 @@
p_sco->rem_bd_known = false;
p_sco->esco.p_esco_cback = NULL; /* Deregister eSCO callback */
(*p_sco->p_disc_cb)(btm_cb.sco_cb.get_index(p_sco));
- LOG_DEBUG("Disconnected SCO link handle:%hu reason:%s", hci_handle,
- hci_reason_code_text(reason).c_str());
+ log::debug("Disconnected SCO link handle:{} reason:{}", hci_handle,
+ hci_reason_code_text(reason).c_str());
BTM_LogHistory(kBtmLogTag, bd_addr, "Disconnected",
base::StringPrintf("handle:0x%04x reason:%s", hci_handle,
hci_reason_code_text(reason).c_str()));
@@ -1276,12 +1279,12 @@
const std::string codec = sco_codec_type_text(codec_type);
log_hfp_audio_packet_loss_stats(bd_addr, num_decoded_frames,
packet_loss_ratio, codec_id);
- LOG_DEBUG(
- "Stopped SCO codec:%s, num_decoded_frames:%d, "
- "packet_loss_ratio:%lf",
+ log::debug(
+ "Stopped SCO codec:{}, num_decoded_frames:{}, "
+ "packet_loss_ratio:{:f}",
codec.c_str(), num_decoded_frames, packet_loss_ratio);
} else {
- LOG_WARN("Failed to get the packet loss stats");
+ log::warn("Failed to get the packet loss stats");
}
auto cleanup = codec_type == BTM_SCO_CODEC_LC3
@@ -1366,9 +1369,9 @@
if (btm_cb.sco_cb.esco_supported) {
*p_def = *p_parms;
- LOG_DEBUG(
- "Setting eSCO mode parameters txbw:0x%08x rxbw:0x%08x max_lat:0x%04x"
- " pkt:0x%04x rtx_effort:0x%02x",
+ log::debug(
+ "Setting eSCO mode parameters txbw:0x{:08x} rxbw:0x{:08x} "
+ "max_lat:0x{:04x} pkt:0x{:04x} rtx_effort:0x{:02x}",
p_def->transmit_bandwidth, p_def->receive_bandwidth,
p_def->max_latency_ms, p_def->packet_types,
p_def->retransmission_effort);
@@ -1376,10 +1379,10 @@
/* Load defaults for SCO only */
*p_def = esco_parameters_for_codec(
SCO_CODEC_CVSD_D1, hfp_hal_interface::get_offload_enabled());
- LOG_WARN("eSCO not supported so setting SCO parameters instead");
- LOG_DEBUG(
- "Setting SCO mode parameters txbw:0x%08x rxbw:0x%08x max_lat:0x%04x"
- " pkt:0x%04x rtx_effort:0x%02x",
+ log::warn("eSCO not supported so setting SCO parameters instead");
+ log::debug(
+ "Setting SCO mode parameters txbw:0x{:08x} rxbw:0x{:08x} "
+ "max_lat:0x{:04x} pkt:0x{:04x} rtx_effort:0x{:02x}",
p_def->transmit_bandwidth, p_def->receive_bandwidth,
p_def->max_latency_ms, p_def->packet_types,
p_def->retransmission_effort);
@@ -1461,11 +1464,11 @@
p_parms->packet_types &
(btm_cb.btm_sco_pkt_types_supported & BTM_SCO_LINK_ONLY_MASK);
- LOG_VERBOSE("%s: SCO Link for handle 0x%04x, pkt 0x%04x", __func__,
- p_sco->hci_handle, p_setup->packet_types);
+ log::verbose("SCO Link for handle 0x{:04x}, pkt 0x{:04x}",
+ p_sco->hci_handle, p_setup->packet_types);
- LOG_VERBOSE("%s: SCO Link for handle 0x%04x, pkt 0x%04x", __func__,
- p_sco->hci_handle, p_setup->packet_types);
+ log::verbose("SCO Link for handle 0x{:04x}, pkt 0x{:04x}",
+ p_sco->hci_handle, p_setup->packet_types);
GetInterface().ChangeConnectionPacketType(
p_sco->hci_handle, BTM_ESCO_2_SCO(p_setup->packet_types));
@@ -1481,12 +1484,13 @@
(btm_cb.btm_sco_pkt_types_supported & BTM_SCO_EXCEPTION_PKTS_MASK));
p_setup->packet_types = temp_packet_types;
- LOG_VERBOSE("%s -> eSCO Link for handle 0x%04x", __func__,
- p_sco->hci_handle);
- LOG_VERBOSE(" txbw 0x%x, rxbw 0x%x, lat 0x%x, retrans 0x%02x, pkt 0x%04x",
- p_setup->transmit_bandwidth, p_setup->receive_bandwidth,
- p_parms->max_latency_ms, p_parms->retransmission_effort,
- temp_packet_types);
+ log::verbose("-> eSCO Link for handle 0x{:04x}", p_sco->hci_handle);
+ log::verbose(
+ " txbw 0x{:x}, rxbw 0x{:x}, lat 0x{:x}, retrans 0x{:02x}, pkt "
+ "0x{:04x}",
+ p_setup->transmit_bandwidth, p_setup->receive_bandwidth,
+ p_parms->max_latency_ms, p_parms->retransmission_effort,
+ temp_packet_types);
/* Use Enhanced Synchronous commands if supported */
if (controller_get_interface()
@@ -1507,9 +1511,9 @@
p_setup->packet_types);
}
- LOG_VERBOSE(
- "%s: txbw 0x%x, rxbw 0x%x, lat 0x%x, retrans 0x%02x, pkt 0x%04x",
- __func__, p_setup->transmit_bandwidth, p_setup->receive_bandwidth,
+ log::verbose(
+ "txbw 0x{:x}, rxbw 0x{:x}, lat 0x{:x}, retrans 0x{:02x}, pkt 0x{:04x}",
+ p_setup->transmit_bandwidth, p_setup->receive_bandwidth,
p_parms->max_latency_ms, p_parms->retransmission_effort,
temp_packet_types);
}
@@ -1720,7 +1724,7 @@
else /* Use 8 bit for all others */
voice_settings |= HCI_INP_SAMPLE_SIZE_8BIT;
- LOG_VERBOSE("%s: voice setting for legacy 0x%03x", __func__, voice_settings);
+ log::verbose("voice setting for legacy 0x{:03x}", voice_settings);
return (voice_settings);
}
@@ -1773,9 +1777,7 @@
bool btm_peer_supports_esco_2m_phy(RawAddress remote_bda) {
uint8_t* features = BTM_ReadRemoteFeatures(remote_bda);
if (features == nullptr) {
- LOG_WARN(
- "Checking remote features but remote feature read is "
- "incomplete");
+ log::warn("Checking remote features but remote feature read is incomplete");
return false;
}
return HCI_EDR_ESCO_2MPS_SUPPORTED(features);
@@ -1784,9 +1786,7 @@
bool btm_peer_supports_esco_3m_phy(RawAddress remote_bda) {
uint8_t* features = BTM_ReadRemoteFeatures(remote_bda);
if (features == nullptr) {
- LOG_WARN(
- "Checking remote features but remote feature read is "
- "incomplete");
+ log::warn("Checking remote features but remote feature read is incomplete");
return false;
}
return HCI_EDR_ESCO_3MPS_SUPPORTED(features);
@@ -1795,9 +1795,7 @@
bool btm_peer_supports_esco_ev3(RawAddress remote_bda) {
uint8_t* features = BTM_ReadRemoteFeatures(remote_bda);
if (features == nullptr) {
- LOG_WARN(
- "Checking remote features but remote feature read is "
- "incomplete");
+ log::warn("Checking remote features but remote feature read is incomplete");
return false;
}
return HCI_ESCO_EV3_SUPPORTED(features);
diff --git a/system/stack/btm/btm_sco_hci.cc b/system/stack/btm/btm_sco_hci.cc
index 9959ed4..27251df 100644
--- a/system/stack/btm/btm_sco_hci.cc
+++ b/system/stack/btm/btm_sco_hci.cc
@@ -14,6 +14,9 @@
* limitations under the License.
*/
+#define LOG_TAG "sco_hci"
+
+#include <bluetooth/log.h>
#include <grp.h>
#include <math.h>
#include <sys/stat.h>
@@ -22,9 +25,6 @@
#include <cfloat>
#include <memory>
-// Define before including log.h
-#define LOG_TAG "sco_hci"
-
#include "btif/include/core_callbacks.h"
#include "btif/include/stack_manager_t.h"
#include "os/log.h"
@@ -95,12 +95,12 @@
void open() {
if (sco_uipc != nullptr) {
- LOG_WARN("Re-opening UIPC that is already running");
+ log::warn("Re-opening UIPC that is already running");
}
sco_uipc = UIPC_Init();
if (sco_uipc == nullptr) {
- LOG_ERROR("%s failed to init UIPC", __func__);
+ log::error("failed to init UIPC");
return;
}
@@ -110,7 +110,7 @@
if (grp) {
int res = chown(SCO_HOST_DATA_PATH, -1, grp->gr_gid);
if (res == -1) {
- LOG_ERROR("%s failed: %s", __func__, strerror(errno));
+ log::error("failed: {}", strerror(errno));
}
}
}
@@ -125,7 +125,7 @@
size_t read(uint8_t* p_buf, uint32_t len) {
if (sco_uipc == nullptr) {
- LOG_WARN("Read from uninitialized or closed UIPC");
+ log::warn("Read from uninitialized or closed UIPC");
return 0;
}
return UIPC_Read(*sco_uipc, UIPC_CH_ID_AV_AUDIO, p_buf, len);
@@ -133,7 +133,7 @@
size_t write(const uint8_t* p_buf, uint32_t len) {
if (sco_uipc == nullptr) {
- LOG_WARN("Write to uninitialized or closed UIPC");
+ log::warn("Write to uninitialized or closed UIPC");
return 0;
}
return UIPC_Send(*sco_uipc, UIPC_CH_ID_AV_AUDIO, 0, p_buf, len) ? len : 0;
@@ -452,7 +452,7 @@
/* In case of unsupported value, error log and fallback to
* BTM_MSBC_PKT_LEN(60). */
if (btm_wbs_supported_pkt_size[i] == 0) {
- LOG_WARN("Unsupported packet size %lu", (unsigned long)pkt_size);
+ log::warn("Unsupported packet size {}", (unsigned long)pkt_size);
i = 0;
}
@@ -555,7 +555,7 @@
void mark_pkt_decoded() {
if (decode_buf_data_len() < BTM_MSBC_PKT_LEN) {
- LOG_ERROR("Trying to mark read offset beyond write offset.");
+ log::error("Trying to mark read offset beyond write offset.");
return;
}
@@ -602,8 +602,8 @@
}
if (rp != 0) {
- LOG_WARN("Skipped %lu bytes of mSBC data ahead of a valid mSBC frame",
- (unsigned long)rp);
+ log::warn("Skipped {} bytes of mSBC data ahead of a valid mSBC frame",
+ (unsigned long)rp);
incr_buf_offset(decode_buf_ro, decode_buf_ro_mirror, buf_size, rp);
}
@@ -630,7 +630,7 @@
uint8_t* fill_msbc_pkt_template() {
uint8_t* wp = &msbc_encode_buf[encode_buf_wo];
if (buf_size - encode_buf_wo < BTM_MSBC_PKT_LEN) {
- LOG_DEBUG("Packet queue can't accommodate more packets.");
+ log::debug("Packet queue can't accommodate more packets.");
return nullptr;
}
@@ -656,8 +656,8 @@
const uint8_t* sco_pkt_read_ptr() {
if (encode_buf_wo - encode_buf_ro < packet_size) {
- LOG_DEBUG("Insufficient data to dequeue. buf_wo:%zu, buf_ro:%zu",
- encode_buf_wo, encode_buf_ro);
+ log::debug("Insufficient data to dequeue. buf_wo:{}, buf_ro:{}",
+ encode_buf_wo, encode_buf_ro);
return nullptr;
}
@@ -671,7 +671,7 @@
GetInterfaceToProfiles()->msbcCodec->initialize();
if (msbc_info) {
- LOG_WARN("Re-initiating mSBC buffer that is active or not cleaned");
+ log::warn("Re-initiating mSBC buffer that is active or not cleaned");
msbc_info->deinit();
osi_free(msbc_info);
}
@@ -706,14 +706,14 @@
bool enqueue_packet(const std::vector<uint8_t>& data, bool corrupted) {
if (msbc_info == nullptr) {
- LOG_WARN("mSBC buffer uninitialized or cleaned");
+ log::warn("mSBC buffer uninitialized or cleaned");
return false;
}
if (data.size() != msbc_info->packet_size) {
- LOG_WARN(
- "Ignoring the coming packet with size %lu that is inconsistent with "
- "the HAL reported packet size %lu",
+ log::warn(
+ "Ignoring the coming packet with size {} that is inconsistent with the "
+ "HAL reported packet size {}",
(unsigned long)data.size(), (unsigned long)msbc_info->packet_size);
return false;
}
@@ -730,12 +730,12 @@
const uint8_t* frame_head = nullptr;
if (msbc_info == nullptr) {
- LOG_WARN("mSBC buffer uninitialized or cleaned");
+ log::warn("mSBC buffer uninitialized or cleaned");
return 0;
}
if (out_data == nullptr) {
- LOG_WARN("%s Invalid output pointer", __func__);
+ log::warn("Invalid output pointer");
return 0;
}
@@ -774,12 +774,12 @@
uint8_t* pkt_body = nullptr;
uint32_t encoded_size = 0;
if (msbc_info == nullptr) {
- LOG_WARN("mSBC buffer uninitialized or cleaned");
+ log::warn("mSBC buffer uninitialized or cleaned");
return 0;
}
if (data == nullptr) {
- LOG_WARN("Invalid data to encode");
+ log::warn("Invalid data to encode");
return 0;
}
@@ -795,7 +795,7 @@
encoded_size =
GetInterfaceToProfiles()->msbcCodec->encodePacket(data, pkt_body);
if (encoded_size != BTM_MSBC_PKT_FRAME_LEN) {
- LOG_WARN("Encoding invalid packet size: %lu", (unsigned long)encoded_size);
+ log::warn("Encoding invalid packet size: {}", (unsigned long)encoded_size);
std::copy(&btm_msbc_zero_packet[BTM_MSBC_H2_HEADER_LEN],
std::end(btm_msbc_zero_packet), pkt_body);
}
@@ -805,12 +805,12 @@
size_t dequeue_packet(const uint8_t** output) {
if (msbc_info == nullptr) {
- LOG_WARN("mSBC buffer uninitialized or cleaned");
+ log::warn("mSBC buffer uninitialized or cleaned");
return 0;
}
if (output == nullptr) {
- LOG_WARN("%s Invalid output pointer", __func__);
+ log::warn("Invalid output pointer");
return 0;
}
@@ -878,7 +878,7 @@
/* In case of unsupported value, error log and fallback to
* BTM_LC3_PKT_LEN(60). */
if (btm_swb_supported_pkt_size[i] == 0) {
- LOG_WARN("Unsupported packet size %lu", (unsigned long)pkt_size);
+ log::warn("Unsupported packet size {}", (unsigned long)pkt_size);
i = 0;
}
@@ -932,7 +932,7 @@
uint8_t* fill_lc3_pkt_template() {
uint8_t* wp = &lc3_encode_buf[encode_buf_wo];
if (buf_size - encode_buf_wo < BTM_LC3_PKT_LEN) {
- LOG_DEBUG("Packet queue can't accommodate more packets.");
+ log::debug("Packet queue can't accommodate more packets.");
return nullptr;
}
@@ -946,7 +946,7 @@
void mark_pkt_decoded() {
if (decode_buf_ro + BTM_LC3_PKT_LEN > decode_buf_wo) {
- LOG_ERROR("Trying to mark read offset beyond write offset.");
+ log::error("Trying to mark read offset beyond write offset.");
return;
}
@@ -983,8 +983,8 @@
}
if (rp != 0) {
- LOG_WARN("Skipped %lu bytes of LC3 data ahead of a valid LC3 frame",
- (unsigned long)rp);
+ log::warn("Skipped {} bytes of LC3 data ahead of a valid LC3 frame",
+ (unsigned long)rp);
decode_buf_ro += rp;
}
return &lc3_decode_buf[decode_buf_ro];
@@ -1007,8 +1007,8 @@
const uint8_t* sco_pkt_read_ptr() {
if (encode_buf_wo - encode_buf_ro < packet_size) {
- LOG_DEBUG("Insufficient data to dequeue. buf_wo:%zu, buf_ro:%zu",
- encode_buf_wo, encode_buf_ro);
+ log::debug("Insufficient data to dequeue. buf_wo:{}, buf_ro:{}",
+ encode_buf_wo, encode_buf_ro);
return nullptr;
}
@@ -1027,7 +1027,7 @@
lost_frames = 0;
if (lc3_info) {
- LOG_WARN("Re-initiating LC3 buffer that is active or not cleaned");
+ log::warn("Re-initiating LC3 buffer that is active or not cleaned");
lc3_info->deinit();
osi_free(lc3_info);
}
@@ -1063,14 +1063,14 @@
bool enqueue_packet(const std::vector<uint8_t>& data, bool corrupted) {
if (lc3_info == nullptr) {
- LOG_WARN("LC3 buffer uninitialized or cleaned");
+ log::warn("LC3 buffer uninitialized or cleaned");
return false;
}
if (data.size() != lc3_info->packet_size) {
- LOG_WARN(
- "Ignoring the coming packet with size %lu that is inconsistent with "
- "the HAL reported packet size %lu",
+ log::warn(
+ "Ignoring the coming packet with size {} that is inconsistent with the "
+ "HAL reported packet size {}",
(unsigned long)data.size(), (unsigned long)lc3_info->packet_size);
return false;
}
@@ -1087,12 +1087,12 @@
const uint8_t* frame_head = nullptr;
if (lc3_info == nullptr) {
- LOG_WARN("LC3 buffer uninitialized or cleaned");
+ log::warn("LC3 buffer uninitialized or cleaned");
return 0;
}
if (out_data == nullptr) {
- LOG_WARN("%s Invalid output pointer", __func__);
+ log::warn("Invalid output pointer");
return 0;
}
@@ -1119,12 +1119,12 @@
size_t encode(int16_t* data, size_t len) {
uint8_t* pkt_body = nullptr;
if (lc3_info == nullptr) {
- LOG_WARN("LC3 buffer uninitialized or cleaned");
+ log::warn("LC3 buffer uninitialized or cleaned");
return 0;
}
if (data == nullptr) {
- LOG_WARN("Invalid data to encode");
+ log::warn("Invalid data to encode");
return 0;
}
@@ -1142,12 +1142,12 @@
size_t dequeue_packet(const uint8_t** output) {
if (lc3_info == nullptr) {
- LOG_WARN("LC3 buffer uninitialized or cleaned");
+ log::warn("LC3 buffer uninitialized or cleaned");
return 0;
}
if (output == nullptr) {
- LOG_WARN("%s Invalid output pointer", __func__);
+ log::warn("Invalid output pointer");
return 0;
}
diff --git a/system/stack/btm/btm_sco_hfp_hal_linux.cc b/system/stack/btm/btm_sco_hfp_hal_linux.cc
index 15e4d44..236b6c0 100644
--- a/system/stack/btm/btm_sco_hfp_hal_linux.cc
+++ b/system/stack/btm/btm_sco_hfp_hal_linux.cc
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+#include <bluetooth/log.h>
#include <poll.h>
#include <sys/socket.h>
#include <unistd.h>
@@ -24,11 +25,12 @@
#include "common/init_flags.h"
#include "hci/controller_interface.h"
#include "main/shim/entry.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#include "osi/include/properties.h"
#include "stack/include/hcimsgs.h"
#include "stack/include/sdpdefs.h"
+using namespace bluetooth;
using bluetooth::legacy::hci::GetInterface;
namespace hfp_hal_interface {
@@ -128,13 +130,13 @@
c.pkt_size = rp->wbs_pkt_len;
break;
default:
- LOG_DEBUG("Unsupported codec ID: %u", codec_id);
+ log::debug("Unsupported codec ID: {}", codec_id);
continue;
}
- LOG_INFO("Caching HFP codec %u, data path %u, data len %d, pkt_size %u",
- (uint64_t)c.inner.codec, c.inner.data_path, c.inner.data.size(),
- c.pkt_size);
+ log::info("Caching HFP codec {}, data path {}, data len {}, pkt_size {}",
+ (uint64_t)c.inner.codec, c.inner.data_path, c.inner.data.size(),
+ c.pkt_size);
cached_codecs.push_back(c);
}
@@ -153,7 +155,7 @@
int btsocket_open_mgmt(uint16_t hci) {
int fd = socket(PF_BLUETOOTH, SOCK_RAW | SOCK_NONBLOCK, BTPROTO_HCI);
if (fd < 0) {
- LOG_DEBUG("Failed to open BT socket.");
+ log::debug("Failed to open BT socket.");
return -errno;
}
@@ -165,7 +167,7 @@
int ret = bind(fd, (struct sockaddr*)&addr, sizeof(addr));
if (ret < 0) {
- LOG_DEBUG("Failed to bind BT socket.");
+ log::debug("Failed to bind BT socket.");
close(fd);
return -errno;
}
@@ -194,8 +196,8 @@
if (ret > 0) {
RETRY_ON_INTR(ret = write(fd, &ev, MGMT_PKT_HDR_SIZE + ev.len));
if (ret < 0) {
- LOG_DEBUG("Failed to call MGMT_OP_GET_SCO_CODEC_CAPABILITIES: %d",
- -errno);
+ log::debug("Failed to call MGMT_OP_GET_SCO_CODEC_CAPABILITIES: {}",
+ -errno);
return -errno;
};
break;
@@ -203,7 +205,7 @@
} while (ret > 0);
if (ret <= 0) {
- LOG_DEBUG("Failed waiting for mgmt socket to be writable.");
+ log::debug("Failed waiting for mgmt socket to be writable.");
return -1;
}
@@ -218,7 +220,7 @@
if (fds[0].revents & POLLIN) {
RETRY_ON_INTR(ret = read(fd, &ev, sizeof(ev)));
if (ret < 0) {
- LOG_DEBUG("Failed to read mgmt socket: %d", -errno);
+ log::debug("Failed to read mgmt socket: {}", -errno);
return -errno;
}
@@ -238,7 +240,7 @@
}
}
} else if (ret == 0) {
- LOG_DEBUG("Timeout while waiting for codec capabilities response.");
+ log::debug("Timeout while waiting for codec capabilities response.");
ret = -1;
}
} while (ret > 0);
@@ -282,8 +284,8 @@
if (ret > 0) {
RETRY_ON_INTR(ret = write(fd, &ev, MGMT_PKT_HDR_SIZE + ev.len));
if (ret < 0) {
- LOG_ERROR("Failed to call MGMT_OP_NOTIFY_SCO_CONNECTION_CHANGE: %d",
- -errno);
+ log::error("Failed to call MGMT_OP_NOTIFY_SCO_CONNECTION_CHANGE: {}",
+ -errno);
return -errno;
};
break;
@@ -291,7 +293,7 @@
} while (ret > 0);
if (ret <= 0) {
- LOG_DEBUG("Failed waiting for mgmt socket to be writable.");
+ log::debug("Failed waiting for mgmt socket to be writable.");
return -1;
}
@@ -303,15 +305,15 @@
int hci = bluetooth::common::InitFlags::GetAdapterIndex();
int fd = btsocket_open_mgmt(hci);
if (fd < 0) {
- LOG_ERROR("Failed to open mgmt channel, error= %d.", fd);
+ log::error("Failed to open mgmt channel, error= {}.", fd);
return;
}
int ret = mgmt_get_codec_capabilities(fd, hci);
if (ret) {
- LOG_ERROR("Failed to get codec capabilities with error = %d.", ret);
+ log::error("Failed to get codec capabilities with error = {}.", ret);
} else {
- LOG_INFO("Successfully queried SCO codec capabilities.");
+ log::info("Successfully queried SCO codec capabilities.");
}
close(fd);
@@ -360,8 +362,7 @@
// Set offload enable/disable
bool enable_offload(bool enable) {
if (!offload_supported && enable) {
- LOG_ERROR("%s: Cannot enable SCO-offload since it is not supported.",
- __func__);
+ log::error("Cannot enable SCO-offload since it is not supported.");
return false;
}
offload_enabled = enable;
@@ -388,7 +389,7 @@
uint8_t codec_id;
if (codec_uuid == UUID_CODEC_LC3 && get_offload_enabled()) {
- LOG_ERROR("Offload path for LC3 is not implemented.");
+ log::error("Offload path for LC3 is not implemented.");
return;
}
@@ -403,21 +404,22 @@
codec_id = get_offload_enabled() ? codec::LC3 : codec::MSBC_TRANSPARENT;
break;
default:
- LOG_WARN("Unsupported codec (%d). Won't set datapath.", codec_uuid);
+ log::warn("Unsupported codec ({}). Won't set datapath.", codec_uuid);
return;
}
found = get_single_codec(codec_id, &codec);
if (!found) {
- LOG_ERROR("Failed to find codec config for codec (%d). Won't set datapath.",
- codec_uuid);
+ log::error(
+ "Failed to find codec config for codec ({}). Won't set datapath.",
+ codec_uuid);
return;
}
- LOG_INFO("Configuring datapath for codec (%d)", codec_uuid);
+ log::info("Configuring datapath for codec ({})", codec_uuid);
if (codec->codec == codec::MSBC && !get_offload_enabled()) {
- LOG_ERROR(
- "Tried to configure offload data path for format (%d) with offload "
+ log::error(
+ "Tried to configure offload data path for format ({}) with offload "
"disabled. Won't set datapath.",
codec_uuid);
return;
@@ -458,12 +460,12 @@
int hci = bluetooth::common::InitFlags::GetAdapterIndex();
int fd = btsocket_open_mgmt(hci);
if (fd < 0) {
- LOG_ERROR("Failed to open mgmt channel, error= %d.", fd);
+ log::error("Failed to open mgmt channel, error= {}.", fd);
return;
}
if (codec == codec::LC3) {
- LOG_ERROR("Offload path for LC3 is not implemented.");
+ log::error("Offload path for LC3 is not implemented.");
return;
}
@@ -483,14 +485,14 @@
int ret = mgmt_notify_sco_connection_change(fd, hci, device, is_connected,
converted_codec);
if (ret) {
- LOG_ERROR(
- "Failed to notify HAL of connection change: hci %d, device %s, "
- "connected %d, codec %d",
+ log::error(
+ "Failed to notify HAL of connection change: hci {}, device {}, "
+ "connected {}, codec {}",
hci, ADDRESS_TO_LOGGABLE_CSTR(device), is_connected, codec);
} else {
- LOG_INFO(
- "Notified HAL of connection change: hci %d, device %s, connected %d, "
- "codec %d",
+ log::info(
+ "Notified HAL of connection change: hci {}, device {}, connected {}, "
+ "codec {}",
hci, ADDRESS_TO_LOGGABLE_CSTR(device), is_connected, codec);
}
diff --git a/system/stack/btm/btm_sec.cc b/system/stack/btm/btm_sec.cc
index 7c482c9..8786253 100644
--- a/system/stack/btm/btm_sec.cc
+++ b/system/stack/btm/btm_sec.cc
@@ -28,6 +28,7 @@
#include <base/functional/bind.h>
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <cstdint>
#include <string>
@@ -76,6 +77,8 @@
}
+using namespace bluetooth;
+
extern tBTM_CB btm_cb;
#define BTM_SEC_MAX_COLLISION_DELAY (5000)
@@ -281,9 +284,10 @@
*
******************************************************************************/
bool BTM_SecRegister(const tBTM_APPL_INFO* p_cb_info) {
- LOG_INFO("p_cb_info->p_le_callback == 0x%p", p_cb_info->p_le_callback);
+ log::info("p_cb_info->p_le_callback == 0x{}",
+ fmt::ptr(p_cb_info->p_le_callback));
if (p_cb_info->p_le_callback) {
- LOG_VERBOSE("SMP_Register( btm_proc_smp_cback )");
+ log::verbose("SMP_Register( btm_proc_smp_cback )");
SMP_Register(btm_proc_smp_cback);
Octet16 zero{0};
/* if no IR is loaded, need to regenerate all the keys */
@@ -291,13 +295,13 @@
btm_ble_reset_id();
}
} else {
- LOG_WARN("p_cb_info->p_le_callback == NULL");
+ log::warn("p_cb_info->p_le_callback == NULL");
}
btm_sec_cb.api = *p_cb_info;
- LOG_INFO("btm_sec_cb.api.p_le_callback = 0x%p ",
- btm_sec_cb.api.p_le_callback);
- LOG_VERBOSE("application registered");
+ log::info("btm_sec_cb.api.p_le_callback = 0x{} ",
+ fmt::ptr(btm_sec_cb.api.p_le_callback));
+ log::verbose("application registered");
return (true);
}
@@ -368,7 +372,7 @@
if (p_dev_rec != nullptr) {
return p_dev_rec->can_read_discoverable;
} else {
- LOG_ERROR(
+ log::error(
"BTM_CanReadDiscoverableCharacteristics invoked for an invalid "
"BD_ADDR");
return false;
@@ -385,8 +389,8 @@
*
******************************************************************************/
void BTM_SetPinType(uint8_t pin_type, PIN_CODE pin_code, uint8_t pin_code_len) {
- LOG_VERBOSE(
- "BTM_SetPinType: pin type %d [variable-0, fixed-1], code %s, length %d",
+ log::verbose(
+ "BTM_SetPinType: pin type {} [variable-0, fixed-1], code {}, length {}",
pin_type, (char*)pin_code, pin_code_len);
/* If device is not up security mode will be set as a part of startup */
@@ -488,26 +492,26 @@
uint8_t pin_len, uint8_t* p_pin) {
tBTM_SEC_DEV_REC* p_dev_rec;
- LOG_VERBOSE(
- "BTM_PINCodeReply(): PairState: %s PairFlags: 0x%02x PinLen:%d "
- "Result:%d",
+ log::verbose(
+ "BTM_PINCodeReply(): PairState: {} PairFlags: 0x{:02x} PinLen:{} "
+ "Result:{}",
tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
btm_sec_cb.pairing_flags, pin_len, res);
/* If timeout already expired or has been canceled, ignore the reply */
if (btm_sec_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_PIN) {
- LOG_WARN("BTM_PINCodeReply() - Wrong State: %d", btm_sec_cb.pairing_state);
+ log::warn("BTM_PINCodeReply() - Wrong State: {}", btm_sec_cb.pairing_state);
return;
}
if (bd_addr != btm_sec_cb.pairing_bda) {
- LOG_ERROR("BTM_PINCodeReply() - Wrong BD Addr");
+ log::error("BTM_PINCodeReply() - Wrong BD Addr");
return;
}
p_dev_rec = btm_find_dev(bd_addr);
if (p_dev_rec == NULL) {
- LOG_ERROR("BTM_PINCodeReply() - no dev CB");
+ log::error("BTM_PINCodeReply() - no dev CB");
return;
}
@@ -554,7 +558,7 @@
* HCI_Connection_Complete event */
/* before originating */
if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) {
- LOG_WARN(
+ log::warn(
"BTM_PINCodeReply(): waiting HCI_Connection_Complete after rejected "
"incoming connection");
/* we change state little bit early so btm_sec_connected() will originate
@@ -564,7 +568,7 @@
}
/* if we already accepted incoming connection from pairing device */
else if (p_dev_rec->sm4 & BTM_SM4_CONN_PEND) {
- LOG_WARN(
+ log::warn(
"BTM_PINCodeReply(): link is connecting so wait pin code request "
"from peer");
btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ);
@@ -600,28 +604,28 @@
tBT_TRANSPORT transport) {
tBTM_SEC_DEV_REC* p_dev_rec;
tBTM_STATUS status;
- LOG_INFO("Transport used %d, bd_addr=%s", transport,
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::info("Transport used {}, bd_addr={}", transport,
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
/* Other security process is in progress */
if (btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) {
- LOG_ERROR("BTM_SecBond: already busy in state: %s",
- tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state));
+ log::error("BTM_SecBond: already busy in state: {}",
+ tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state));
return (BTM_WRONG_MODE);
}
p_dev_rec = btm_find_or_alloc_dev(bd_addr);
if (p_dev_rec == NULL) {
- LOG_ERROR("No memory to allocate new p_dev_rec");
+ log::error("No memory to allocate new p_dev_rec");
return (BTM_NO_RESOURCES);
}
if (!controller_get_interface()->get_is_ready()) {
- LOG_ERROR("controller module is not ready");
+ log::error("controller module is not ready");
return (BTM_NO_RESOURCES);
}
- LOG_VERBOSE("before update sec_flags=0x%x", p_dev_rec->sec_rec.sec_flags);
+ log::verbose("before update sec_flags=0x{:x}", p_dev_rec->sec_rec.sec_flags);
/* Finished if connection is active and already paired */
if (((p_dev_rec->hci_handle != HCI_INVALID_HANDLE) &&
@@ -630,13 +634,13 @@
((p_dev_rec->ble_hci_handle != HCI_INVALID_HANDLE) &&
transport == BT_TRANSPORT_LE &&
(p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_AUTHENTICATED))) {
- LOG_WARN("BTM_SecBond -> Already Paired");
+ log::warn("BTM_SecBond -> Already Paired");
return (BTM_SUCCESS);
}
/* Tell controller to get rid of the link key if it has one stored */
if ((BTM_DeleteStoredLinkKey(&bd_addr, NULL)) != BTM_SUCCESS) {
- LOG_ERROR("Failed to delete stored link keys");
+ log::error("Failed to delete stored link keys");
return (BTM_NO_RESOURCES);
}
@@ -669,7 +673,7 @@
~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_AUTHENTICATED | BTM_SEC_ENCRYPTED |
BTM_SEC_ROLE_SWITCHED | BTM_SEC_LINK_KEY_AUTHED);
- LOG_VERBOSE("after update sec_flags=0x%x", p_dev_rec->sec_rec.sec_flags);
+ log::verbose("after update sec_flags=0x{:x}", p_dev_rec->sec_rec.sec_flags);
if (!bluetooth::shim::GetController()->SupportsSimplePairing()) {
/* The special case when we authenticate keyboard. Set pin type to fixed */
/* It would be probably better to do it from the application, but it is */
@@ -683,8 +687,8 @@
}
}
- LOG_VERBOSE("BTM_SecBond: Remote sm4: 0x%x HCI Handle: 0x%04x",
- p_dev_rec->sm4, p_dev_rec->hci_handle);
+ log::verbose("BTM_SecBond: Remote sm4: 0x{:x} HCI Handle: 0x{:04x}",
+ p_dev_rec->sm4, p_dev_rec->hci_handle);
#if (BTM_SEC_FORCE_RNR_FOR_DBOND == TRUE)
p_dev_rec->sec_rec.sec_flags &= ~BTM_SEC_NAME_KNOWN;
@@ -701,7 +705,8 @@
return (BTM_CMD_STARTED);
}
- LOG_VERBOSE("sec mode: %d sm4:x%x", btm_sec_cb.security_mode, p_dev_rec->sm4);
+ log::verbose("sec mode: {} sm4:x{:x}", btm_sec_cb.security_mode,
+ p_dev_rec->sm4);
if (!bluetooth::shim::GetController()->SupportsSimplePairing() ||
(p_dev_rec->sm4 == BTM_SM4_KNOWN)) {
if (btm_sec_check_prefetch_pin(p_dev_rec)) return (BTM_CMD_STARTED);
@@ -721,17 +726,18 @@
btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ);
status = BTM_CMD_STARTED;
}
- LOG_VERBOSE("State:%s sm4: 0x%x sec_state:%d",
- tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
- p_dev_rec->sm4, p_dev_rec->sec_rec.sec_state);
+ log::verbose("State:{} sm4: 0x{:x} sec_state:{}",
+ tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
+ p_dev_rec->sm4, p_dev_rec->sec_rec.sec_state);
} else {
/* both local and peer are 2.1 */
status = btm_sec_dd_create_conn(p_dev_rec);
}
if (status != BTM_CMD_STARTED) {
- LOG_ERROR("BTM_ReadRemoteDeviceName or btm_sec_dd_create_conn error: 0x%x",
- (int)status);
+ log::error(
+ "BTM_ReadRemoteDeviceName or btm_sec_dd_create_conn error: 0x{:x}",
+ (int)status);
btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
}
@@ -758,7 +764,7 @@
transport =
BTM_UseLeLink(bd_addr) ? BT_TRANSPORT_LE : BT_TRANSPORT_BR_EDR;
} else {
- LOG_INFO("Forcing transport LE (was auto) because of the address type");
+ log::info("Forcing transport LE (was auto) because of the address type");
transport = BT_TRANSPORT_LE;
}
}
@@ -769,7 +775,7 @@
if ((transport == BT_TRANSPORT_LE && (dev_type & BT_DEVICE_TYPE_BLE) == 0) ||
(transport == BT_TRANSPORT_BR_EDR &&
(dev_type & BT_DEVICE_TYPE_BREDR) == 0)) {
- LOG_WARN(
+ log::warn(
"Can't start bonding - requested transport and transport we've seen "
"device on don't match");
return BTM_ILLEGAL_ACTION;
@@ -791,9 +797,9 @@
tBTM_STATUS BTM_SecBondCancel(const RawAddress& bd_addr) {
tBTM_SEC_DEV_REC* p_dev_rec;
- LOG_VERBOSE("BTM_SecBondCancel() State: %s flags:0x%x",
- tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
- btm_sec_cb.pairing_flags);
+ log::verbose("BTM_SecBondCancel() State: {} flags:0x{:x}",
+ tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
+ btm_sec_cb.pairing_flags);
p_dev_rec = btm_find_dev(bd_addr);
if (!p_dev_rec || btm_sec_cb.pairing_bda != bd_addr) {
return BTM_UNKNOWN_ADDR;
@@ -801,7 +807,7 @@
if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_LE_ACTIVE) {
if (p_dev_rec->sec_rec.sec_state == BTM_SEC_STATE_AUTHENTICATING) {
- LOG_VERBOSE("Cancel LE pairing");
+ log::verbose("Cancel LE pairing");
if (SMP_PairCancel(bd_addr)) {
return BTM_CMD_STARTED;
}
@@ -809,8 +815,8 @@
return BTM_WRONG_MODE;
}
- LOG_VERBOSE("hci_handle:0x%x sec_state:%d", p_dev_rec->hci_handle,
- p_dev_rec->sec_rec.sec_state);
+ log::verbose("hci_handle:0x{:x} sec_state:{}", p_dev_rec->hci_handle,
+ p_dev_rec->sec_rec.sec_state);
if (BTM_PAIR_STATE_WAIT_LOCAL_PIN == btm_sec_cb.pairing_state &&
BTM_PAIR_FLAGS_WE_STARTED_DD & btm_sec_cb.pairing_flags) {
/* pre-fetching pin for dedicated bonding */
@@ -912,7 +918,7 @@
tBTM_BLE_SEC_ACT sec_act) {
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
if (p_dev_rec == nullptr) {
- LOG_ERROR("Unable to set encryption for unknown device");
+ log::error("Unable to set encryption for unknown device");
return BTM_WRONG_MODE;
}
@@ -921,10 +927,11 @@
switch (transport) {
case BT_TRANSPORT_BR_EDR:
if (p_dev_rec->hci_handle == HCI_INVALID_HANDLE) {
- LOG_WARN(
- "Security Manager: BTM_SetEncryption not connected peer:%s "
- "transport:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), bt_transport_text(transport).c_str());
+ log::warn(
+ "Security Manager: BTM_SetEncryption not connected peer:{} "
+ "transport:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ bt_transport_text(transport).c_str());
if (p_callback) {
do_in_main_thread(
FROM_HERE, base::BindOnce(p_callback, std::move(owned_bd_addr),
@@ -933,10 +940,11 @@
return BTM_WRONG_MODE;
}
if (p_dev_rec->sec_rec.sec_flags & BTM_SEC_ENCRYPTED) {
- LOG_DEBUG(
- "Security Manager: BTM_SetEncryption already encrypted peer:%s "
- "transport:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), bt_transport_text(transport).c_str());
+ log::debug(
+ "Security Manager: BTM_SetEncryption already encrypted peer:{} "
+ "transport:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ bt_transport_text(transport).c_str());
if (p_callback) {
do_in_main_thread(FROM_HERE,
base::BindOnce(p_callback, std::move(owned_bd_addr),
@@ -948,10 +956,11 @@
case BT_TRANSPORT_LE:
if (p_dev_rec->ble_hci_handle == HCI_INVALID_HANDLE) {
- LOG_WARN(
- "Security Manager: BTM_SetEncryption not connected peer:%s "
- "transport:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), bt_transport_text(transport).c_str());
+ log::warn(
+ "Security Manager: BTM_SetEncryption not connected peer:{} "
+ "transport:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ bt_transport_text(transport).c_str());
if (p_callback) {
do_in_main_thread(
FROM_HERE, base::BindOnce(p_callback, std::move(owned_bd_addr),
@@ -960,10 +969,11 @@
return BTM_WRONG_MODE;
}
if (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_ENCRYPTED) {
- LOG_DEBUG(
- "Security Manager: BTM_SetEncryption already encrypted peer:%s "
- "transport:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), bt_transport_text(transport).c_str());
+ log::debug(
+ "Security Manager: BTM_SetEncryption already encrypted peer:{} "
+ "transport:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ bt_transport_text(transport).c_str());
if (p_callback) {
do_in_main_thread(FROM_HERE,
base::BindOnce(p_callback, std::move(owned_bd_addr),
@@ -974,7 +984,7 @@
break;
default:
- LOG_ERROR("Unknown transport");
+ log::error("Unknown transport");
break;
}
@@ -1010,8 +1020,8 @@
}
if (enqueue) {
- LOG_WARN("Security Manager: Enqueue request in state:%s",
- security_state_text(p_dev_rec->sec_rec.sec_state).c_str());
+ log::warn("Security Manager: Enqueue request in state:{}",
+ security_state_text(p_dev_rec->sec_rec.sec_state).c_str());
btm_sec_queue_encrypt_request(bd_addr, transport, p_callback, p_ref_data,
sec_act);
return BTM_CMD_STARTED;
@@ -1019,10 +1029,10 @@
} else {
if (p_dev_rec->sec_rec.p_callback ||
(p_dev_rec->sec_rec.sec_state != BTM_SEC_STATE_IDLE)) {
- LOG_WARN("Security Manager: BTM_SetEncryption busy, enqueue request");
+ log::warn("Security Manager: BTM_SetEncryption busy, enqueue request");
btm_sec_queue_encrypt_request(bd_addr, transport, p_callback, p_ref_data,
sec_act);
- LOG_INFO("Queued start encryption");
+ log::info("Queued start encryption");
return BTM_CMD_STARTED;
}
}
@@ -1033,10 +1043,10 @@
(BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT);
p_dev_rec->is_originator = false;
- LOG_DEBUG(
- "Security Manager: BTM_SetEncryption classic_handle:0x%04x "
- "ble_handle:0x%04x state:%d flags:0x%x "
- "required:0x%x p_callback=%c",
+ log::debug(
+ "Security Manager: BTM_SetEncryption classic_handle:0x{:04x} "
+ "ble_handle:0x{:04x} state:{} flags:0x{:x} required:0x{:x} "
+ "p_callback={:c}",
p_dev_rec->hci_handle, p_dev_rec->ble_hci_handle,
p_dev_rec->sec_rec.sec_state, p_dev_rec->sec_rec.sec_flags,
p_dev_rec->sec_rec.security_required, (p_callback) ? 'T' : 'F');
@@ -1049,7 +1059,7 @@
L2CA_GetBleConnRole(bd_addr));
} else {
rc = BTM_WRONG_MODE;
- LOG_WARN("cannot call btm_ble_set_encryption, p is NULL");
+ log::warn("cannot call btm_ble_set_encryption, p is NULL");
}
break;
@@ -1058,7 +1068,7 @@
break;
default:
- LOG_ERROR("Unknown transport");
+ log::error("Unknown transport");
break;
}
@@ -1069,9 +1079,9 @@
default:
if (p_callback) {
- LOG_DEBUG("Executing encryption callback peer:%s transport:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
- bt_transport_text(transport).c_str());
+ log::debug("Executing encryption callback peer:{} transport:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ bt_transport_text(transport).c_str());
p_dev_rec->sec_rec.p_callback = nullptr;
do_in_main_thread(
FROM_HERE,
@@ -1133,8 +1143,8 @@
break;
}
- LOG_DEBUG("Send hci disconnect handle:0x%04x reason:%s", conn_handle,
- hci_reason_code_text(reason).c_str());
+ log::debug("Send hci disconnect handle:0x{:04x} reason:{}", conn_handle,
+ hci_reason_code_text(reason).c_str());
acl_disconnect_after_role_switch(conn_handle, reason, comment);
return status;
@@ -1153,14 +1163,15 @@
*
******************************************************************************/
void BTM_ConfirmReqReply(tBTM_STATUS res, const RawAddress& bd_addr) {
- LOG_VERBOSE("BTM_ConfirmReqReply() State: %s Res: %u",
- tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), res);
+ log::verbose("BTM_ConfirmReqReply() State: {} Res: {}",
+ tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
+ res);
/* If timeout already expired or has been canceled, ignore the reply */
if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_WAIT_NUMERIC_CONFIRM) ||
(btm_sec_cb.pairing_bda != bd_addr)) {
- LOG_WARN(
- "Unexpected pairing confirm for %s, pairing_state: %s, pairing_bda: %s",
+ log::warn(
+ "Unexpected pairing confirm for {}, pairing_state: {}, pairing_bda: {}",
ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
ADDRESS_TO_LOGGABLE_CSTR(btm_sec_cb.pairing_bda));
@@ -1200,8 +1211,9 @@
******************************************************************************/
void BTM_PasskeyReqReply(tBTM_STATUS res, const RawAddress& bd_addr,
uint32_t passkey) {
- LOG_VERBOSE("BTM_PasskeyReqReply: State: %s res:%d",
- tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), res);
+ log::verbose("BTM_PasskeyReqReply: State: {} res:{}",
+ tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
+ res);
if ((btm_sec_cb.pairing_state == BTM_PAIR_STATE_IDLE) ||
(btm_sec_cb.pairing_bda != bd_addr)) {
@@ -1270,8 +1282,9 @@
******************************************************************************/
void BTM_RemoteOobDataReply(tBTM_STATUS res, const RawAddress& bd_addr,
const Octet16& c, const Octet16& r) {
- LOG_VERBOSE("State: %s res: %d",
- tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), res);
+ log::verbose("State: {} res: {}",
+ tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
+ res);
/* If timeout already expired or has been canceled, ignore the reply */
if (btm_sec_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_OOB_RSP) return;
@@ -1326,7 +1339,7 @@
p_dev_rec = btm_find_dev(bd_addr);
if (p_dev_rec == NULL) {
- LOG_WARN("unknown BDA: %s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::warn("unknown BDA: {}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return false;
}
@@ -1351,7 +1364,7 @@
tBT_DEVICE_TYPE BTM_GetPeerDeviceTypeFromFeatures(const RawAddress& bd_addr) {
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
if (p_dev_rec == nullptr) {
- LOG_WARN("Unknown BDA:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::warn("Unknown BDA:{}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
} else {
if (p_dev_rec->remote_supports_ble && p_dev_rec->remote_supports_bredr) {
return BT_DEVICE_TYPE_DUMO;
@@ -1360,8 +1373,8 @@
} else if (p_dev_rec->remote_supports_ble) {
return BT_DEVICE_TYPE_BLE;
} else {
- LOG_WARN("Device features does not support BR/EDR and BLE:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::warn("Device features does not support BR/EDR and BLE:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
}
}
return BT_DEVICE_TYPE_BREDR;
@@ -1421,8 +1434,8 @@
is_possible = true;
}
}
- LOG_VERBOSE("is_possible: %d sec_flags: 0x%x", is_possible,
- p_dev_rec->sec_rec.sec_flags);
+ log::verbose("is_possible: {} sec_flags: 0x{:x}", is_possible,
+ p_dev_rec->sec_rec.sec_flags);
return is_possible;
}
@@ -1438,13 +1451,14 @@
******************************************************************************/
static void btm_sec_check_upgrade(tBTM_SEC_DEV_REC* p_dev_rec,
bool is_originator) {
- LOG_VERBOSE("verify whether the link key should be upgraded");
+ log::verbose("verify whether the link key should be upgraded");
/* Only check if link key already exists */
if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_KNOWN)) return;
if (btm_sec_is_upgrade_possible(p_dev_rec, is_originator)) {
- LOG_VERBOSE("need upgrade!! sec_flags:0x%x", p_dev_rec->sec_rec.sec_flags);
+ log::verbose("need upgrade!! sec_flags:0x{:x}",
+ p_dev_rec->sec_rec.sec_flags);
/* if the application confirms the upgrade, set the upgrade bit */
p_dev_rec->sm4 |= BTM_SM4_UPGRADE;
@@ -1452,16 +1466,16 @@
p_dev_rec->sec_rec.sec_flags &=
~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED);
p_dev_rec->sec_rec.sec_flags &= ~BTM_SEC_AUTHENTICATED;
- LOG_VERBOSE("sec_flags:0x%x", p_dev_rec->sec_rec.sec_flags);
+ log::verbose("sec_flags:0x{:x}", p_dev_rec->sec_rec.sec_flags);
}
}
tBTM_STATUS btm_sec_l2cap_access_req_by_requirement(
const RawAddress& bd_addr, uint16_t security_required, bool is_originator,
tBTM_SEC_CALLBACK* p_callback, void* p_ref_data) {
- LOG_DEBUG(
- "Checking l2cap access requirements peer:%s security:0x%x "
- "is_initiator:%s",
+ log::debug(
+ "Checking l2cap access requirements peer:{} security:0x{:x} "
+ "is_initiator:{}",
ADDRESS_TO_LOGGABLE_CSTR(bd_addr), security_required,
logbool(is_originator).c_str());
@@ -1481,9 +1495,9 @@
/* acceptor receives L2CAP Channel Connect Request for Secure Connections
* Only service */
if (!local_supports_sc || !p_dev_rec->SupportsSecureConnections()) {
- LOG_WARN(
- "Policy requires mode 4 level 4, but local_support_for_sc=%d, "
- "rmt_support_for_sc=%s, failing connection",
+ log::warn(
+ "Policy requires mode 4 level 4, but local_support_for_sc={}, "
+ "rmt_support_for_sc={}, failing connection",
local_supports_sc,
logbool(p_dev_rec->SupportsSecureConnections()).c_str());
if (p_callback) {
@@ -1500,8 +1514,8 @@
/* we will process one after another */
if ((p_dev_rec->sec_rec.p_callback) ||
(btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE)) {
- LOG_DEBUG("security_flags:x%x, sec_flags:x%x", security_required,
- p_dev_rec->sec_rec.sec_flags);
+ log::debug("security_flags:x{:x}, sec_flags:x{:x}", security_required,
+ p_dev_rec->sec_rec.sec_flags);
rc = BTM_CMD_STARTED;
if ((btm_sec_cb.security_mode == BTM_SEC_MODE_SERVICE) ||
(BTM_SM4_KNOWN == p_dev_rec->sm4) ||
@@ -1544,7 +1558,9 @@
if (rc == BTM_SUCCESS) {
if (access_secure_service_from_temp_bond(p_dev_rec, is_originator, security_required)) {
- LOG_ERROR("Trying to access a secure service from a temp bonding, rejecting");
+ log::error(
+ "Trying to access a secure service from a temp bonding, "
+ "rejecting");
rc = BTM_FAILED_ON_SECURITY;
}
@@ -1578,8 +1594,8 @@
}
} else if (!(BTM_SM4_KNOWN & p_dev_rec->sm4)) {
/* the remote features are not known yet */
- LOG_DEBUG(
- "Remote features have not yet been received sec_flags:0x%02x %s",
+ log::debug(
+ "Remote features have not yet been received sec_flags:0x{:02x} {}",
p_dev_rec->sec_rec.sec_flags,
(is_originator) ? "initiator" : "acceptor");
@@ -1588,18 +1604,18 @@
}
}
- LOG_VERBOSE("sm4:0x%x, sec_flags:0x%x, security_required:0x%x chk:%d",
- p_dev_rec->sm4, p_dev_rec->sec_rec.sec_flags, security_required,
- chk_acp_auth_done);
+ log::verbose("sm4:0x{:x}, sec_flags:0x{:x}, security_required:0x{:x} chk:{}",
+ p_dev_rec->sm4, p_dev_rec->sec_rec.sec_flags, security_required,
+ chk_acp_auth_done);
p_dev_rec->sec_rec.security_required = security_required;
p_dev_rec->sec_rec.p_ref_data = p_ref_data;
p_dev_rec->is_originator = is_originator;
if (chk_acp_auth_done) {
- LOG_VERBOSE(
- "(SM4 to SM4) btm_sec_l2cap_access_req rspd. authenticated: x%x, enc: "
- "x%x",
+ log::verbose(
+ "(SM4 to SM4) btm_sec_l2cap_access_req rspd. authenticated: x{:x}, "
+ "enc: x{:x}",
(p_dev_rec->sec_rec.sec_flags & BTM_SEC_AUTHENTICATED),
(p_dev_rec->sec_rec.sec_flags & BTM_SEC_ENCRYPTED));
/* SM4, but we do not know for sure which level of security we need.
@@ -1612,7 +1628,7 @@
sequence
because of data path issues. Delay this disconnect a little bit
*/
- LOG_INFO(
+ log::info(
"peer should have initiated security process by now (SM4 to SM4)");
p_dev_rec->sec_rec.p_callback = p_callback;
p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_DELAY_FOR_ENC;
@@ -1635,7 +1651,7 @@
p_dev_rec->sec_rec.sec_flags &=
~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED |
BTM_SEC_AUTHENTICATED);
- LOG_VERBOSE("sec_flags:0x%x", p_dev_rec->sec_rec.sec_flags);
+ log::verbose("sec_flags:0x{:x}", p_dev_rec->sec_rec.sec_flags);
} else {
/* If we already have a link key to the connected peer, is it secure
* enough? */
@@ -1645,8 +1661,8 @@
rc = btm_sec_execute_procedure(p_dev_rec);
if (rc != BTM_CMD_STARTED) {
- LOG_VERBOSE("p_dev_rec=%p, clearing callback. old p_callback=%p", p_dev_rec,
- p_dev_rec->sec_rec.p_callback);
+ log::verbose("p_dev_rec={}, clearing callback. old p_callback={}",
+ fmt::ptr(p_dev_rec), fmt::ptr(p_dev_rec->sec_rec.p_callback));
p_dev_rec->sec_rec.p_callback = NULL;
(*p_callback)(&bd_addr, transport, p_dev_rec->sec_rec.p_ref_data, rc);
}
@@ -1679,7 +1695,7 @@
// should check PSM range in LE connection oriented L2CAP connection
constexpr tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR;
- LOG_DEBUG("is_originator:%d, psm=0x%04x", is_originator, psm);
+ log::debug("is_originator:{}, psm=0x{:04x}", is_originator, psm);
// Find the service record for the PSM
tBTM_SEC_SERV_REC* p_serv_rec =
@@ -1687,14 +1703,14 @@
// If there is no application registered with this PSM do not allow connection
if (!p_serv_rec) {
- LOG_WARN("PSM: 0x%04x no application registered", psm);
+ log::warn("PSM: 0x{:04x} no application registered", psm);
(*p_callback)(&bd_addr, transport, p_ref_data, BTM_MODE_UNSUPPORTED);
return (BTM_MODE_UNSUPPORTED);
}
/* Services level0 by default have no security */
if (psm == BT_PSM_SDP) {
- LOG_DEBUG("No security required for SDP");
+ log::debug("No security required for SDP");
(*p_callback)(&bd_addr, transport, p_ref_data, BTM_SUCCESS_NO_SECURITY);
return (BTM_SUCCESS);
}
@@ -1743,7 +1759,8 @@
tBTM_STATUS rc;
bool transport = false; /* should check PSM range in LE connection oriented
L2CAP connection */
- LOG_DEBUG("Multiplex access request device:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::debug("Multiplex access request device:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
/* Find or get oldest record */
p_dev_rec = btm_find_or_alloc_dev(bd_addr);
@@ -1753,8 +1770,8 @@
/* we will process one after another */
if ((p_dev_rec->sec_rec.p_callback) ||
(btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE)) {
- LOG_DEBUG("Pairing in progress pairing_state:%s",
- tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state));
+ log::debug("Pairing in progress pairing_state:{}",
+ tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state));
rc = BTM_CMD_STARTED;
@@ -1799,7 +1816,7 @@
/* the new security request */
if (p_dev_rec->sec_rec.sec_state != BTM_SEC_STATE_IDLE) {
- LOG_DEBUG("A pending security procedure in progress");
+ log::debug("A pending security procedure in progress");
rc = BTM_CMD_STARTED;
}
if (rc == BTM_CMD_STARTED) {
@@ -1809,11 +1826,13 @@
{
if (access_secure_service_from_temp_bond(p_dev_rec,
is_originator, security_required)) {
- LOG_ERROR("Trying to access a secure rfcomm service from a temp bonding, rejecting");
+ log::error(
+ "Trying to access a secure rfcomm service from a temp bonding, "
+ "rejecting");
rc = BTM_FAILED_ON_SECURITY;
}
if (p_callback) {
- LOG_DEBUG("Notifying client that security access has been granted");
+ log::debug("Notifying client that security access has been granted");
(*p_callback)(&bd_addr, transport, p_ref_data, rc);
}
}
@@ -1827,9 +1846,9 @@
/* acceptor receives service connection establishment Request for */
/* Secure Connections Only service */
if (!(local_supports_sc) || !(p_dev_rec->SupportsSecureConnections())) {
- LOG_DEBUG(
- "Secure Connection only mode unsupported local_SC_support:%s"
- " remote_SC_support:%s",
+ log::debug(
+ "Secure Connection only mode unsupported local_SC_support:{} "
+ "remote_SC_support:{}",
logbool(local_supports_sc).c_str(),
logbool(p_dev_rec->SupportsSecureConnections()).c_str());
if (p_callback)
@@ -1864,9 +1883,9 @@
p_dev_rec->sec_rec.sec_flags &=
~(BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED |
BTM_SEC_AUTHENTICATED);
- LOG_VERBOSE("sec_flags:0x%x", p_dev_rec->sec_rec.sec_flags);
+ log::verbose("sec_flags:0x{:x}", p_dev_rec->sec_rec.sec_flags);
} else {
- LOG_DEBUG("Already have link key; checking if link key is sufficient");
+ log::debug("Already have link key; checking if link key is sufficient");
btm_sec_check_upgrade(p_dev_rec, is_originator);
}
}
@@ -1877,9 +1896,9 @@
p_dev_rec->sec_rec.p_ref_data = p_ref_data;
rc = btm_sec_execute_procedure(p_dev_rec);
- LOG_DEBUG("Started security procedure peer:%s btm_status:%s",
- ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->RemoteAddress()),
- btm_status_text(rc).c_str());
+ log::debug("Started security procedure peer:{} btm_status:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->RemoteAddress()),
+ btm_status_text(rc).c_str());
if (rc != BTM_CMD_STARTED) {
if (p_callback) {
p_dev_rec->sec_rec.p_callback = NULL;
@@ -1906,7 +1925,8 @@
if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
(btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) &&
(btm_sec_cb.pairing_bda == bda)) {
- LOG_VERBOSE("Security Manager: reject connect request from bonding device");
+ log::verbose(
+ "Security Manager: reject connect request from bonding device");
/* incoming connection from bonding device is rejected */
btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_REJECTED_CONNECT;
@@ -1972,9 +1992,9 @@
*
******************************************************************************/
void btm_create_conn_cancel_complete(uint8_t status, const RawAddress bd_addr) {
- LOG_VERBOSE("btm_create_conn_cancel_complete(): in State: %s status:%d",
- tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
- status);
+ log::verbose("btm_create_conn_cancel_complete(): in State: {} status:{}",
+ tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
+ status);
log_link_layer_connection_event(
&bd_addr, bluetooth::common::kUnknownConnectionHandle,
android::bluetooth::DIRECTION_OUTGOING, android::bluetooth::LINK_TYPE_ACL,
@@ -2029,7 +2049,7 @@
/* Check that the ACL is still up before starting security procedures */
if (BTM_IsAclConnectionUp(p_e->bd_addr, p_e->transport)) {
if (p_e->psm != 0) {
- LOG_VERBOSE("PSM:0x%04x Is_Orig:%u", p_e->psm, p_e->is_orig);
+ log::verbose("PSM:0x{:04x} Is_Orig:{}", p_e->psm, p_e->is_orig);
btm_sec_mx_access_request(p_e->bd_addr, p_e->is_orig,
p_e->rfcomm_security_requirement,
@@ -2066,7 +2086,7 @@
BTM_SEC_NONE, BT_PSM_RFCOMM, BTM_SEC_PROTO_RFCOMM, 0);
BTM_SetSecurityLevel(true, "RFC_MUX", BTM_SEC_SERVICE_RFC_MUX, BTM_SEC_NONE,
BT_PSM_RFCOMM, BTM_SEC_PROTO_RFCOMM, 0);
- LOG_VERBOSE("btm_sec_dev_reset sec mode: %d", btm_sec_cb.security_mode);
+ log::verbose("btm_sec_dev_reset sec mode: {}", btm_sec_cb.security_mode);
}
/*******************************************************************************
@@ -2092,8 +2112,8 @@
p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_IDLE;
- LOG_VERBOSE("clearing callback. p_dev_rec=%p, p_callback=%p", p_dev_rec,
- p_dev_rec->sec_rec.p_callback);
+ log::verbose("clearing callback. p_dev_rec={}, p_callback={}",
+ fmt::ptr(p_dev_rec), fmt::ptr(p_dev_rec->sec_rec.p_callback));
p_dev_rec->sec_rec.p_callback = NULL;
}
@@ -2125,8 +2145,8 @@
/* set up the control block to indicated dedicated bonding */
btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_DISC_WHEN_DONE;
- LOG_INFO("Security Manager: %s",
- ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr));
+ log::info("Security Manager: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr));
btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_PIN_REQ);
@@ -2142,8 +2162,8 @@
if (p_bd_addr == nullptr) {
// TODO Still need to send status back to get SDP state machine
// running
- LOG_ERROR("Unable to issue callback with unknown address status:%s",
- hci_status_code_text(status).c_str());
+ log::error("Unable to issue callback with unknown address status:{}",
+ hci_status_code_text(status).c_str());
return;
}
@@ -2176,13 +2196,14 @@
tBTM_SEC_DEV_REC* p_dev_rec = nullptr;
uint8_t old_sec_state;
- LOG_INFO("btm_sec_rmt_name_request_complete for %s",
- p_bd_addr ? ADDRESS_TO_LOGGABLE_CSTR(*p_bd_addr) : "null");
+ log::info("btm_sec_rmt_name_request_complete for {}",
+ p_bd_addr ? ADDRESS_TO_LOGGABLE_CSTR(*p_bd_addr) : "null");
if ((!p_bd_addr && !BTM_IsAclConnectionUp(btm_sec_cb.connecting_bda,
BT_TRANSPORT_BR_EDR)) ||
(p_bd_addr && !BTM_IsAclConnectionUp(*p_bd_addr, BT_TRANSPORT_BR_EDR))) {
- LOG_WARN("Remote read request complete with no underlying link connection");
+ log::warn(
+ "Remote read request complete with no underlying link connection");
}
/* If remote name request failed, p_bd_addr is null and we need to search */
@@ -2190,7 +2211,7 @@
if (p_bd_addr)
p_dev_rec = btm_find_dev(*p_bd_addr);
else {
- LOG_INFO(
+ log::info(
"Remote read request complete with no address so searching device "
"database");
p_dev_rec = btm_sec_find_dev_by_sec_state(BTM_SEC_STATE_GETTING_NAME);
@@ -2202,11 +2223,12 @@
if (!p_bd_name) p_bd_name = (const uint8_t*)"";
if (p_dev_rec == nullptr) {
- LOG_DEBUG(
- "Remote read request complete for unknown device pairing_state:%s "
- "status:%s name:%s",
+ log::debug(
+ "Remote read request complete for unknown device pairing_state:{} "
+ "status:{} name:{}",
tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
- hci_status_code_text(status).c_str(), p_bd_name);
+ hci_status_code_text(status).c_str(),
+ reinterpret_cast<char const*>(p_bd_name));
call_registered_rmt_name_callbacks(p_bd_addr, kDevClassEmpty, nullptr,
status);
@@ -2215,23 +2237,25 @@
old_sec_state = p_dev_rec->sec_rec.sec_state;
if (status == HCI_SUCCESS) {
- LOG_DEBUG(
- "Remote read request complete for known device pairing_state:%s "
- "name:%s sec_state:%s",
- tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), p_bd_name,
+ log::debug(
+ "Remote read request complete for known device pairing_state:{} "
+ "name:{} sec_state:{}",
+ tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
+ reinterpret_cast<char const*>(p_bd_name),
security_state_text(p_dev_rec->sec_rec.sec_state).c_str());
strlcpy((char*)p_dev_rec->sec_bd_name, (const char*)p_bd_name,
BTM_MAX_REM_BD_NAME_LEN + 1);
p_dev_rec->sec_rec.sec_flags |= BTM_SEC_NAME_KNOWN;
- LOG_VERBOSE("setting BTM_SEC_NAME_KNOWN sec_flags:0x%x",
- p_dev_rec->sec_rec.sec_flags);
+ log::verbose("setting BTM_SEC_NAME_KNOWN sec_flags:0x{:x}",
+ p_dev_rec->sec_rec.sec_flags);
} else {
- LOG_WARN(
- "Remote read request failed for known device pairing_state:%s "
- "status:%s name:%s sec_state:%s",
+ log::warn(
+ "Remote read request failed for known device pairing_state:{} "
+ "status:{} name:{} sec_state:{}",
tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
- hci_status_code_text(status).c_str(), p_bd_name,
+ hci_status_code_text(status).c_str(),
+ reinterpret_cast<char const*>(p_bd_name),
security_state_text(p_dev_rec->sec_rec.sec_state).c_str());
/* Notify all clients waiting for name to be resolved even if it failed so
@@ -2250,14 +2274,13 @@
* ask now */
if ((btm_sec_cb.pairing_state == BTM_PAIR_STATE_WAIT_LOCAL_PIN) &&
p_bd_addr && (btm_sec_cb.pairing_bda == *p_bd_addr)) {
- LOG_VERBOSE(
- "delayed pin now being requested flags:0x%x, "
- "(p_pin_callback=0x%p)",
- btm_sec_cb.pairing_flags, btm_sec_cb.api.p_pin_callback);
+ log::verbose(
+ "delayed pin now being requested flags:0x{:x}, (p_pin_callback=0x{})",
+ btm_sec_cb.pairing_flags, fmt::ptr(btm_sec_cb.api.p_pin_callback));
if ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_PIN_REQD) == 0 &&
btm_sec_cb.api.p_pin_callback) {
- LOG_VERBOSE("calling pin_callback");
+ log::verbose("calling pin_callback");
btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
(*btm_sec_cb.api.p_pin_callback)(
p_dev_rec->bd_addr, p_dev_rec->dev_class, p_bd_name,
@@ -2273,8 +2296,8 @@
/* Check if we were delaying bonding because name was not resolved */
if (btm_sec_cb.pairing_state == BTM_PAIR_STATE_GET_REM_NAME) {
if (p_bd_addr && btm_sec_cb.pairing_bda == *p_bd_addr) {
- LOG_VERBOSE("continue bonding sm4: 0x%04x, status:0x%x", p_dev_rec->sm4,
- status);
+ log::verbose("continue bonding sm4: 0x{:04x}, status:0x{:x}",
+ p_dev_rec->sm4, status);
if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_CANCEL_DD) {
btm_sec_bond_cancel_complete();
return;
@@ -2292,15 +2315,15 @@
/* set the KNOWN flag only if BTM_PAIR_FLAGS_REJECTED_CONNECT is not
* set.*/
/* If it is set, there may be a race condition */
- LOG_VERBOSE("IS_SM4_UNKNOWN Flags:0x%04x", btm_sec_cb.pairing_flags);
+ log::verbose("IS_SM4_UNKNOWN Flags:0x{:04x}", btm_sec_cb.pairing_flags);
if ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) == 0)
p_dev_rec->sm4 |= BTM_SM4_KNOWN;
}
- LOG_VERBOSE("SM4 Value: %x, Legacy:%d,IS SM4:%d, Unknown:%d",
- p_dev_rec->sm4, BTM_SEC_IS_SM4_LEGACY(p_dev_rec->sm4),
- BTM_SEC_IS_SM4(p_dev_rec->sm4),
- BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4));
+ log::verbose("SM4 Value: {:x}, Legacy:{},IS SM4:{}, Unknown:{}",
+ p_dev_rec->sm4, BTM_SEC_IS_SM4_LEGACY(p_dev_rec->sm4),
+ BTM_SEC_IS_SM4(p_dev_rec->sm4),
+ BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4));
bool await_connection = true;
/* BT 2.1 or carkit, bring up the connection to force the peer to request
@@ -2314,7 +2337,7 @@
* HCI_Connection_Complete event */
/* before originating */
if (btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) {
- LOG_WARN(
+ log::warn(
"waiting HCI_Connection_Complete after rejecting connection");
}
/* Both we and the peer are 2.1 - continue to create connection */
@@ -2323,7 +2346,7 @@
if (req_status == BTM_SUCCESS) {
await_connection = false;
} else if (req_status != BTM_CMD_STARTED) {
- LOG_WARN("failed to start connection");
+ log::warn("failed to start connection");
btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
@@ -2333,14 +2356,14 @@
}
if (await_connection) {
- LOG_DEBUG("Wait for connection to begin pairing");
+ log::debug("Wait for connection to begin pairing");
return;
}
} else {
- LOG_WARN("wrong BDA, retry with pairing BDA");
+ log::warn("wrong BDA, retry with pairing BDA");
if (BTM_ReadRemoteDeviceName(btm_sec_cb.pairing_bda, NULL,
BT_TRANSPORT_BR_EDR) != BTM_CMD_STARTED) {
- LOG_ERROR("failed to start remote name request");
+ log::error("failed to start remote name request");
NotifyBondingChange(*p_dev_rec, HCI_ERR_MEMORY_FULL);
};
return;
@@ -2360,7 +2383,7 @@
/* If this is a bonding procedure can disconnect the link now */
if ((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) &&
(p_dev_rec->sec_rec.sec_flags & BTM_SEC_AUTHENTICATED)) {
- LOG_WARN("btm_sec_rmt_name_request_complete (none/ce)");
+ log::warn("btm_sec_rmt_name_request_complete (none/ce)");
p_dev_rec->sec_rec.security_required &= ~(BTM_SEC_OUT_AUTHENTICATE);
l2cu_start_post_bond_timer(p_dev_rec->hci_handle);
return;
@@ -2375,7 +2398,7 @@
}
if (p_dev_rec->sm4 & BTM_SM4_REQ_PEND) {
- LOG_VERBOSE("waiting for remote features!!");
+ log::verbose("waiting for remote features!!");
return;
}
@@ -2406,19 +2429,20 @@
p_dev_rec = btm_find_or_alloc_dev(bd_addr);
- LOG_INFO("Got btm_sec_rmt_host_support_feat_evt from %s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::info("Got btm_sec_rmt_host_support_feat_evt from {}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
- LOG_VERBOSE("btm_sec_rmt_host_support_feat_evt sm4: 0x%x p[0]: 0x%x",
- p_dev_rec->sm4, features_0);
+ log::verbose("btm_sec_rmt_host_support_feat_evt sm4: 0x{:x} p[0]: 0x{:x}",
+ p_dev_rec->sm4, features_0);
if (BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)) {
p_dev_rec->sm4 = BTM_SM4_KNOWN;
if (HCI_SSP_HOST_SUPPORTED((std::array<uint8_t, 1>({features_0})))) {
p_dev_rec->sm4 = BTM_SM4_TRUE;
}
- LOG_VERBOSE("btm_sec_rmt_host_support_feat_evt sm4: 0x%x features[0]: 0x%x",
- p_dev_rec->sm4, features_0);
+ log::verbose(
+ "btm_sec_rmt_host_support_feat_evt sm4: 0x{:x} features[0]: 0x{:x}",
+ p_dev_rec->sm4, features_0);
}
}
@@ -2435,8 +2459,8 @@
******************************************************************************/
void btm_io_capabilities_req(RawAddress p) {
if (btm_sec_is_a_bonded_dev(p)) {
- LOG_WARN("Incoming bond request, but %s is already bonded (removing)",
- ADDRESS_TO_LOGGABLE_CSTR(p));
+ log::warn("Incoming bond request, but {} is already bonded (removing)",
+ ADDRESS_TO_LOGGABLE_CSTR(p));
bta_dm_process_remove_device(p);
}
@@ -2444,9 +2468,9 @@
if ((btm_sec_cb.security_mode == BTM_SEC_MODE_SC) &&
(!p_dev_rec->remote_feature_received)) {
- LOG_VERBOSE(
- "Device security mode is SC only."
- "To continue need to know remote features.");
+ log::verbose(
+ "Device security mode is SC only.To continue need to know remote "
+ "features.");
// ACL calls back to btm_sec_set_peer_sec_caps after it gets data
p_dev_rec->remote_features_needed = true;
@@ -2466,9 +2490,9 @@
p_dev_rec->sm4 |= BTM_SM4_TRUE;
- LOG_VERBOSE("State: %s, Security Mode: %d, Device security Flags: 0x%04x",
- tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
- btm_sec_cb.security_mode, btm_sec_cb.pairing_flags);
+ log::verbose("State: {}, Security Mode: {}, Device security Flags: 0x{:04x}",
+ tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
+ btm_sec_cb.security_mode, btm_sec_cb.pairing_flags);
uint8_t err_code = 0;
bool is_orig = true;
@@ -2502,23 +2526,23 @@
/* any other state is unexpected */
default:
err_code = HCI_ERR_HOST_BUSY_PAIRING;
- LOG_ERROR("Unexpected Pairing state received %d",
- btm_sec_cb.pairing_state);
+ log::error("Unexpected Pairing state received {}",
+ btm_sec_cb.pairing_state);
break;
}
if (btm_sec_cb.pairing_disabled) {
/* pairing is not allowed */
- LOG_VERBOSE("Pairing is not allowed -> fail pairing.");
+ log::verbose("Pairing is not allowed -> fail pairing.");
err_code = HCI_ERR_PAIRING_NOT_ALLOWED;
} else if (btm_sec_cb.security_mode == BTM_SEC_MODE_SC) {
bool local_supports_sc =
bluetooth::shim::GetController()->SupportsSecureConnections();
/* device in Secure Connections Only mode */
if (!(local_supports_sc) || !(p_dev_rec->SupportsSecureConnections())) {
- LOG_DEBUG(
- "SC only service, local_support_for_sc:%s,"
- " remote_support_for_sc:%s -> fail pairing",
+ log::debug(
+ "SC only service, local_support_for_sc:{}, remote_support_for_sc:{} "
+ "-> fail pairing",
logbool(local_supports_sc).c_str(),
logbool(p_dev_rec->SupportsSecureConnections()).c_str());
err_code = HCI_ERR_PAIRING_NOT_ALLOWED;
@@ -2582,8 +2606,8 @@
/* At this moment we know that both sides are SC capable, device in */
/* SC only mode requires MITM for any service so let's set MITM bit */
evt_data.auth_req |= BTM_AUTH_YN_BIT;
- LOG_VERBOSE("for device in \"SC only\" mode set auth_req to 0x%02x",
- evt_data.auth_req);
+ log::verbose("for device in \"SC only\" mode set auth_req to 0x{:02x}",
+ evt_data.auth_req);
}
/* if the user does not indicate "reply later" by setting the oob_data to
@@ -2593,9 +2617,9 @@
btm_sec_cb.devcb.loc_auth_req = evt_data.auth_req;
btm_sec_cb.devcb.loc_io_caps = evt_data.io_cap;
- LOG_VERBOSE("State: %s IO_CAP:%d oob_data:%d auth_req:%d",
- tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
- evt_data.io_cap, evt_data.oob_data, evt_data.auth_req);
+ log::verbose("State: {} IO_CAP:{} oob_data:{} auth_req:{}",
+ tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
+ evt_data.io_cap, evt_data.oob_data, evt_data.auth_req);
btsnd_hcic_io_cap_req_reply(evt_data.bd_addr, evt_data.io_cap,
evt_data.oob_data, evt_data.auth_req);
@@ -2674,9 +2698,9 @@
tBTM_SEC_DEV_REC* p_dev_rec;
p_bda = bda;
- LOG_DEBUG("BDA:%s, event:%s, state:%s", ADDRESS_TO_LOGGABLE_CSTR(p_bda),
- sp_evt_to_text(event).c_str(),
- tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state));
+ log::debug("BDA:{}, event:{}, state:{}", ADDRESS_TO_LOGGABLE_CSTR(p_bda),
+ sp_evt_to_text(event).c_str(),
+ tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state));
p_dev_rec = btm_find_dev(p_bda);
if ((p_dev_rec != NULL) &&
@@ -2695,16 +2719,16 @@
/* The device record must be allocated in the "IO cap exchange" step */
evt_data.cfm_req.num_val = value;
- LOG_VERBOSE("num_val:%u", evt_data.cfm_req.num_val);
+ log::verbose("num_val:{}", evt_data.cfm_req.num_val);
evt_data.cfm_req.just_works = true;
/* process user confirm req in association with the auth_req param */
if (btm_sec_cb.devcb.loc_io_caps == BTM_IO_CAP_IO) {
if (p_dev_rec->sec_rec.rmt_io_caps == BTM_IO_CAP_UNKNOWN) {
- LOG_ERROR(
- "did not receive IO cap response prior"
- " to BTM_SP_CFM_REQ_EVT, failing pairing request");
+ log::error(
+ "did not receive IO cap response prior to BTM_SP_CFM_REQ_EVT, "
+ "failing pairing request");
status = BTM_WRONG_MODE;
BTM_ConfirmReqReply(status, p_bda);
return;
@@ -2723,11 +2747,11 @@
}
}
- LOG_VERBOSE("just_works:%d, io loc:%d, rmt:%d, auth loc:%d, rmt:%d",
- evt_data.cfm_req.just_works, btm_sec_cb.devcb.loc_io_caps,
- p_dev_rec->sec_rec.rmt_io_caps,
- btm_sec_cb.devcb.loc_auth_req,
- p_dev_rec->sec_rec.rmt_auth_req);
+ log::verbose("just_works:{}, io loc:{}, rmt:{}, auth loc:{}, rmt:{}",
+ evt_data.cfm_req.just_works, btm_sec_cb.devcb.loc_io_caps,
+ p_dev_rec->sec_rec.rmt_io_caps,
+ btm_sec_cb.devcb.loc_auth_req,
+ p_dev_rec->sec_rec.rmt_auth_req);
evt_data.cfm_req.loc_auth_req = btm_sec_cb.devcb.loc_auth_req;
evt_data.cfm_req.rmt_auth_req = p_dev_rec->sec_rec.rmt_auth_req;
@@ -2738,7 +2762,7 @@
case BTM_SP_KEY_NOTIF_EVT:
/* Passkey notification (other side is a keyboard) */
evt_data.key_notif.passkey = value;
- LOG_VERBOSE("passkey:%u", evt_data.key_notif.passkey);
+ log::verbose("passkey:{}", evt_data.key_notif.passkey);
btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
break;
@@ -2750,7 +2774,7 @@
}
break;
default:
- LOG_WARN("unhandled event:%s", sp_evt_to_text(event).c_str());
+ log::warn("unhandled event:{}", sp_evt_to_text(event).c_str());
break;
}
@@ -2767,7 +2791,7 @@
}
if (event == BTM_SP_CFM_REQ_EVT) {
- LOG_VERBOSE("calling BTM_ConfirmReqReply with status: %d", status);
+ log::verbose("calling BTM_ConfirmReqReply with status: {}", status);
BTM_ConfirmReqReply(status, p_bda);
} else if (btm_sec_cb.devcb.loc_io_caps != BTM_IO_CAP_NONE &&
event == BTM_SP_KEY_REQ_EVT) {
@@ -2816,12 +2840,12 @@
p_dev_rec = btm_find_dev(bd_addr);
if (p_dev_rec == NULL) {
- LOG_ERROR("unknown BDA: %s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::error("unknown BDA: {}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return;
}
- LOG_VERBOSE(
- "btm_simple_pair_complete() Pair State: %s Status:%d sec_state: %u",
+ log::verbose(
+ "btm_simple_pair_complete() Pair State: {} Status:{} sec_state: {}",
tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), status,
p_dev_rec->sec_rec.sec_state);
@@ -2878,7 +2902,7 @@
evt_data.bd_addr = bd_addr;
RawAddress& p_bda = evt_data.bd_addr;
- LOG_VERBOSE("BDA: %s", ADDRESS_TO_LOGGABLE_CSTR(p_bda));
+ log::verbose("BDA: {}", ADDRESS_TO_LOGGABLE_CSTR(p_bda));
p_dev_rec = btm_find_dev(p_bda);
if ((p_dev_rec != NULL) && btm_sec_cb.api.p_sp_callback) {
evt_data.bd_addr = p_dev_rec->bd_addr;
@@ -2911,7 +2935,7 @@
*
******************************************************************************/
void btm_read_local_oob_complete(const tBTM_SP_LOC_OOB evt_data) {
- LOG_VERBOSE("btm_read_local_oob_complete:%d", evt_data.status);
+ log::verbose("btm_read_local_oob_complete:{}", evt_data.status);
if (btm_sec_cb.api.p_sp_callback) {
tBTM_SP_EVT_DATA btm_sp_evt_data;
@@ -2947,8 +2971,8 @@
p_dev_rec = btm_find_dev_by_handle(handle);
if (p_dev_rec != NULL) {
- LOG_VERBOSE("btm_sec_auth_collision: state %d (retrying in a moment...)",
- p_dev_rec->sec_rec.sec_state);
+ log::verbose("btm_sec_auth_collision: state {} (retrying in a moment...)",
+ p_dev_rec->sec_rec.sec_state);
/* We will restart authentication after timeout */
if (p_dev_rec->sec_rec.sec_state == BTM_SEC_STATE_AUTHENTICATING ||
p_dev_rec->sec_rec.is_security_state_bredr_encrypting())
@@ -2990,8 +3014,8 @@
btm_restore_mode();
p_dev_rec->sm4 |= BTM_SM4_RETRY;
p_dev_rec->sec_rec.sec_flags &= ~BTM_SEC_LINK_KEY_KNOWN;
- LOG_VERBOSE("Retry for missing key sm4:x%x sec_flags:0x%x", p_dev_rec->sm4,
- p_dev_rec->sec_rec.sec_flags);
+ log::verbose("Retry for missing key sm4:x{:x} sec_flags:0x{:x}",
+ p_dev_rec->sm4, p_dev_rec->sec_rec.sec_flags);
/* With BRCM controller, we do not need to delete the stored link key in
controller.
@@ -3012,16 +3036,17 @@
bool was_authenticating = false;
if (p_dev_rec) {
- LOG_VERBOSE(
- "Security Manager: in state: %s, handle: %d, status: %d, "
- "dev->sec_rec.sec_state:%d, bda: %s, RName: %s",
+ log::verbose(
+ "Security Manager: in state: {}, handle: {}, status: {}, "
+ "dev->sec_rec.sec_state:{}, bda: {}, RName: {}",
tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), handle,
status, p_dev_rec->sec_rec.sec_state,
- ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr), p_dev_rec->sec_bd_name);
+ ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr),
+ reinterpret_cast<char const*>(p_dev_rec->sec_bd_name));
} else {
- LOG_VERBOSE("Security Manager: in state: %s, handle: %d, status: %d",
- tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
- handle, status);
+ log::verbose("Security Manager: in state: {}, handle: {}, status: {}",
+ tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
+ handle, status);
}
/* For transaction collision we need to wait and repeat. There is no need */
@@ -3119,7 +3144,7 @@
BTM_BLE_SEC_NONE);
} else if (p_dev_rec->IsLocallyInitiated()) {
// Encryption will be set in role_changed callback
- LOG_INFO(
+ log::info(
"auth completed in role=peripheral, try to switch role and "
"encrypt");
BTM_SwitchRoleToCentral(p_dev_rec->RemoteAddress());
@@ -3176,8 +3201,8 @@
/* for random timeout because only peripheral should receive the result */
if ((status == HCI_ERR_LMP_ERR_TRANS_COLLISION) ||
(status == HCI_ERR_DIFF_TRANSACTION_COLLISION)) {
- LOG_ERROR("Encryption collision failed status:%s",
- hci_error_code_text(status).c_str());
+ log::error("Encryption collision failed status:{}",
+ hci_error_code_text(status).c_str());
btm_sec_auth_collision(handle);
return;
}
@@ -3185,9 +3210,9 @@
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
if (p_dev_rec == nullptr) {
- LOG_WARN(
- "Received encryption change for unknown device handle:0x%04x status:%s "
- "enable:0x%x",
+ log::warn(
+ "Received encryption change for unknown device handle:0x{:04x} "
+ "status:{} enable:0x{:x}",
handle, hci_status_code_text(status).c_str(), encr_enable);
return;
}
@@ -3195,9 +3220,9 @@
const tBT_TRANSPORT transport =
BTM_IsBleConnection(handle) ? BT_TRANSPORT_LE : BT_TRANSPORT_BR_EDR;
- LOG_DEBUG(
- "Security Manager encryption change request hci_status:%s"
- " request:%s state:%s sec_flags:0x%x",
+ log::debug(
+ "Security Manager encryption change request hci_status:{} request:{} "
+ "state:{} sec_flags:0x{:x}",
hci_status_code_text(status).c_str(),
(encr_enable) ? "encrypt" : "unencrypt",
(p_dev_rec->sec_rec.sec_state) ? "encrypted" : "unencrypted",
@@ -3219,13 +3244,14 @@
p_dev_rec->sec_rec.set_le_device_authenticated();
}
} else {
- LOG_ERROR(
- "Received encryption change for unknown device handle:0x%04x "
- "status:%s enable:0x%x",
+ log::error(
+ "Received encryption change for unknown device handle:0x{:04x} "
+ "status:{} enable:0x{:x}",
handle, hci_status_code_text(status).c_str(), encr_enable);
}
} else {
- LOG_INFO("Encryption was not enabled locally resetting encryption state");
+ log::info(
+ "Encryption was not enabled locally resetting encryption state");
/* It is possible that we decrypted the link to perform role switch */
/* mark link not to be encrypted, so that when we execute security next
* time it will kick in again */
@@ -3234,9 +3260,9 @@
} else if (p_dev_rec->ble_hci_handle == handle) { // BLE
p_dev_rec->sec_rec.sec_flags &= ~BTM_SEC_LE_ENCRYPTED;
} else {
- LOG_ERROR(
- "Received encryption change for unknown device handle:0x%04x "
- "status:%s enable:0x%x",
+ log::error(
+ "Received encryption change for unknown device handle:0x{:04x} "
+ "status:{} enable:0x{:x}",
handle, hci_status_code_text(status).c_str(), encr_enable);
}
}
@@ -3254,8 +3280,8 @@
bt_transport_text(transport).c_str(),
is_encrypted ? 'T' : 'F'));
- LOG_DEBUG("after update p_dev_rec->sec_rec.sec_flags=0x%x",
- p_dev_rec->sec_rec.sec_flags);
+ log::debug("after update p_dev_rec->sec_rec.sec_flags=0x{:x}",
+ p_dev_rec->sec_rec.sec_flags);
btm_sec_check_pending_enc_req(p_dev_rec, transport, encr_enable);
@@ -3269,7 +3295,7 @@
btm_ble_link_encrypted(p_dev_rec->ble.pseudo_addr, encr_enable);
if (status == HCI_ERR_KEY_MISSING) {
- LOG_INFO("Remote key missing - will report");
+ log::info("Remote key missing - will report");
bta_dm_remote_key_missing(p_dev_rec->ble.pseudo_addr);
return;
}
@@ -3280,8 +3306,8 @@
p_dev_rec->sec_rec.enc_key_size = 16;
}
- LOG_DEBUG("in new_encr_key_256 is %d",
- p_dev_rec->sec_rec.new_encryption_key_is_p256);
+ log::debug("in new_encr_key_256 is {}",
+ p_dev_rec->sec_rec.new_encryption_key_is_p256);
if ((status == HCI_SUCCESS) && encr_enable &&
(p_dev_rec->hci_handle == handle)) {
@@ -3290,7 +3316,7 @@
if (p_dev_rec->sec_rec.rmt_auth_req == BTM_AUTH_SP_NO &&
btm_sec_cb.devcb.loc_auth_req == BTM_AUTH_SP_NO) {
derive_ltk = false;
- LOG_VERBOSE("BR key is temporary, skip derivation of LE LTK");
+ log::verbose("BR key is temporary, skip derivation of LE LTK");
}
tHCI_ROLE role = HCI_ROLE_UNKNOWN;
BTM_GetRole(p_dev_rec->bd_addr, &role);
@@ -3305,7 +3331,7 @@
/* BR/EDR is encrypted with LK that can be used to derive LE LTK */
p_dev_rec->sec_rec.new_encryption_key_is_p256 = false;
- LOG_VERBOSE("start SM over BR/EDR");
+ log::verbose("start SM over BR/EDR");
SMP_BR_PairWith(p_dev_rec->bd_addr);
}
}
@@ -3315,8 +3341,9 @@
if (!p_dev_rec->sec_rec.is_security_state_bredr_encrypting()) {
if (BTM_SEC_STATE_DELAY_FOR_ENC == p_dev_rec->sec_rec.sec_state) {
p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_IDLE;
- LOG_VERBOSE("clearing callback. p_dev_rec=%p, p_callback=%p", p_dev_rec,
- p_dev_rec->sec_rec.p_callback);
+ log::verbose("clearing callback. p_dev_rec={}, p_callback={}",
+ fmt::ptr(p_dev_rec),
+ fmt::ptr(p_dev_rec->sec_rec.p_callback));
p_dev_rec->sec_rec.p_callback = NULL;
l2cu_resubmit_pending_sec_req(&p_dev_rec->bd_addr);
return;
@@ -3354,12 +3381,12 @@
/* If remote device stop the encryption before we call "Read Encryption Key
* Size", we might receive Insufficient Security, which means that link is
* no longer encrypted. */
- LOG_INFO("encryption stopped on link:0x%x", handle);
+ log::info("encryption stopped on link:0x{:x}", handle);
return;
}
if (status != HCI_SUCCESS) {
- LOG_ERROR("disconnecting, status:0x%x", status);
+ log::error("disconnecting, status:0x{:x}", status);
acl_disconnect_from_handle(handle, HCI_ERR_PEER_USER,
"stack::btu::btu_hcif::read_encryption_key_size_"
"complete_after_encryption_change Bad key size");
@@ -3367,8 +3394,8 @@
}
if (key_size < MIN_KEY_SIZE) {
- LOG_ERROR(
- "encryption key too short, disconnecting. handle:0x%x,key_size:%d",
+ log::error(
+ "encryption key too short, disconnecting. handle:0x{:x},key_size:{}",
handle, key_size);
acl_disconnect_from_handle(
@@ -3434,11 +3461,11 @@
static void btm_sec_connect_after_reject_timeout(void* /* data */) {
tBTM_SEC_DEV_REC* p_dev_rec = btm_sec_cb.p_collided_dev_rec;
- LOG_VERBOSE("restarting ACL connection");
+ log::verbose("restarting ACL connection");
btm_sec_cb.p_collided_dev_rec = 0;
if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED) {
- LOG_WARN("Security Manager: failed to start connection");
+ log::warn("Security Manager: failed to start connection");
btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
@@ -3466,38 +3493,41 @@
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bda);
if (!p_dev_rec) {
- LOG_DEBUG(
- "Connected to new device state:%s handle:0x%04x status:%s "
- "enc_mode:%hhu bda:%s",
+ log::debug(
+ "Connected to new device state:{} handle:0x{:04x} status:{} "
+ "enc_mode:{} bda:{}",
tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), handle,
hci_status_code_text(status).c_str(), enc_mode,
ADDRESS_TO_LOGGABLE_CSTR(bda));
if (status == HCI_SUCCESS) {
p_dev_rec = btm_sec_alloc_dev(bda);
- LOG_DEBUG("Allocated new device record for new connection peer:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bda));
+ log::debug("Allocated new device record for new connection peer:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bda));
} else {
/* If the device matches with stored paring address
* reset the paring state to idle */
if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
btm_sec_cb.pairing_bda == bda) {
- LOG_WARN("Connection failed during bonding attempt peer:%s reason:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bda), hci_error_code_text(status).c_str());
+ log::warn("Connection failed during bonding attempt peer:{} reason:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bda),
+ hci_error_code_text(status).c_str());
btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
}
- LOG_DEBUG("Ignoring failed device connection peer:%s reason:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bda), hci_error_code_text(status).c_str());
+ log::debug("Ignoring failed device connection peer:{} reason:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bda),
+ hci_error_code_text(status).c_str());
return;
}
} else {
- LOG_DEBUG(
- "Connected to known device state:%s handle:0x%04x status:%s "
- "enc_mode:%hhu bda:%s RName:%s",
+ log::debug(
+ "Connected to known device state:{} handle:0x{:04x} status:{} "
+ "enc_mode:{} bda:{} RName:{}",
tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state), handle,
hci_status_code_text(status).c_str(), enc_mode,
- ADDRESS_TO_LOGGABLE_CSTR(bda), p_dev_rec->sec_bd_name);
+ ADDRESS_TO_LOGGABLE_CSTR(bda),
+ reinterpret_cast<char const*>(p_dev_rec->sec_bd_name));
bit_shift = (handle == p_dev_rec->ble_hci_handle) ? 8 : 0;
/* Update the timestamp for this device */
@@ -3511,9 +3541,8 @@
/* Motorola S9 disconnects without asking pin code */
if ((status != HCI_SUCCESS) &&
(btm_sec_cb.pairing_state == BTM_PAIR_STATE_WAIT_PIN_REQ)) {
- LOG_WARN(
- "Security Manager: btm_sec_connected: incoming connection "
- "failed "
+ log::warn(
+ "Security Manager: btm_sec_connected: incoming connection failed "
"without asking PIN");
p_dev_rec->sm4 &= ~BTM_SM4_CONN_PEND;
@@ -3532,7 +3561,7 @@
if (BTM_ReadRemoteDeviceName(p_dev_rec->bd_addr, NULL,
BT_TRANSPORT_BR_EDR) !=
BTM_CMD_STARTED) {
- LOG_ERROR("cannot read remote name");
+ log::error("cannot read remote name");
btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
}
}
@@ -3555,9 +3584,9 @@
/* if we rejected incoming connection from bonding device */
if ((status == HCI_ERR_HOST_REJECT_DEVICE) &&
(btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT)) {
- LOG_WARN(
- "Security Manager: btm_sec_connected: HCI_Conn_Comp Flags:0x%04x, "
- "sm4: 0x%x",
+ log::warn(
+ "Security Manager: btm_sec_connected: HCI_Conn_Comp Flags:0x{:04x}, "
+ "sm4: 0x{:x}",
btm_sec_cb.pairing_flags, p_dev_rec->sm4);
btm_sec_cb.pairing_flags &= ~BTM_PAIR_FLAGS_REJECTED_CONNECT;
@@ -3566,7 +3595,7 @@
btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_GET_REM_NAME);
if (BTM_ReadRemoteDeviceName(bda, NULL, BT_TRANSPORT_BR_EDR) !=
BTM_CMD_STARTED) {
- LOG_ERROR("cannot read remote name");
+ log::error("cannot read remote name");
btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
}
return;
@@ -3585,7 +3614,7 @@
}
/* wait for incoming connection without resetting pairing state */
else if (status == HCI_ERR_CONNECTION_EXISTS) {
- LOG_WARN(
+ log::warn(
"Security Manager: btm_sec_connected: Wait for incoming connection");
return;
}
@@ -3603,8 +3632,8 @@
p_dev_rec->sec_rec.security_required &= ~BTM_SEC_OUT_AUTHENTICATE;
p_dev_rec->sec_rec.sec_flags &=
~((BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LINK_KEY_AUTHED) << bit_shift);
- LOG_VERBOSE("security_required:%x ",
- p_dev_rec->sec_rec.security_required);
+ log::verbose("security_required:{:x} ",
+ p_dev_rec->sec_rec.security_required);
btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
@@ -3645,9 +3674,9 @@
p_dev_rec = btm_find_dev(bda);
if (!p_dev_rec) {
/* Don't callback when device security record was removed */
- LOG_DEBUG(
- "device security record associated with this bda has been "
- "removed! bda=%s, do not callback",
+ log::debug(
+ "device security record associated with this bda has been removed! "
+ "bda={}, do not callback",
ADDRESS_TO_LOGGABLE_CSTR(bda));
return;
}
@@ -3686,8 +3715,8 @@
/* Let l2cap start bond timer */
l2cu_update_lcb_4_bonding(p_dev_rec->bd_addr, true);
}
- LOG_INFO("Connection complete during pairing process peer:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bda));
+ log::info("Connection complete during pairing process peer:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bda));
BTM_LogHistory(kBtmLogTag, bda, "Dedicated bonding",
base::StringPrintf("Initiated:%c pairing_flag:0x%02x",
(is_pair_flags_we_started_dd) ? 'T' : 'F',
@@ -3728,8 +3757,8 @@
/* After connection is established we perform security if we do not know */
/* the name, or if we are originator because some procedure can have */
/* been scheduled while connection was down */
- LOG_DEBUG("Is connection locally initiated:%s",
- logbool(p_dev_rec->is_originator).c_str());
+ log::debug("Is connection locally initiated:{}",
+ logbool(p_dev_rec->is_originator).c_str());
if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_NAME_KNOWN) ||
p_dev_rec->is_originator) {
res = btm_sec_execute_procedure(p_dev_rec);
@@ -3767,13 +3796,14 @@
std::string comment) {
if ((reason != HCI_ERR_CONN_CAUSE_LOCAL_HOST) &&
(reason != HCI_ERR_PEER_USER) && (reason != HCI_ERR_REMOTE_POWER_OFF)) {
- LOG_WARN("Got uncommon disconnection reason:%s handle:0x%04x comment:%s",
- hci_error_code_text(reason).c_str(), handle, comment.c_str());
+ log::warn("Got uncommon disconnection reason:{} handle:0x{:04x} comment:{}",
+ hci_error_code_text(reason).c_str(), handle, comment.c_str());
}
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
if (p_dev_rec == nullptr) {
- LOG_WARN("Got disconnect for unknown device record handle:0x%04x", handle);
+ log::warn("Got disconnect for unknown device record handle:0x{:04x}",
+ handle);
return;
}
@@ -3788,8 +3818,8 @@
const uint8_t old_pairing_flags = btm_sec_cb.pairing_flags;
if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_IDLE) &&
(btm_sec_cb.pairing_bda == p_dev_rec->bd_addr)) {
- LOG_DEBUG("Disconnected while pairing process active handle:0x%04x",
- handle);
+ log::debug("Disconnected while pairing process active handle:0x{:04x}",
+ handle);
btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
p_dev_rec->sec_rec.sec_flags &= ~BTM_SEC_LINK_KEY_KNOWN;
@@ -3813,14 +3843,16 @@
if (p_dev_rec == nullptr) {
// |btm_sec_cb.api.p_auth_complete_callback| may cause |p_dev_rec| to be
// deallocated.
- LOG_WARN("Device record was deallocated after user callback");
+ log::warn("Device record was deallocated after user callback");
return;
}
}
- LOG_DEBUG(
- "Disconnection complete device:%s name:%s state:%s reason:%s sec_req:%x",
- ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr), p_dev_rec->sec_bd_name,
+ log::debug(
+ "Disconnection complete device:{} name:{} state:{} reason:{} "
+ "sec_req:{:x}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr),
+ reinterpret_cast<char const*>(p_dev_rec->sec_bd_name),
tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state),
hci_reason_code_text(reason).c_str(),
p_dev_rec->sec_rec.security_required);
@@ -3858,16 +3890,16 @@
* disconnection.
*/
if (is_sample_ltk(p_dev_rec->sec_rec.ble_keys.pltk)) {
- LOG_INFO("removing bond to device that used sample LTK: %s",
- ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr));
+ log::info("removing bond to device that used sample LTK: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr));
bta_dm_remove_device(p_dev_rec->bd_addr);
return;
}
if (p_dev_rec->sec_rec.sec_state == BTM_SEC_STATE_DISCONNECTING_BOTH) {
- LOG_DEBUG("Waiting for other transport to disconnect current:%s",
- bt_transport_text(transport).c_str());
+ log::debug("Waiting for other transport to disconnect current:{}",
+ bt_transport_text(transport).c_str());
p_dev_rec->sec_rec.sec_state = (transport == BT_TRANSPORT_LE)
? BTM_SEC_STATE_DISCONNECTING
: BTM_SEC_STATE_DISCONNECTING_BLE;
@@ -3883,9 +3915,9 @@
p_dev_rec->sec_rec.p_callback = nullptr;
(*p_callback)(&p_dev_rec->bd_addr, transport, p_dev_rec->sec_rec.p_ref_data,
BTM_ERR_PROCESSING);
- LOG_DEBUG("Cleaned up pending security state device:%s transport:%s",
- ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr),
- bt_transport_text(transport).c_str());
+ log::debug("Cleaned up pending security state device:{} transport:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr),
+ bt_transport_text(transport).c_str());
}
}
@@ -3909,20 +3941,20 @@
/* If remote device stop the encryption before we call "Read Encryption Key
* Size", we might receive Insufficient Security, which means that link is
* no longer encrypted. */
- LOG_INFO("encryption stopped on link: 0x%x ", handle);
+ log::info("encryption stopped on link: 0x{:x} ", handle);
return;
}
if (status != HCI_SUCCESS) {
- LOG_INFO("disconnecting, status: 0x%x", status);
+ log::info("disconnecting, status: 0x{:x}", status);
acl_disconnect_from_handle(handle, HCI_ERR_PEER_USER,
"stack::btu_hcif Key size fail");
return;
}
if (key_size < MIN_KEY_SIZE) {
- LOG_ERROR(
- "encryption key too short, disconnecting. handle: 0x%x key_size %d",
+ log::error(
+ "encryption key too short, disconnecting. handle: 0x{:x} key_size {}",
handle, key_size);
acl_disconnect_from_handle(handle, HCI_ERR_HOST_REJECT_SECURITY,
@@ -3956,8 +3988,8 @@
bool we_are_bonding = false;
bool ltk_derived_lk = false;
- LOG_DEBUG("New link key generated device:%s key_type:%hhu",
- ADDRESS_TO_LOGGABLE_CSTR(p_bda), key_type);
+ log::debug("New link key generated device:{} key_type:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_bda), key_type);
if ((key_type >= BTM_LTK_DERIVED_LKEY_OFFSET + BTM_LKEY_TYPE_COMBINATION) &&
(key_type <=
@@ -3999,8 +4031,8 @@
/* save LTK derived LK no matter what */
if (ltk_derived_lk) {
if (btm_sec_cb.api.p_link_key_callback) {
- LOG_VERBOSE("Save LTK derived LK (key_type = %d)",
- p_dev_rec->sec_rec.link_key_type);
+ log::verbose("Save LTK derived LK (key_type = {})",
+ p_dev_rec->sec_rec.link_key_type);
(*btm_sec_cb.api.p_link_key_callback)(
p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, link_key,
p_dev_rec->sec_rec.link_key_type, true /* is_ctkd */);
@@ -4009,8 +4041,8 @@
if ((p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_UNAUTH_COMB_P_256) ||
(p_dev_rec->sec_rec.link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256)) {
p_dev_rec->sec_rec.new_encryption_key_is_p256 = true;
- LOG_VERBOSE("set new_encr_key_256 to %d",
- p_dev_rec->sec_rec.new_encryption_key_is_p256);
+ log::verbose("set new_encr_key_256 to {}",
+ p_dev_rec->sec_rec.new_encryption_key_is_p256);
}
}
@@ -4022,8 +4054,8 @@
((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) !=
BTM_COD_MAJOR_PERIPHERAL)) &&
!ltk_derived_lk) {
- LOG_VERBOSE("Delayed BDA: %s, Type: %d", ADDRESS_TO_LOGGABLE_CSTR(p_bda),
- key_type);
+ log::verbose("Delayed BDA: {}, Type: {}", ADDRESS_TO_LOGGABLE_CSTR(p_bda),
+ key_type);
p_dev_rec->sec_rec.link_key_not_sent = true;
@@ -4033,9 +4065,9 @@
SendRemoteNameRequest(p_bda);
}
- LOG_VERBOSE("rmt_io_caps:%d, sec_flags:x%x, dev_class[1]:x%02x",
- p_dev_rec->sec_rec.rmt_io_caps, p_dev_rec->sec_rec.sec_flags,
- p_dev_rec->dev_class[1]);
+ log::verbose("rmt_io_caps:{}, sec_flags:x{:x}, dev_class[1]:x{:02x}",
+ p_dev_rec->sec_rec.rmt_io_caps, p_dev_rec->sec_rec.sec_flags,
+ p_dev_rec->dev_class[1]);
return;
}
@@ -4047,9 +4079,9 @@
{
if (btm_sec_cb.api.p_link_key_callback) {
if (ltk_derived_lk) {
- LOG_VERBOSE(
- "btm_sec_link_key_notification() LTK derived LK is saved already"
- " (key_type = %d)",
+ log::verbose(
+ "btm_sec_link_key_notification() LTK derived LK is saved already "
+ "(key_type = {})",
p_dev_rec->sec_rec.link_key_type);
} else {
(*btm_sec_cb.api.p_link_key_callback)(
@@ -4072,7 +4104,7 @@
void btm_sec_link_key_request(const RawAddress bda) {
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_or_alloc_dev(bda);
- LOG_VERBOSE("bda: %s", ADDRESS_TO_LOGGABLE_CSTR(bda));
+ log::verbose("bda: {}", ADDRESS_TO_LOGGABLE_CSTR(bda));
if (!concurrentPeerAuthIsEnabled()) {
p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_AUTHENTICATING;
}
@@ -4080,9 +4112,9 @@
if ((btm_sec_cb.pairing_state == BTM_PAIR_STATE_WAIT_PIN_REQ) &&
(btm_sec_cb.collision_start_time != 0) &&
(btm_sec_cb.p_collided_dev_rec->bd_addr == bda)) {
- LOG_VERBOSE(
- "btm_sec_link_key_request() rejecting link key req "
- "State: %d START_TIMEOUT : %" PRIu64,
+ log::verbose(
+ "btm_sec_link_key_request() rejecting link key req State: {} "
+ "START_TIMEOUT : {}",
btm_sec_cb.pairing_state, btm_sec_cb.collision_start_time);
btsnd_hcic_link_key_neg_reply(bda);
return;
@@ -4119,9 +4151,9 @@
p_dev_rec = btm_find_dev(p_cb->pairing_bda);
- LOG_VERBOSE("State: %s Flags: %u",
- tBTM_SEC_CB::btm_pair_state_descr(p_cb->pairing_state),
- p_cb->pairing_flags);
+ log::verbose("State: {} Flags: {}",
+ tBTM_SEC_CB::btm_pair_state_descr(p_cb->pairing_state),
+ p_cb->pairing_flags);
switch (p_cb->pairing_state) {
case BTM_PAIR_STATE_WAIT_PIN_REQ:
@@ -4174,8 +4206,8 @@
* complete.
* now it's time to tear down the ACL link*/
if (p_dev_rec == NULL) {
- LOG_ERROR("BTM_PAIR_STATE_WAIT_DISCONNECT unknown BDA: %s",
- ADDRESS_TO_LOGGABLE_CSTR(p_cb->pairing_bda));
+ log::error("BTM_PAIR_STATE_WAIT_DISCONNECT unknown BDA: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_cb->pairing_bda));
break;
}
btm_sec_send_hci_disconnect(
@@ -4201,8 +4233,8 @@
break;
default:
- LOG_WARN("not processed state: %s",
- tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state));
+ log::warn("not processed state: {}",
+ tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state));
btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_IDLE);
break;
}
@@ -4225,9 +4257,9 @@
/* it may need to stretch timeouts */
l2c_pin_code_request(p_bda);
- LOG_DEBUG("Controller requests PIN code device:%s state:%s",
- ADDRESS_TO_LOGGABLE_CSTR(p_bda),
- tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state));
+ log::debug("Controller requests PIN code device:{} state:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_bda),
+ tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state));
RawAddress local_bd_addr = *controller_get_interface()->get_address();
if (p_bda == local_bd_addr) {
@@ -4242,8 +4274,8 @@
return;
} else if ((btm_sec_cb.pairing_state != BTM_PAIR_STATE_WAIT_PIN_REQ) ||
p_bda != btm_sec_cb.pairing_bda) {
- LOG_WARN("btm_sec_pin_code_request() rejected - state: %s",
- tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state));
+ log::warn("btm_sec_pin_code_request() rejected - state: {}",
+ tBTM_SEC_CB::btm_pair_state_descr(btm_sec_cb.pairing_state));
btsnd_hcic_pin_code_neg_reply(p_bda);
return;
}
@@ -4260,7 +4292,7 @@
}
if (!p_cb->pairing_disabled && (p_cb->cfg.pin_type == HCI_PIN_TYPE_FIXED)) {
- LOG_VERBOSE("btm_sec_pin_code_request fixed pin replying");
+ log::verbose("btm_sec_pin_code_request fixed pin replying");
btm_sec_cb.change_pairing_state(BTM_PAIR_STATE_WAIT_AUTH_COMPLETE);
btsnd_hcic_pin_code_req_reply(p_bda, p_cb->cfg.pin_code_len,
p_cb->cfg.pin_code);
@@ -4275,7 +4307,7 @@
/* We could have started connection after asking user for the PIN code */
if (btm_sec_cb.pin_code_len != 0) {
- LOG_VERBOSE("btm_sec_pin_code_request bonding sending reply");
+ log::verbose("btm_sec_pin_code_request bonding sending reply");
btsnd_hcic_pin_code_req_reply(p_bda, btm_sec_cb.pin_code_len,
p_cb->pin_code);
@@ -4305,10 +4337,11 @@
((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))) {
- LOG_WARN(
- "btm_sec_pin_code_request(): Pairing disabled:%d; PIN callback:%p, Dev "
- "Rec:%p!",
- p_cb->pairing_disabled, p_cb->api.p_pin_callback, p_dev_rec);
+ 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);
}
@@ -4326,7 +4359,7 @@
/* Also cannot send remote name request while paging, i.e. connection is not
* completed */
if (p_dev_rec->sec_rec.sec_flags & BTM_SEC_NAME_KNOWN) {
- LOG_VERBOSE("btm_sec_pin_code_request going for callback");
+ log::verbose("btm_sec_pin_code_request going for callback");
btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
if (p_cb->api.p_pin_callback) {
@@ -4336,7 +4369,7 @@
BTM_SEC_IN_MIN_16_DIGIT_PIN));
}
} else {
- LOG_VERBOSE("btm_sec_pin_code_request going for remote name");
+ log::verbose("btm_sec_pin_code_request going for remote name");
/* We received PIN code request for the device with unknown name */
/* it is not user friendly just to ask for the PIN without name */
@@ -4398,8 +4431,8 @@
******************************************************************************/
tBTM_STATUS btm_sec_execute_procedure(tBTM_SEC_DEV_REC* p_dev_rec) {
CHECK(p_dev_rec != nullptr);
- LOG_DEBUG(
- "security_required:0x%x security_flags:0x%x security_state:%s[%hhu]",
+ log::debug(
+ "security_required:0x{:x} security_flags:0x{:x} security_state:{}[{}]",
p_dev_rec->sec_rec.security_required, p_dev_rec->sec_rec.sec_flags,
security_state_text(
static_cast<tSECURITY_STATE>(p_dev_rec->sec_rec.sec_state))
@@ -4408,17 +4441,17 @@
if (p_dev_rec->sec_rec.sec_state != BTM_SEC_STATE_IDLE &&
p_dev_rec->sec_rec.sec_state != BTM_SEC_STATE_LE_ENCRYPTING) {
- LOG_INFO("No immediate action taken in busy state: %s",
- security_state_text(p_dev_rec->sec_rec.sec_state).c_str());
+ log::info("No immediate action taken in busy state: {}",
+ security_state_text(p_dev_rec->sec_rec.sec_state).c_str());
return (BTM_CMD_STARTED);
}
/* If any security is required, get the name first */
if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_NAME_KNOWN) &&
(p_dev_rec->hci_handle != HCI_INVALID_HANDLE)) {
- LOG_DEBUG("Security Manager: Start get name");
+ log::debug("Security Manager: Start get name");
if (!btm_sec_start_get_name(p_dev_rec)) {
- LOG_WARN("Unable to start remote name request");
+ log::warn("Unable to start remote name request");
return (BTM_NO_RESOURCES);
}
return (BTM_CMD_STARTED);
@@ -4434,13 +4467,13 @@
if (p_dev_rec->IsLocallyInitiated()) {
if (p_dev_rec->sec_rec.security_required &
(BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) {
- LOG_DEBUG("Outgoing authentication/encryption Required");
+ log::debug("Outgoing authentication/encryption Required");
start_auth = true;
}
} else {
if (p_dev_rec->sec_rec.security_required &
(BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) {
- LOG_DEBUG("Incoming authentication/encryption Required");
+ log::debug("Incoming authentication/encryption Required");
start_auth = true;
}
}
@@ -4456,14 +4489,14 @@
if (!p_dev_rec->IsLocallyInitiated()) {
if (p_dev_rec->sec_rec.security_required &
BTM_SEC_IN_MIN_16_DIGIT_PIN) {
- LOG_DEBUG("BTM_SEC_IN_MIN_16_DIGIT_PIN Required");
+ log::debug("BTM_SEC_IN_MIN_16_DIGIT_PIN Required");
start_auth = true;
}
}
}
if (start_auth) {
- LOG_DEBUG("Security Manager: Start authentication");
+ log::debug("Security Manager: Start authentication");
/*
* If we do have a link-key, but we end up here because we need an
@@ -4499,20 +4532,20 @@
(!p_dev_rec->IsLocallyInitiated() &&
(p_dev_rec->sec_rec.security_required & BTM_SEC_IN_ENCRYPT))) &&
(p_dev_rec->hci_handle != HCI_INVALID_HANDLE)) {
- LOG_VERBOSE("Security Manager: Start encryption");
+ log::verbose("Security Manager: Start encryption");
btsnd_hcic_set_conn_encrypt(p_dev_rec->hci_handle, true);
p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_ENCRYPTING;
return (BTM_CMD_STARTED);
} else {
- LOG_DEBUG("Encryption not required");
+ log::debug("Encryption not required");
}
if ((p_dev_rec->sec_rec.security_required & BTM_SEC_MODE4_LEVEL4) &&
(p_dev_rec->sec_rec.link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256)) {
- LOG_VERBOSE(
- "Security Manager: SC only service, but link key type is 0x%02x -"
- "security failure",
+ log::verbose(
+ "Security Manager: SC only service, but link key type is 0x{:02x} "
+ "-security failure",
p_dev_rec->sec_rec.link_key_type);
return (BTM_FAILED_ON_SECURITY);
}
@@ -4520,7 +4553,8 @@
if (access_secure_service_from_temp_bond(
p_dev_rec, p_dev_rec->IsLocallyInitiated(),
p_dev_rec->sec_rec.security_required)) {
- LOG_ERROR("Trying to access a secure service from a temp bonding, rejecting");
+ log::error(
+ "Trying to access a secure service from a temp bonding, rejecting");
return (BTM_FAILED_ON_SECURITY);
}
@@ -4529,7 +4563,7 @@
~(BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_IN_AUTHENTICATE |
BTM_SEC_OUT_ENCRYPT | BTM_SEC_IN_ENCRYPT);
- LOG_VERBOSE("Security Manager: access granted");
+ log::verbose("Security Manager: access granted");
return (BTM_SUCCESS);
}
@@ -4577,7 +4611,7 @@
FROM_HERE, base::Bind(&btm_sec_auth_timer_timeout, addr),
std::chrono::milliseconds(delay_auth));
if (status != BT_STATUS_SUCCESS) {
- LOG_ERROR("do_in_main_thread_delayed failed. directly calling");
+ log::error("do_in_main_thread_delayed failed. directly calling");
btm_sec_auth_timer_timeout(addr);
}
}
@@ -4594,18 +4628,18 @@
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(*p_addr);
delete p_addr;
if (p_dev_rec == NULL) {
- LOG_INFO("invalid device or not found");
+ log::info("invalid device or not found");
} else if (btm_dev_authenticated(p_dev_rec)) {
- LOG_INFO("device is already authenticated");
+ log::info("device is already authenticated");
if (p_dev_rec->sec_rec.p_callback) {
(*p_dev_rec->sec_rec.p_callback)(&p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR,
p_dev_rec->sec_rec.p_ref_data,
BTM_SUCCESS);
}
} else if (p_dev_rec->sec_rec.sec_state == BTM_SEC_STATE_AUTHENTICATING) {
- LOG_INFO("device is in the process of authenticating");
+ log::info("device is in the process of authenticating");
} else {
- LOG_INFO("starting authentication");
+ log::info("starting authentication");
p_dev_rec->sec_rec.sec_state = BTM_SEC_STATE_AUTHENTICATING;
btsnd_hcic_auth_request(p_dev_rec->hci_handle);
}
@@ -4622,7 +4656,7 @@
*
******************************************************************************/
static void btm_sec_collision_timeout(void* /* data */) {
- LOG_VERBOSE("restaring security process after collision");
+ log::verbose("restaring security process after collision");
tBTM_STATUS status = btm_sec_execute_procedure(btm_sec_cb.p_collided_dev_rec);
@@ -4683,9 +4717,9 @@
void tBTM_SEC_CB::change_pairing_state(tBTM_PAIRING_STATE new_state) {
tBTM_PAIRING_STATE old_state = pairing_state;
- LOG_DEBUG("Pairing state changed %s => %s pairing_flags:0x%x",
- tBTM_SEC_CB::btm_pair_state_descr(pairing_state),
- tBTM_SEC_CB::btm_pair_state_descr(new_state), pairing_flags);
+ log::debug("Pairing state changed {} => {} pairing_flags:0x{:x}",
+ tBTM_SEC_CB::btm_pair_state_descr(pairing_state),
+ tBTM_SEC_CB::btm_pair_state_descr(new_state), pairing_flags);
if (pairing_state != new_state) {
BTM_LogHistory(
@@ -4769,8 +4803,8 @@
void btm_sec_dev_rec_cback_event(tBTM_SEC_DEV_REC* p_dev_rec,
tBTM_STATUS btm_status, bool is_le_transport) {
ASSERT(p_dev_rec != nullptr);
- LOG_DEBUG("transport=%s, btm_status=%s", is_le_transport ? "le" : "classic",
- btm_status_text(btm_status).c_str());
+ log::debug("transport={}, btm_status={}", is_le_transport ? "le" : "classic",
+ btm_status_text(btm_status).c_str());
tBTM_SEC_CALLBACK* p_callback = p_dev_rec->sec_rec.p_callback;
p_dev_rec->sec_rec.p_callback = NULL;
@@ -4820,8 +4854,8 @@
p_e->bd_addr = bd_addr;
p_e->rfcomm_security_requirement = security_required;
- LOG_VERBOSE("PSM: 0x%04x Is_Orig: %u security_required: 0x%x", psm, is_orig,
- security_required);
+ log::verbose("PSM: 0x{:04x} Is_Orig: {} security_required: 0x{:x}", psm,
+ is_orig, security_required);
fixed_queue_enqueue(btm_sec_cb.sec_pending_q, p_e);
@@ -4836,9 +4870,8 @@
if ((major == BTM_COD_MAJOR_AUDIO) &&
((minor == BTM_COD_MINOR_CONFM_HANDSFREE) ||
(minor == BTM_COD_MINOR_CAR_AUDIO))) {
- LOG_VERBOSE(
- "Skipping pre-fetch PIN for carkit COD Major: 0x%02x Minor: "
- "0x%02x",
+ log::verbose(
+ "Skipping pre-fetch PIN for carkit COD Major: 0x{:02x} Minor: 0x{:02x}",
major, minor);
if (!btm_sec_cb.security_mode_changed) {
@@ -4856,7 +4889,7 @@
/* pin was not supplied - pre-fetch pin code now */
if (btm_sec_cb.api.p_pin_callback &&
((btm_sec_cb.pairing_flags & BTM_PAIR_FLAGS_PIN_REQD) == 0)) {
- LOG_VERBOSE("PIN code callback called");
+ log::verbose("PIN code callback called");
if (BTM_IsAclConnectionUp(p_dev_rec->bd_addr, BT_TRANSPORT_BR_EDR))
btm_sec_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD;
(btm_sec_cb.api.p_pin_callback)(
@@ -4966,7 +4999,7 @@
*
******************************************************************************/
void btm_sec_clear_ble_keys(tBTM_SEC_DEV_REC* p_dev_rec) {
- LOG_VERBOSE("Clearing BLE Keys");
+ log::verbose("Clearing BLE Keys");
memset(&p_dev_rec->sec_rec.ble_keys, 0, sizeof(tBTM_SEC_BLE_KEYS));
btm_ble_resolving_list_remove_dev(p_dev_rec);
@@ -5004,7 +5037,7 @@
uint32_t ext_feat;
uint8_t chnl_mask[L2CAP_FIXED_CHNL_ARRAY_SIZE];
- LOG_VERBOSE("link_key_type = 0x%x", p_dev_rec->sec_rec.link_key_type);
+ log::verbose("link_key_type = 0x{:x}", p_dev_rec->sec_rec.link_key_type);
if ((p_dev_rec->sec_rec.link_key_type != BTM_LKEY_TYPE_UNAUTH_COMB_P_256) &&
(p_dev_rec->sec_rec.link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256))
@@ -5044,8 +5077,8 @@
p_dev_rec->is_originator) {
tBTM_STATUS btm_status = btm_sec_execute_procedure(p_dev_rec);
if (btm_status != BTM_CMD_STARTED) {
- LOG_WARN("Security procedure not started! status:%s",
- btm_status_text(btm_status).c_str());
+ log::warn("Security procedure not started! status:{}",
+ btm_status_text(btm_status).c_str());
btm_sec_dev_rec_cback_event(p_dev_rec, btm_status, false);
}
}
@@ -5062,7 +5095,7 @@
}
if (p_dev_rec->remote_features_needed) {
- LOG_DEBUG("Now device in SC Only mode, waiting for peer remote features!");
+ log::debug("Now device in SC Only mode, waiting for peer remote features!");
btm_io_capabilities_req(p_dev_rec->bd_addr);
p_dev_rec->remote_features_needed = false;
}
diff --git a/system/stack/btm/btm_sec_cb.cc b/system/stack/btm/btm_sec_cb.cc
index f9628e6..b1bb0e7 100644
--- a/system/stack/btm/btm_sec_cb.cc
+++ b/system/stack/btm/btm_sec_cb.cc
@@ -19,6 +19,8 @@
#include "stack/btm/btm_sec_cb.h"
+#include <bluetooth/log.h>
+
#include <cstdint>
#include "internal_include/bt_trace.h"
@@ -32,6 +34,8 @@
#include "stack/include/bt_psm_types.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
void tBTM_SEC_CB::Init(uint8_t initial_security_mode) {
memset(&cfg, 0, sizeof(cfg));
memset(&devcb, 0, sizeof(devcb));
@@ -131,11 +135,11 @@
} else if (transport == BT_TRANSPORT_LE) {
return sec_rec->is_le_device_encrypted();
}
- LOG_ERROR("unknown transport:%s", bt_transport_text(transport).c_str());
+ log::error("unknown transport:{}", bt_transport_text(transport).c_str());
return false;
}
- LOG_ERROR("unknown device:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::error("unknown device:{}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return false;
}
@@ -148,11 +152,11 @@
} else if (transport == BT_TRANSPORT_LE) {
return sec_rec->is_le_link_key_authenticated();
}
- LOG_ERROR("unknown transport:%s", bt_transport_text(transport).c_str());
+ log::error("unknown transport:{}", bt_transport_text(transport).c_str());
return false;
}
- LOG_ERROR("unknown device:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::error("unknown device:{}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return false;
}
@@ -165,11 +169,11 @@
} else if (transport == BT_TRANSPORT_LE) {
return sec_rec->is_le_device_authenticated();
}
- LOG_ERROR("unknown transport:%s", bt_transport_text(transport).c_str());
+ log::error("unknown transport:{}", bt_transport_text(transport).c_str());
return false;
}
- LOG_ERROR("unknown device:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::error("unknown device:{}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return false;
}
@@ -182,11 +186,11 @@
} else if (transport == BT_TRANSPORT_LE) {
return sec_rec->is_le_link_key_known();
}
- LOG_ERROR("unknown transport:%s", bt_transport_text(transport).c_str());
+ log::error("unknown transport:{}", bt_transport_text(transport).c_str());
return false;
}
- LOG_ERROR("unknown device:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::error("unknown device:{}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return false;
}
@@ -199,8 +203,8 @@
p_dev_rec->sec_rec.is_link_key_known())) {
is_bonded = true;
}
- LOG_DEBUG("Device record bonded check peer:%s is_bonded:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), logbool(is_bonded).c_str());
+ log::debug("Device record bonded check peer:{} is_bonded:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr), logbool(is_bonded).c_str());
return is_bonded;
}
@@ -214,7 +218,7 @@
uint16_t first_unused_record = BTM_NO_AVAIL_SEC_SERVICES;
bool record_allocated = false;
- LOG_VERBOSE("sec_level:0x%x", sec_level);
+ log::verbose("sec_level:0x{:x}", sec_level);
/* See if the record can be reused (same service name, psm, mx_proto_id,
service_id, and mx_chan_id), or obtain the next unused record */
@@ -245,7 +249,7 @@
}
if (!record_allocated) {
- LOG_WARN("Out of Service Records (%d)", BTM_SEC_MAX_SERVICE_RECORDS);
+ log::warn("Out of Service Records ({})", BTM_SEC_MAX_SERVICE_RECORDS);
return (record_allocated);
}
@@ -312,9 +316,9 @@
p_srec->security_flags |= (uint16_t)(sec_level | BTM_SEC_IN_USE);
- LOG_DEBUG(
- "[%d]: id:%d, is_orig:%s psm:0x%04x proto_id:%d chan_id:%d"
- " : sec:0x%x service_name:[%s] (up to %d chars saved)",
+ log::debug(
+ "[{}]: id:{}, is_orig:{} psm:0x{:04x} proto_id:{} chan_id:{} : "
+ "sec:0x{:x} service_name:[{}] (up to {} chars saved)",
index, service_id, logbool(is_originator).c_str(), psm, mx_proto_id,
mx_chan_id, p_srec->security_flags, p_name, BT_MAX_SERVICE_NAME_LEN);
@@ -331,7 +335,7 @@
if ((p_srec->security_flags & BTM_SEC_IN_USE) &&
(p_srec->psm != BT_PSM_SDP) &&
(!service_id || (service_id == p_srec->service_id))) {
- LOG_VERBOSE("BTM_SEC_CLR[%d]: id:%d", i, service_id);
+ log::verbose("BTM_SEC_CLR[{}]: id:{}", i, service_id);
p_srec->security_flags = 0;
num_freed++;
}
@@ -347,12 +351,12 @@
for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_srec++) {
/* Delete services with specified name (if in use and not SDP) */
if ((p_srec->security_flags & BTM_SEC_IN_USE) && (p_srec->psm == psm)) {
- LOG_VERBOSE("BTM_SEC_CLR[%d]: id %d ", i, p_srec->service_id);
+ log::verbose("BTM_SEC_CLR[{}]: id {} ", i, p_srec->service_id);
p_srec->security_flags = 0;
num_freed++;
}
}
- LOG_VERBOSE("psm:0x%x num_freed:%d", psm, num_freed);
+ log::verbose("psm:0x{:x} num_freed:{}", psm, num_freed);
return (num_freed);
}
diff --git a/system/stack/btm/btm_sec_int_types.h b/system/stack/btm/btm_sec_int_types.h
index 4f8d84d..a2e265b 100644
--- a/system/stack/btm/btm_sec_int_types.h
+++ b/system/stack/btm/btm_sec_int_types.h
@@ -17,6 +17,8 @@
#pragma once
+#include <bluetooth/log.h>
+
#include <cstdint>
#include "stack/include/bt_octets.h"
@@ -105,3 +107,8 @@
#define BTM_SEC_ENC_PENDING 5 /* wait for link encryption pending */
typedef uint8_t tBTM_SEC_ACTION;
+
+namespace fmt {
+template <>
+struct formatter<tBTM_PAIRING_STATE> : enum_formatter<tBTM_PAIRING_STATE> {};
+} // namespace fmt
diff --git a/system/stack/btm/btm_security_client_interface.cc b/system/stack/btm/btm_security_client_interface.cc
index f573199c..1679117 100644
--- a/system/stack/btm/btm_security_client_interface.cc
+++ b/system/stack/btm/btm_security_client_interface.cc
@@ -17,6 +17,8 @@
#define LOG_TAG "sec_interf"
+#include <bluetooth/log.h>
+
#include "os/log.h"
#include "stack/btm/btm_dev.h"
#include "stack/btm/btm_sec.h"
@@ -26,6 +28,8 @@
#include "stack/include/security_client_callbacks.h"
#include "types/bt_transport.h"
+using namespace bluetooth;
+
static void BTM_SecConfirmReqReply(tBTM_STATUS res, tBT_TRANSPORT transport,
const RawAddress bd_addr) {
if (transport == BT_TRANSPORT_BR_EDR) {
@@ -33,7 +37,7 @@
} else if (transport == BT_TRANSPORT_LE) {
BTM_BleConfirmReply(bd_addr, res);
} else {
- LOG_ERROR("Unexpected transport:%d", transport);
+ log::error("Unexpected transport:{}", transport);
}
}
diff --git a/system/stack/btm/hfp_lc3_decoder.cc b/system/stack/btm/hfp_lc3_decoder.cc
index dd82859..42bc382 100644
--- a/system/stack/btm/hfp_lc3_decoder.cc
+++ b/system/stack/btm/hfp_lc3_decoder.cc
@@ -19,12 +19,15 @@
#include "hfp_lc3_decoder.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <lc3.h>
#include <cstring>
+#include "os/log.h"
#include "osi/include/allocator.h"
-#include "osi/include/log.h"
+
+using namespace bluetooth;
const int HFP_LC3_H2_HEADER_LEN = 2;
const int HFP_LC3_PKT_FRAME_LEN = 58;
@@ -35,8 +38,7 @@
bool hfp_lc3_decoder_init() {
if (hfp_lc3_decoder_mem) {
- LOG_WARN("%s: The decoder instance should have had been released.",
- __func__);
+ log::warn("The decoder instance should have had been released.");
osi_free(hfp_lc3_decoder_mem);
}
@@ -61,8 +63,8 @@
bool hfp_lc3_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf,
size_t out_len) {
if (o_buf == nullptr || out_len < HFP_LC3_PCM_BYTES) {
- LOG_ERROR("%s: Output buffer size %zu is less than LC3 frame size %d",
- __func__, out_len, HFP_LC3_PCM_BYTES);
+ log::error("Output buffer size {} is less than LC3 frame size {}", out_len,
+ HFP_LC3_PCM_BYTES);
return false;
}
diff --git a/system/stack/btm/hfp_lc3_decoder_linux.cc b/system/stack/btm/hfp_lc3_decoder_linux.cc
index 52d3d45..68674aa 100644
--- a/system/stack/btm/hfp_lc3_decoder_linux.cc
+++ b/system/stack/btm/hfp_lc3_decoder_linux.cc
@@ -16,12 +16,16 @@
#define LOG_TAG "hfp_lc3_decoder"
+#include <bluetooth/log.h>
+
#include <algorithm>
#include "hfp_lc3_decoder.h"
#include "mmc/codec_client/codec_client.h"
#include "mmc/proto/mmc_config.pb.h"
-#include "osi/include/log.h"
+#include "os/log.h"
+
+using namespace bluetooth;
const int HFP_LC3_H2_HEADER_LEN = 2;
const int HFP_LC3_PKT_FRAME_LEN = 58;
@@ -51,8 +55,7 @@
int ret = client->init(config);
if (ret < 0) {
- LOG_ERROR("%s: Init failed with error message, %s", __func__,
- strerror(-ret));
+ log::error("Init failed with error message, {}", strerror(-ret));
return false;
}
@@ -70,13 +73,13 @@
bool hfp_lc3_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf,
size_t out_len) {
if (o_buf == nullptr || out_len < HFP_LC3_PCM_BYTES) {
- LOG_ERROR("%s: Output buffer size %zu is less than LC3 frame size %d",
- __func__, out_len, HFP_LC3_PCM_BYTES);
+ log::error("Output buffer size {} is less than LC3 frame size {}", out_len,
+ HFP_LC3_PCM_BYTES);
return false;
}
if (!client) {
- LOG_ERROR("%s: CodecClient has not been initialized", __func__);
+ log::error("CodecClient has not been initialized");
return false;
}
@@ -91,8 +94,7 @@
o_packet, out_len + 1);
if (rc < 0) {
- LOG_WARN("%s: Decode failed with error message, %s", __func__,
- strerror(-rc));
+ log::warn("Decode failed with error message, {}", strerror(-rc));
return false;
}
diff --git a/system/stack/btm/hfp_lc3_encoder.cc b/system/stack/btm/hfp_lc3_encoder.cc
index f968513..767969f 100644
--- a/system/stack/btm/hfp_lc3_encoder.cc
+++ b/system/stack/btm/hfp_lc3_encoder.cc
@@ -18,12 +18,15 @@
#include "hfp_lc3_encoder.h"
+#include <bluetooth/log.h>
#include <lc3.h>
#include <cstring>
+#include "os/log.h"
#include "osi/include/allocator.h"
-#include "osi/include/log.h"
+
+using namespace bluetooth;
const int HFP_LC3_PCM_BYTES = 480;
const int HFP_LC3_PKT_FRAME_LEN = 58;
@@ -33,8 +36,7 @@
void hfp_lc3_encoder_init() {
if (hfp_lc3_encoder_mem) {
- LOG_WARN("%s: The encoder instance should have had been released.",
- __func__);
+ log::warn("The encoder instance should have had been released.");
osi_free(hfp_lc3_encoder_mem);
}
@@ -56,7 +58,7 @@
uint32_t hfp_lc3_encode_frames(int16_t* input, uint8_t* output) {
if (input == nullptr || output == nullptr) {
- LOG_ERROR("%s: Buffer is null.", __func__);
+ log::error("Buffer is null.");
return 0;
}
diff --git a/system/stack/btm/hfp_lc3_encoder_linux.cc b/system/stack/btm/hfp_lc3_encoder_linux.cc
index 7225014..2385a2f 100644
--- a/system/stack/btm/hfp_lc3_encoder_linux.cc
+++ b/system/stack/btm/hfp_lc3_encoder_linux.cc
@@ -16,10 +16,14 @@
#define LOG_TAG "hfp_lc3_encoder"
+#include <bluetooth/log.h>
+
#include "hfp_lc3_encoder.h"
#include "mmc/codec_client/codec_client.h"
#include "mmc/proto/mmc_config.pb.h"
-#include "osi/include/log.h"
+#include "os/log.h"
+
+using namespace bluetooth;
const int HFP_LC3_PCM_BYTES = 480;
const int HFP_LC3_PKT_FRAME_LEN = 58;
@@ -46,8 +50,7 @@
int ret = client->init(config);
if (ret < 0) {
- LOG_ERROR("%s: Init failed with error message, %s", __func__,
- strerror(-ret));
+ log::error("Init failed with error message, {}", strerror(-ret));
}
return;
}
@@ -62,12 +65,12 @@
uint32_t hfp_lc3_encode_frames(int16_t* input, uint8_t* output) {
if (input == nullptr || output == nullptr) {
- LOG_ERROR("%s: Buffer is null", __func__);
+ log::error("Buffer is null");
return 0;
}
if (!client) {
- LOG_ERROR("%s: CodecClient has not been initialized", __func__);
+ log::error("CodecClient has not been initialized");
return 0;
}
@@ -75,8 +78,7 @@
HFP_LC3_PKT_FRAME_LEN);
if (rc < 0) {
- LOG_WARN("%s: Encode failed with error message, %s", __func__,
- strerror(-rc));
+ log::warn("Encode failed with error message, {}", strerror(-rc));
return 0;
}
diff --git a/system/stack/btm/hfp_msbc_decoder.cc b/system/stack/btm/hfp_msbc_decoder.cc
index 96c8825..2d4f452 100644
--- a/system/stack/btm/hfp_msbc_decoder.cc
+++ b/system/stack/btm/hfp_msbc_decoder.cc
@@ -19,16 +19,24 @@
#include "hfp_msbc_decoder.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <cstring>
#include "embdrv/sbc/decoder/include/oi_codec_sbc.h"
#include "embdrv/sbc/decoder/include/oi_status.h"
-#include "osi/include/log.h"
+#include "os/log.h"
#define HFP_MSBC_PKT_LEN 60
#define HFP_MSBC_PCM_BYTES 240
+using namespace bluetooth;
+
+namespace fmt {
+template <>
+struct formatter<OI_STATUS> : enum_formatter<OI_STATUS> {};
+} // namespace fmt
+
typedef struct {
OI_CODEC_SBC_DECODER_CONTEXT decoder_context;
uint32_t context_data[CODEC_DATA_WORDS(2, SBC_CODEC_FAST_FILTER_BUFFERS)];
@@ -41,15 +49,14 @@
&hfp_msbc_decoder.decoder_context, hfp_msbc_decoder.context_data,
sizeof(hfp_msbc_decoder.context_data), 1, 1, false);
if (!OI_SUCCESS(status)) {
- LOG_ERROR("%s: OI_CODEC_SBC_DecoderReset failed with error code %d",
- __func__, status);
+ log::error("OI_CODEC_SBC_DecoderReset failed with error code {}", status);
return false;
}
status = OI_CODEC_SBC_DecoderConfigureMSbc(&hfp_msbc_decoder.decoder_context);
if (!OI_SUCCESS(status)) {
- LOG_ERROR("%s: OI_CODEC_SBC_DecoderConfigureMSbc failed with error code %d",
- __func__, status);
+ log::error("OI_CODEC_SBC_DecoderConfigureMSbc failed with error code {}",
+ status);
return false;
}
@@ -64,8 +71,8 @@
bool hfp_msbc_decoder_decode_packet(const uint8_t* i_buf, int16_t* o_buf,
size_t out_len) {
if (out_len < HFP_MSBC_PCM_BYTES) {
- LOG_ERROR(
- "Output buffer's size %lu is less than one complete mSBC frame %d",
+ log::error(
+ "Output buffer's size {} is less than one complete mSBC frame {}",
(unsigned long)out_len, HFP_MSBC_PCM_BYTES);
return false;
}
@@ -80,8 +87,8 @@
OI_STATUS status = OI_CODEC_SBC_DecodeFrame(
&hfp_msbc_decoder.decoder_context, &oi_data, &oi_size, o_buf, &out_avail);
if (!OI_SUCCESS(status) || out_avail != HFP_MSBC_PCM_BYTES || oi_size != 0) {
- LOG_ERROR("Decoding failure: %d, %lu, %lu", status,
- (unsigned long)out_avail, (unsigned long)oi_size);
+ log::error("Decoding failure: {}, {}, {}", status, (unsigned long)out_avail,
+ (unsigned long)oi_size);
return false;
}
diff --git a/system/stack/btm/hfp_msbc_encoder.cc b/system/stack/btm/hfp_msbc_encoder.cc
index 581a49d..4f4d605 100644
--- a/system/stack/btm/hfp_msbc_encoder.cc
+++ b/system/stack/btm/hfp_msbc_encoder.cc
@@ -21,7 +21,6 @@
#include <cstring>
#include "embdrv/sbc/encoder/include/sbc_encoder.h"
-#include "osi/include/log.h"
typedef struct {
SBC_ENC_PARAMS sbc_encoder_params;
diff --git a/system/stack/btm/neighbor_inquiry.h b/system/stack/btm/neighbor_inquiry.h
index de0e955..c51661c 100644
--- a/system/stack/btm/neighbor_inquiry.h
+++ b/system/stack/btm/neighbor_inquiry.h
@@ -16,6 +16,8 @@
#pragma once
+#include <bluetooth/log.h>
+
#include <cstdint>
#include "internal_include/bt_target.h"
@@ -306,3 +308,9 @@
bool btm_inq_find_bdaddr(const RawAddress& p_bda);
tINQ_DB_ENT* btm_inq_db_find(const RawAddress& p_bda);
+
+namespace fmt {
+template <>
+struct formatter<tBTM_INQUIRY_CMPL::STATUS>
+ : enum_formatter<tBTM_INQUIRY_CMPL::STATUS> {};
+} // namespace fmt
diff --git a/system/stack/btm/power_mode.h b/system/stack/btm/power_mode.h
index eb98945..e21162d 100644
--- a/system/stack/btm/power_mode.h
+++ b/system/stack/btm/power_mode.h
@@ -130,7 +130,87 @@
/* Idle state - page scan, LE advt, inquiry scan */
#define BTM_CONTRL_IDLE 3
-typedef uint8_t tBTM_CONTRL_STATE;
+#define BTM_CONTRL_NUM_ACL_CLASSIC_ACTIVE_MASK 0xF
+#define BTM_CONTRL_NUM_ACL_CLASSIC_ACTIVE_SHIFT 0
+#define BTM_CONTRL_NUM_ACL_CLASSIC_SNIFF_MASK 0xF
+#define BTM_CONTRL_NUM_ACL_CLASSIC_SNIFF_SHIFT 4
+#define BTM_CONTRL_NUM_ACL_LE_MASK 0xF
+#define BTM_CONTRL_NUM_ACL_LE_SHIFT 8
+#define BTM_CONTRL_NUM_LE_ADV_MASK 0xF
+#define BTM_CONTRL_NUM_LE_ADV_SHIFT 12
+
+#define BTM_CONTRL_LE_SCAN_MODE_IDLE 0
+#define BTM_CONTRL_LE_SCAN_MODE_ULTRA_LOW_POWER 1
+#define BTM_CONTRL_LE_SCAN_MODE_LOW_POWER 2
+#define BTM_CONTRL_LE_SCAN_MODE_BALANCED 3
+#define BTM_CONTRL_LE_SCAN_MODE_LOW_LATENCY 4
+#define BTM_CONTRL_LE_SCAN_MODE_MASK 0xF
+#define BTM_CONTRL_LE_SCAN_MODE_SHIFT 16
+
+#define BTM_CONTRL_INQUIRY_SHIFT 20
+#define BTM_CONTRL_INQUIRY (1u << BTM_CONTRL_INQUIRY_SHIFT)
+#define BTM_CONTRL_SCO_SHIFT 21
+#define BTM_CONTRL_SCO (1u << BTM_CONTRL_SCO_SHIFT)
+#define BTM_CONTRL_A2DP_SHIFT 22
+#define BTM_CONTRL_A2DP (1u << BTM_CONTRL_A2DP_SHIFT)
+#define BTM_CONTRL_LE_AUDIO_SHIFT 23
+#define BTM_CONTRL_LE_AUDIO (1u << BTM_CONTRL_LE_AUDIO_SHIFT)
+
+typedef uint32_t tBTM_CONTRL_STATE;
+
+inline void set_num_acl_active_to_ctrl_state(uint32_t num,
+ tBTM_CONTRL_STATE& ctrl_state) {
+ if (num > BTM_CONTRL_NUM_ACL_CLASSIC_ACTIVE_MASK) {
+ num = BTM_CONTRL_NUM_ACL_CLASSIC_ACTIVE_MASK;
+ }
+ ctrl_state |= ((num & BTM_CONTRL_NUM_ACL_CLASSIC_ACTIVE_MASK)
+ << BTM_CONTRL_NUM_ACL_CLASSIC_ACTIVE_SHIFT);
+}
+
+inline void set_num_acl_sniff_to_ctrl_state(uint32_t num,
+ tBTM_CONTRL_STATE& ctrl_state) {
+ if (num > BTM_CONTRL_NUM_ACL_CLASSIC_SNIFF_MASK) {
+ num = BTM_CONTRL_NUM_ACL_CLASSIC_SNIFF_MASK;
+ }
+ ctrl_state |= ((num & BTM_CONTRL_NUM_ACL_CLASSIC_SNIFF_MASK)
+ << BTM_CONTRL_NUM_ACL_CLASSIC_SNIFF_SHIFT);
+}
+
+inline void set_num_acl_le_to_ctrl_state(uint32_t num,
+ tBTM_CONTRL_STATE& ctrl_state) {
+ if (num > BTM_CONTRL_NUM_ACL_LE_MASK) {
+ num = BTM_CONTRL_NUM_ACL_LE_MASK;
+ }
+ ctrl_state |=
+ ((num & BTM_CONTRL_NUM_ACL_LE_MASK) << BTM_CONTRL_NUM_ACL_LE_SHIFT);
+}
+
+inline void set_num_le_adv_to_ctrl_state(uint32_t num,
+ tBTM_CONTRL_STATE& ctrl_state) {
+ if (num > BTM_CONTRL_NUM_LE_ADV_MASK) {
+ num = BTM_CONTRL_NUM_LE_ADV_MASK;
+ }
+ ctrl_state |=
+ ((num & BTM_CONTRL_NUM_LE_ADV_MASK) << BTM_CONTRL_NUM_LE_ADV_SHIFT);
+}
+
+inline void set_le_scan_mode_to_ctrl_state(uint32_t duty_cycle,
+ tBTM_CONTRL_STATE& ctrl_state) {
+ uint32_t scan_mode;
+ if (duty_cycle == 0) {
+ scan_mode = BTM_CONTRL_LE_SCAN_MODE_IDLE;
+ } else if (duty_cycle <= 5) {
+ scan_mode = BTM_CONTRL_LE_SCAN_MODE_ULTRA_LOW_POWER;
+ } else if (duty_cycle <= 10) {
+ scan_mode = BTM_CONTRL_LE_SCAN_MODE_LOW_POWER;
+ } else if (duty_cycle <= 25) {
+ scan_mode = BTM_CONTRL_LE_SCAN_MODE_BALANCED;
+ } else {
+ scan_mode = BTM_CONTRL_LE_SCAN_MODE_LOW_LATENCY;
+ }
+ ctrl_state |= ((scan_mode & BTM_CONTRL_LE_SCAN_MODE_MASK)
+ << BTM_CONTRL_LE_SCAN_MODE_SHIFT);
+}
/*******************************************************************************
*
@@ -199,3 +279,48 @@
*
******************************************************************************/
tBTM_CONTRL_STATE BTM_PM_ReadControllerState(void);
+
+/*******************************************************************************
+ *
+ * Function BTM_PM_ReadSniffLinkCount
+ *
+ * Description Return the number of BT connection in sniff mode
+ *
+ * Returns Number of BT connection in sniff mode
+ *
+ ******************************************************************************/
+uint8_t BTM_PM_ReadSniffLinkCount(void);
+
+/*******************************************************************************
+ *
+ * Function BTM_PM_ReadBleLinkCount
+ *
+ * Description Return the number of BLE connection
+ *
+ * Returns Number of BLE connection
+ *
+ ******************************************************************************/
+uint8_t BTM_PM_ReadBleLinkCount(void);
+
+/*******************************************************************************
+ *
+ * Function BTM_PM_DeviceInScanState
+ *
+ * Description This function is called to check if in inquiry
+ *
+ * Returns true, if in inquiry
+ *
+ ******************************************************************************/
+bool BTM_PM_DeviceInScanState(void);
+
+/*******************************************************************************
+ *
+ * Function BTM_PM_ReadBleScanDutyCycle
+ *
+ * Description Returns BLE scan duty cycle which is (window * 100) /
+ *interval
+ *
+ * Returns BLE scan duty cycle
+ *
+ ******************************************************************************/
+uint32_t BTM_PM_ReadBleScanDutyCycle(void);
diff --git a/system/stack/btm/security_device_record.h b/system/stack/btm/security_device_record.h
index cdc9599..f66935f 100644
--- a/system/stack/btm/security_device_record.h
+++ b/system/stack/btm/security_device_record.h
@@ -19,6 +19,7 @@
#pragma once
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <cstdint>
#include <string>
@@ -113,7 +114,7 @@
if (is_ble_addr_type_known(ble_addr_type)) {
ble_addr_type_ = ble_addr_type;
} else {
- LOG_ERROR("Unknown address type:0x%x", ble_addr_type);
+ bluetooth::log::error("Unknown address type:0x{:x}", ble_addr_type);
}
}
@@ -456,3 +457,11 @@
// security related properties
tBTM_SEC_REC sec_rec;
};
+
+namespace fmt {
+template <>
+struct formatter<tSECURITY_STATE>
+ : string_formatter<tSECURITY_STATE, &security_state_text> {};
+template <>
+struct formatter<tBLE_RAND_ADDR_TYPE> : enum_formatter<tBLE_RAND_ADDR_TYPE> {};
+} // namespace fmt
diff --git a/system/stack/btm/security_event_parser.cc b/system/stack/btm/security_event_parser.cc
new file mode 100644
index 0000000..0e675e1
--- /dev/null
+++ b/system/stack/btm/security_event_parser.cc
@@ -0,0 +1,280 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "security_event_parser.h"
+
+#include <bluetooth/log.h>
+
+#include <optional>
+#include <string>
+
+#include "btm_sec.h"
+#include "common/metrics.h"
+#include "hci/hci_packets.h"
+#include "main/shim/helpers.h"
+#include "stack/include/btm_sec_api_types.h"
+#include "stack/include/hci_error_code.h"
+#include "stack/include/sec_hci_link_interface.h"
+#include "stack/include/stack_metrics_logging.h"
+#include "types/raw_address.h"
+
+using namespace bluetooth;
+using namespace bluetooth::hci;
+using android::bluetooth::hci::CMD_UNKNOWN;
+using android::bluetooth::hci::STATUS_UNKNOWN;
+using bluetooth::common::kUnknownConnectionHandle;
+
+namespace bluetooth::stack::btm {
+namespace {
+static void log_address_and_status(const Address& bda, EventCode event_code,
+ ErrorCode event_status) {
+ uint32_t cmd = android::bluetooth::hci::CMD_UNKNOWN;
+ uint16_t status = static_cast<uint16_t>(event_status);
+ uint16_t reason = android::bluetooth::hci::STATUS_UNKNOWN;
+ uint16_t handle = bluetooth::common::kUnknownConnectionHandle;
+ int64_t value = 0;
+ log_classic_pairing_event(ToRawAddress(bda), handle, cmd,
+ static_cast<uint16_t>(event_code), status, reason,
+ value);
+}
+static void log_address(const Address& bda, EventCode event_code) {
+ uint32_t cmd = android::bluetooth::hci::CMD_UNKNOWN;
+ uint16_t status = android::bluetooth::hci::STATUS_UNKNOWN;
+ uint16_t reason = android::bluetooth::hci::STATUS_UNKNOWN;
+ uint16_t handle = bluetooth::common::kUnknownConnectionHandle;
+ int64_t value = 0;
+ log_classic_pairing_event(ToRawAddress(bda), handle, cmd,
+ static_cast<uint16_t>(event_code), status, reason,
+ value);
+}
+static void parse_encryption_change(const EventView event) {
+ auto change_opt = EncryptionChangeView::CreateOptional(event);
+ ASSERT(change_opt.has_value());
+ auto change = change_opt.value();
+
+ ErrorCode status = change.GetStatus();
+ uint16_t handle = change.GetConnectionHandle();
+ EncryptionEnabled encr_enable = change.GetEncryptionEnabled();
+
+ btm_sec_encryption_change_evt(handle, static_cast<tHCI_STATUS>(status),
+ static_cast<uint8_t>(encr_enable));
+ log_classic_pairing_event(ToRawAddress(Address::kEmpty), handle,
+ android::bluetooth::hci::CMD_UNKNOWN,
+ static_cast<uint32_t>(change.GetEventCode()),
+ static_cast<uint16_t>(status),
+ android::bluetooth::hci::STATUS_UNKNOWN, 0);
+}
+static void parse_change_connection_link_key_complete(const EventView event) {
+ auto complete_opt =
+ ChangeConnectionLinkKeyCompleteView::CreateOptional(event);
+ ASSERT(complete_opt.has_value());
+ auto complete = complete_opt.value();
+
+ log_classic_pairing_event(ToRawAddress(Address::kEmpty),
+ complete.GetConnectionHandle(),
+ android::bluetooth::hci::CMD_UNKNOWN,
+ static_cast<uint32_t>(complete.GetEventCode()),
+ static_cast<uint16_t>(complete.GetStatus()),
+ android::bluetooth::hci::STATUS_UNKNOWN, 0);
+}
+static void parse_central_link_key_complete(const EventView event) {
+ auto event_opt = CentralLinkKeyCompleteView::CreateOptional(event);
+ ASSERT(event_opt.has_value());
+ auto complete = event_opt.value();
+
+ log::info("Unhandled event: {}", EventCodeText(event.GetEventCode()).c_str());
+}
+static void parse_return_link_keys(const EventView event) {
+ auto event_opt = ReturnLinkKeysView::CreateOptional(event);
+ ASSERT(event_opt.has_value());
+ auto view = event_opt.value();
+
+ log::info("Unhandled event: {}", EventCodeText(event.GetEventCode()).c_str());
+}
+static void parse_pin_code_request(const EventView event) {
+ auto event_opt = PinCodeRequestView::CreateOptional(event);
+ ASSERT(event_opt.has_value());
+ auto request = event_opt.value();
+ btm_sec_pin_code_request(ToRawAddress(request.GetBdAddr()));
+}
+static void parse_link_key_request(const EventView event) {
+ auto event_opt = LinkKeyRequestView::CreateOptional(event);
+ ASSERT(event_opt.has_value());
+ auto request = event_opt.value();
+
+ btm_sec_link_key_request(ToRawAddress(request.GetBdAddr()));
+ log_address(request.GetBdAddr(), event.GetEventCode());
+}
+static void parse_link_key_notification(const EventView event) {
+ auto event_opt = LinkKeyNotificationView::CreateOptional(event);
+ ASSERT(event_opt.has_value());
+ auto notification = event_opt.value();
+
+ btm_sec_link_key_notification(
+ ToRawAddress(notification.GetBdAddr()), notification.GetLinkKey(),
+ static_cast<uint8_t>(notification.GetKeyType()));
+ log_address(notification.GetBdAddr(), event.GetEventCode());
+}
+static void parse_encryption_key_refresh_complete(const EventView event) {
+ auto event_opt = EncryptionKeyRefreshCompleteView::CreateOptional(event);
+ ASSERT(event_opt.has_value());
+ auto refresh = event_opt.value();
+
+ btm_sec_encryption_key_refresh_complete(
+ refresh.GetConnectionHandle(),
+ static_cast<tHCI_STATUS>(refresh.GetStatus()));
+}
+static void parse_io_capabilities_req(const EventView event) {
+ auto event_opt = IoCapabilityRequestView::CreateOptional(event);
+ ASSERT(event_opt.has_value());
+ auto request = event_opt.value();
+
+ RawAddress peer = ToRawAddress(request.GetBdAddr());
+
+ btm_io_capabilities_req(peer);
+ log_address(request.GetBdAddr(), event.GetEventCode());
+}
+static void parse_io_capabilities_rsp(const EventView event) {
+ auto response_opt = IoCapabilityResponseView::CreateOptional(event);
+ ASSERT(response_opt.has_value());
+ auto response = response_opt.value();
+
+ tBTM_SP_IO_RSP evt_data{
+ .bd_addr = ToRawAddress(response.GetBdAddr()),
+ .io_cap = static_cast<tBTM_IO_CAP>(response.GetIoCapability()),
+ .oob_data = static_cast<tBTM_OOB_DATA>(response.GetOobDataPresent()),
+ .auth_req =
+ static_cast<tBTM_AUTH_REQ>(response.GetAuthenticationRequirements()),
+ };
+
+ btm_io_capabilities_rsp(evt_data);
+ log_address(response.GetBdAddr(), event.GetEventCode());
+}
+static void parse_remote_oob_data_request(const EventView event) {
+ auto event_opt = RemoteOobDataRequestView::CreateOptional(event);
+ ASSERT(event_opt.has_value());
+ auto request = event_opt.value();
+
+ btm_rem_oob_req(ToRawAddress(request.GetBdAddr()));
+ log_address(request.GetBdAddr(), event.GetEventCode());
+}
+static void parse_simple_pairing_complete(const EventView event) {
+ auto event_opt = SimplePairingCompleteView::CreateOptional(event);
+ ASSERT(event_opt.has_value());
+ auto complete = event_opt.value();
+
+ btm_simple_pair_complete(ToRawAddress(complete.GetBdAddr()),
+ static_cast<uint8_t>(complete.GetStatus()));
+ log_address_and_status(complete.GetBdAddr(), event.GetEventCode(),
+ complete.GetStatus());
+}
+static void parse_user_passkey_notification(const EventView event) {
+ auto event_opt = UserPasskeyNotificationView::CreateOptional(event);
+ ASSERT(event_opt.has_value());
+ auto notification = event_opt.value();
+
+ btm_proc_sp_req_evt(BTM_SP_KEY_NOTIF_EVT,
+ ToRawAddress(notification.GetBdAddr()),
+ notification.GetPasskey());
+ log_address(notification.GetBdAddr(), event.GetEventCode());
+}
+static void parse_keypress_notification(const EventView event) {
+ auto event_opt = KeypressNotificationView::CreateOptional(event);
+ ASSERT(event_opt.has_value());
+ auto notification = event_opt.value();
+
+ log::info("Unhandled event: {}", EventCodeText(event.GetEventCode()).c_str());
+ log_address(notification.GetBdAddr(), event.GetEventCode());
+}
+static void parse_user_confirmation_request(const EventView event) {
+ auto event_opt = UserConfirmationRequestView::CreateOptional(event);
+ ASSERT(event_opt.has_value());
+ auto request = event_opt.value();
+
+ btm_proc_sp_req_evt(BTM_SP_CFM_REQ_EVT, ToRawAddress(request.GetBdAddr()),
+ request.GetNumericValue());
+ log_address(request.GetBdAddr(), event.GetEventCode());
+}
+static void parse_user_passkey_request(const EventView event) {
+ auto event_opt = UserPasskeyRequestView::CreateOptional(event);
+ ASSERT(event_opt.has_value());
+ auto request = event_opt.value();
+
+ btm_proc_sp_req_evt(BTM_SP_KEY_REQ_EVT, ToRawAddress(request.GetBdAddr()),
+ 0 /* No value needed */);
+ log_address(request.GetBdAddr(), event.GetEventCode());
+}
+} // namespace
+} // namespace bluetooth::stack::btm
+
+namespace bluetooth::stack::btm {
+
+void SecurityEventParser::OnSecurityEvent(bluetooth::hci::EventView event) {
+ switch (event.GetEventCode()) {
+ case EventCode::ENCRYPTION_CHANGE:
+ parse_encryption_change(event);
+ break;
+ case EventCode::CHANGE_CONNECTION_LINK_KEY_COMPLETE:
+ parse_change_connection_link_key_complete(event);
+ break;
+ case EventCode::CENTRAL_LINK_KEY_COMPLETE:
+ parse_central_link_key_complete(event);
+ break;
+ case EventCode::RETURN_LINK_KEYS:
+ parse_return_link_keys(event);
+ break;
+ case EventCode::PIN_CODE_REQUEST:
+ parse_pin_code_request(event);
+ break;
+ case EventCode::LINK_KEY_REQUEST:
+ parse_link_key_request(event);
+ break;
+ case EventCode::LINK_KEY_NOTIFICATION:
+ parse_link_key_notification(event);
+ break;
+ case EventCode::ENCRYPTION_KEY_REFRESH_COMPLETE:
+ parse_encryption_key_refresh_complete(event);
+ break;
+ case EventCode::IO_CAPABILITY_REQUEST:
+ parse_io_capabilities_req(event);
+ break;
+ case EventCode::IO_CAPABILITY_RESPONSE:
+ parse_io_capabilities_rsp(event);
+ break;
+ case EventCode::REMOTE_OOB_DATA_REQUEST:
+ parse_remote_oob_data_request(event);
+ break;
+ case EventCode::SIMPLE_PAIRING_COMPLETE:
+ parse_simple_pairing_complete(event);
+ break;
+ case EventCode::USER_PASSKEY_NOTIFICATION:
+ parse_user_passkey_notification(event);
+ break;
+ case EventCode::KEYPRESS_NOTIFICATION:
+ parse_keypress_notification(event);
+ break;
+ case EventCode::USER_CONFIRMATION_REQUEST:
+ parse_user_confirmation_request(event);
+ break;
+ case EventCode::USER_PASSKEY_REQUEST:
+ parse_user_passkey_request(event);
+ break;
+ default:
+ log::error("Unhandled event {}",
+ EventCodeText(event.GetEventCode()).c_str());
+ }
+}
+} // namespace bluetooth::stack::btm
diff --git a/system/stack/btm/security_event_parser.h b/system/stack/btm/security_event_parser.h
new file mode 100644
index 0000000..f29e372
--- /dev/null
+++ b/system/stack/btm/security_event_parser.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include "hci/hci_packets.h"
+
+namespace bluetooth::stack::btm {
+
+class SecurityEventParser {
+ public:
+ SecurityEventParser() = default;
+ virtual ~SecurityEventParser() = default;
+ void OnSecurityEvent(bluetooth::hci::EventView event);
+};
+
+} // namespace bluetooth::stack::btm
diff --git a/system/stack/btu/btu_hcif.cc b/system/stack/btu/btu_hcif.cc
index c95e7e4..4d6a238 100644
--- a/system/stack/btu/btu_hcif.cc
+++ b/system/stack/btu/btu_hcif.cc
@@ -31,6 +31,7 @@
#include <base/functional/bind.h>
#include <base/location.h>
+#include <bluetooth/log.h>
#include <cstdint>
@@ -63,6 +64,7 @@
#include "types/hci_role.h"
#include "types/raw_address.h"
+using namespace bluetooth;
using base::Location;
using bluetooth::hci::IsoManager;
@@ -110,11 +112,8 @@
static void btu_hcif_io_cap_request_evt(const uint8_t* p);
static void btu_hcif_io_cap_response_evt(const uint8_t* p);
-static void btu_ble_ll_conn_param_upd_evt(uint8_t* p, uint16_t evt_len);
static void btu_ble_proc_ltk_req(uint8_t* p, uint16_t evt_len);
static void btu_hcif_encryption_key_refresh_cmpl_evt(uint8_t* p);
-static void btu_ble_data_length_change_evt(uint8_t* p, uint16_t evt_len);
-static void btu_ble_rc_param_req_evt(uint8_t* p, uint8_t len);
/**
* Log HCI event metrics that are not handled in special functions
@@ -199,8 +198,8 @@
case HCI_CONNECTION_REQUEST_EVT: // EventCode::CONNECTION_REQUEST
case HCI_DISCONNECTION_COMP_EVT: // EventCode::DISCONNECTION_COMPLETE
default:
- LOG_ERROR(
- "Unexpectedly received event_code:0x%02x that should not be "
+ log::error(
+ "Unexpectedly received event_code:0x{:02x} that should not be "
"handled here",
evt_code);
break;
@@ -227,8 +226,8 @@
// validate event size
if (hci_evt_len < hci_event_parameters_minimum_length[hci_evt_code]) {
- LOG_WARN("%s: evt:0x%2X, malformed event of size %hhd", __func__,
- hci_evt_code, hci_evt_len);
+ log::warn("evt:0x{:2X}, malformed event of size {}", hci_evt_code,
+ hci_evt_len);
return;
}
@@ -263,16 +262,14 @@
btu_hcif_read_rmt_ext_features_comp_evt(p, hci_evt_len);
break;
case HCI_COMMAND_COMPLETE_EVT:
- LOG_ERROR(
- "%s should not have received a command complete event. "
- "Someone didn't go through the hci transmit_command function.",
- __func__);
+ log::error(
+ "should not have received a command complete event. Someone didn't "
+ "go through the hci transmit_command function.");
break;
case HCI_COMMAND_STATUS_EVT:
- LOG_ERROR(
- "%s should not have received a command status event. "
- "Someone didn't go through the hci transmit_command function.",
- __func__);
+ log::error(
+ "should not have received a command status event. Someone didn't go "
+ "through the hci transmit_command function.");
break;
case HCI_MODE_CHANGE_EVT:
btu_hcif_mode_change_evt(p);
@@ -328,32 +325,12 @@
uint8_t ble_evt_len = hci_evt_len - 1;
switch (ble_sub_code) {
- case HCI_BLE_ADV_PKT_RPT_EVT: /* result of inquiry */
- btm_ble_process_adv_pkt(ble_evt_len, p);
- break;
- case HCI_BLE_LL_CONN_PARAM_UPD_EVT:
- btu_ble_ll_conn_param_upd_evt(p, ble_evt_len);
- break;
case HCI_BLE_READ_REMOTE_FEAT_CMPL_EVT:
btm_ble_read_remote_features_complete(p, ble_evt_len);
break;
case HCI_BLE_LTK_REQ_EVT: /* received only at peripheral device */
btu_ble_proc_ltk_req(p, ble_evt_len);
break;
- case HCI_BLE_RC_PARAM_REQ_EVT:
- btu_ble_rc_param_req_evt(p, ble_evt_len);
- break;
- case HCI_BLE_DATA_LENGTH_CHANGE_EVT:
- btu_ble_data_length_change_evt(p, hci_evt_len);
- break;
-
- case HCI_BLE_PHY_UPDATE_COMPLETE_EVT:
- btm_ble_process_phy_update_pkt(ble_evt_len, p);
- break;
-
- case HCI_LE_EXTENDED_ADVERTISING_REPORT_EVT:
- btm_ble_process_ext_adv_pkt(hci_evt_len, p);
- break;
case HCI_BLE_REQ_PEER_SCA_CPL_EVT:
btm_acl_process_sca_cmpl_pkt(ble_evt_len, p);
@@ -369,32 +346,17 @@
ble_evt_len);
break;
- case HCI_LE_PERIODIC_ADV_SYNC_TRANSFERE_RECEIVED_EVT:
- btm_ble_periodic_adv_sync_tx_rcvd(p, hci_evt_len);
- break;
-
- case HCI_LE_BIGINFO_ADVERTISING_REPORT_EVT:
- btm_ble_biginfo_adv_report_rcvd(p, hci_evt_len);
- break;
-
- // Events are now captured by gd/hci/le_acl_connection_interface.h
- case HCI_BLE_CONN_COMPLETE_EVT: // SubeventCode::CONNECTION_COMPLETE
- case HCI_BLE_ENHANCED_CONN_COMPLETE_EVT: // SubeventCode::ENHANCED_CONNECTION_COMPLETE
- case HCI_LE_SUBRATE_CHANGE_EVT: // SubeventCode::LE_SUBRATE_CHANGE
default:
- LOG_ERROR(
- "Unexpectedly received LE sub_event_code:0x%02x that should not "
- "be handled here",
+ log::error(
+ "Unexpectedly received LE sub_event_code:0x{:02x} that should "
+ "not be handled here",
ble_sub_code);
break;
}
} break;
- case HCI_VENDOR_SPECIFIC_EVT:
- btm_vendor_specific_evt(const_cast<const uint8_t*>(p), hci_evt_len);
- break;
-
// Events now captured by gd::hci_layer module
+ case HCI_VENDOR_SPECIFIC_EVT:
case HCI_HARDWARE_ERROR_EVT:
case HCI_NUM_COMPL_DATA_PKTS_EVT: // EventCode::NUMBER_OF_COMPLETED_PACKETS
case HCI_CONNECTION_COMP_EVT: // EventCode::CONNECTION_COMPLETE
@@ -404,8 +366,8 @@
case HCI_ROLE_CHANGE_EVT: // EventCode::ROLE_CHANGE
case HCI_DISCONNECTION_COMP_EVT: // EventCode::DISCONNECTION_COMPLETE
default:
- LOG_ERROR(
- "Unexpectedly received event_code:0x%02x that should not be "
+ log::error(
+ "Unexpectedly received event_code:0x{:02x} that should not be "
"handled here",
hci_evt_code);
break;
@@ -731,8 +693,7 @@
btu_hcif_log_command_complete_metrics(opcode, stream);
cmd_with_cb_data* cb_wrapper = (cmd_with_cb_data*)context;
- LOG_VERBOSE("command complete for: %s",
- cb_wrapper->posted_from.ToString().c_str());
+ log::verbose("command complete for: {}", cb_wrapper->posted_from.ToString());
// 2 for event header: event code (1) + parameter length (1)
// 3 for command complete header: num_hci_pkt (1) + opcode (2)
uint16_t param_len = static_cast<uint16_t>(event->len - 5);
@@ -765,8 +726,7 @@
// report command status error
cmd_with_cb_data* cb_wrapper = (cmd_with_cb_data*)context;
- LOG_VERBOSE("command status for: %s",
- cb_wrapper->posted_from.ToString().c_str());
+ log::verbose("command status for: {}", cb_wrapper->posted_from.ToString());
std::move(cb_wrapper->cb).Run(&status, sizeof(uint16_t));
cmd_with_cb_data_cleanup(cb_wrapper);
osi_free(cb_wrapper);
@@ -1010,10 +970,6 @@
static void btu_hcif_hdl_command_complete(uint16_t opcode, uint8_t* p,
uint16_t evt_len) {
switch (opcode) {
- case HCI_INQUIRY_CANCEL:
- /* Tell inquiry processing that we are done */
- btm_process_cancel_complete(HCI_SUCCESS, BTM_BR_INQUIRY_MASK);
- break;
case HCI_SET_EVENT_FILTER:
break;
@@ -1067,7 +1023,7 @@
case HCI_BLE_CREATE_LL_CONN:
case HCI_LE_EXTENDED_CREATE_CONNECTION:
// No command complete event for those commands according to spec
- LOG_ERROR("No command complete expected, but received!");
+ log::error("No command complete expected, but received!");
break;
case HCI_BLE_TRANSMITTER_TEST:
@@ -1112,8 +1068,9 @@
break;
default:
- LOG_ERROR("Command complete for opcode:0x%02x should not be handled here",
- opcode);
+ log::error(
+ "Command complete for opcode:0x{:02x} should not be handled here",
+ opcode);
break;
}
}
@@ -1247,16 +1204,16 @@
case HCI_READ_RMT_CLOCK_OFFSET: // 0x041f
case HCI_CHANGE_CONN_PACKET_TYPE: // 0x040f
if (hci_status != HCI_SUCCESS) {
- LOG_WARN("Received bad command status for opcode:0x%02x status:%s",
- opcode, hci_status_code_text(hci_status).c_str());
+ log::warn("Received bad command status for opcode:0x{:02x} status:{}",
+ opcode, hci_status_code_text(hci_status));
}
break;
default:
- LOG_ERROR(
- "Command status for opcode:0x%02x should not be handled here "
- "status:%s",
- opcode, hci_status_code_text(hci_status).c_str());
+ log::error(
+ "Command status for opcode:0x{:02x} should not be handled here "
+ "status:{}",
+ opcode, hci_status_code_text(hci_status));
}
}
@@ -1371,7 +1328,7 @@
// No value needed.
break;
default:
- LOG_WARN("unexpected event:%s", sp_evt_to_text(event).c_str());
+ log::warn("unexpected event:{}", sp_evt_to_text(event));
break;
}
btm_proc_sp_req_evt(event, bda, value);
@@ -1380,7 +1337,7 @@
uint8_t status;
if (evt_len < 1 + BD_ADDR_LEN) {
- LOG_ERROR("malformatted event packet, too short");
+ log::error("malformatted event packet, too short");
return;
}
@@ -1410,7 +1367,7 @@
return;
err_out:
- LOG_ERROR("bogus event packet, too short");
+ log::error("bogus event packet, too short");
}
/*******************************************************************************
@@ -1522,31 +1479,6 @@
* BLE Events
**********************************************/
-static void btu_ble_ll_conn_param_upd_evt(uint8_t* p, uint16_t evt_len) {
- /* LE connection update has completed successfully as a central. */
- /* We can enable the update request if the result is a success. */
- /* extract the HCI handle first */
- uint8_t status;
- uint16_t handle;
- uint16_t interval;
- uint16_t latency;
- uint16_t timeout;
-
- if (evt_len < 9) {
- LOG_ERROR("Malformated event packet, too short");
- return;
- }
-
- STREAM_TO_UINT8(status, p);
- STREAM_TO_UINT16(handle, p);
- STREAM_TO_UINT16(interval, p);
- STREAM_TO_UINT16(latency, p);
- STREAM_TO_UINT16(timeout, p);
-
- acl_ble_update_event_received(static_cast<tHCI_STATUS>(status), handle,
- interval, latency, timeout);
-}
-
static void btu_ble_proc_ltk_req(uint8_t* p, uint16_t evt_len) {
uint16_t ediv, handle;
uint8_t* pp;
@@ -1559,7 +1491,7 @@
// - 8-byte random number
// - 2 byte Encrypted_Diversifier
if (evt_len < 2 + 8 + 2) {
- LOG_ERROR("Event packet too short");
+ log::error("Event packet too short");
return;
}
@@ -1570,48 +1502,6 @@
/* This is empty until an upper layer cares about returning event */
}
-static void btu_ble_data_length_change_evt(uint8_t* p, uint16_t evt_len) {
- uint16_t handle;
- uint16_t tx_data_len;
- uint16_t rx_data_len;
-
- if (!controller_get_interface()->SupportsBleDataPacketLengthExtension()) {
- LOG_WARN("request not supported");
- return;
- }
-
- // 2 bytes each for handle, tx_data_len, TxTimer, rx_data_len
- if (evt_len < 8) {
- LOG_ERROR("Event packet too short");
- return;
- }
-
- STREAM_TO_UINT16(handle, p);
- STREAM_TO_UINT16(tx_data_len, p);
- p += 2; /* Skip the TxTimer */
- STREAM_TO_UINT16(rx_data_len, p);
-
- l2cble_process_data_length_change_event(handle, tx_data_len, rx_data_len);
-}
-
/**********************************************
* End of BLE Events Handler
**********************************************/
-static void btu_ble_rc_param_req_evt(uint8_t* p, uint8_t len) {
- uint16_t handle;
- uint16_t int_min, int_max, latency, timeout;
-
- if (len < 10) {
- LOG_ERROR("bogus event packet, too short");
- return;
- }
-
- STREAM_TO_UINT16(handle, p);
- STREAM_TO_UINT16(int_min, p);
- STREAM_TO_UINT16(int_max, p);
- STREAM_TO_UINT16(latency, p);
- STREAM_TO_UINT16(timeout, p);
-
- l2cble_process_rc_param_request_evt(handle, int_min, int_max, latency,
- timeout);
-}
diff --git a/system/stack/btu/main_thread.cc b/system/stack/btu/main_thread.cc
index f29c4b8..a2cdd7b 100644
--- a/system/stack/btu/main_thread.cc
+++ b/system/stack/btu/main_thread.cc
@@ -24,12 +24,14 @@
#include <base/logging.h>
#include <base/run_loop.h>
#include <base/threading/thread.h>
+#include <bluetooth/log.h>
#include "common/message_loop_thread.h"
#include "include/hardware/bluetooth.h"
#include "os/log.h"
using bluetooth::common::MessageLoopThread;
+using namespace bluetooth;
static MessageLoopThread main_thread("bt_main_thread");
@@ -38,7 +40,7 @@
bt_status_t do_in_main_thread(const base::Location& from_here,
base::OnceClosure task) {
if (!main_thread.DoInThread(from_here, std::move(task))) {
- LOG(ERROR) << __func__ << ": failed from " << from_here.ToString();
+ log::error("failed from {}", from_here.ToString());
return BT_STATUS_FAIL;
}
return BT_STATUS_SUCCESS;
@@ -48,7 +50,7 @@
base::OnceClosure task,
std::chrono::microseconds delay) {
if (!main_thread.DoInThreadDelayed(from_here, std::move(task), delay)) {
- LOG(ERROR) << __func__ << ": failed from " << from_here.ToString();
+ log::error("failed from {}", from_here.ToString());
return BT_STATUS_FAIL;
}
return BT_STATUS_SUCCESS;
@@ -65,13 +67,13 @@
void main_thread_start_up() {
main_thread.StartUp();
if (!main_thread.IsRunning()) {
- LOG(FATAL) << __func__ << ": unable to start btu message loop thread.";
+ log::fatal("unable to start btu message loop thread.");
}
if (!main_thread.EnableRealTimeScheduling()) {
#if defined(__ANDROID__)
- LOG(FATAL) << __func__ << ": unable to enable real time scheduling";
+ log::fatal("unable to enable real time scheduling");
#else
- LOG(ERROR) << __func__ << ": unable to enable real time scheduling";
+ log::error("unable to enable real time scheduling");
#endif
}
}
diff --git a/system/stack/eatt/eatt.cc b/system/stack/eatt/eatt.cc
index 9bd17d8..8a959c4 100644
--- a/system/stack/eatt/eatt.cc
+++ b/system/stack/eatt/eatt.cc
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-#include <base/logging.h>
+#include <bluetooth/log.h>
#include "eatt_impl.h"
#include "stack/include/bt_hdr.h"
@@ -33,7 +33,7 @@
void Start() {
if (eatt_impl_) {
- LOG(ERROR) << "Eatt already started";
+ log::error("Eatt already started");
return;
};
@@ -48,7 +48,7 @@
reg_info_.pL2CA_CreditBasedCollisionInd_Cb = eatt_collision_ind;
if (L2CA_RegisterLECoc(BT_PSM_EATT, reg_info_, BTM_SEC_NONE, {}) == 0) {
- LOG(ERROR) << __func__ << " cannot register EATT";
+ log::error("cannot register EATT");
} else {
eatt_impl_ = std::make_unique<eatt_impl>();
}
@@ -56,7 +56,7 @@
void Stop() {
if (!eatt_impl_) {
- LOG(ERROR) << "Eatt not started";
+ log::error("Eatt not started");
return;
}
eatt_impl_.reset(nullptr);
diff --git a/system/stack/eatt/eatt_impl.h b/system/stack/eatt/eatt_impl.h
index b9983ee..79e6260 100644
--- a/system/stack/eatt/eatt_impl.h
+++ b/system/stack/eatt/eatt_impl.h
@@ -16,6 +16,7 @@
*/
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <map>
#include <vector>
@@ -114,8 +115,8 @@
void remove_channel_by_cid(eatt_device* eatt_dev, uint16_t lcid) {
auto channel = eatt_dev->eatt_channels[lcid];
if (!channel->cl_cmd_q_.empty()) {
- LOG_WARN("Channel %c, for device %s is not empty on disconnection.", lcid,
- channel->bda_.ToString().c_str());
+ log::warn("Channel {:c}, for device {} is not empty on disconnection.",
+ lcid, ADDRESS_TO_LOGGABLE_STR(channel->bda_));
channel->cl_cmd_q_.clear();
}
@@ -144,8 +145,8 @@
* for LE case it is not necessary to read it before establish connection.
* Therefore assume, device supports EATT since we got request to create
* EATT channels. Just create device here. */
- LOG(INFO) << __func__ << " Adding device: " << bda
- << " on incoming EATT creation request";
+ log::info("Adding device: {} on incoming EATT creation request",
+ ADDRESS_TO_LOGGABLE_STR(bda));
eatt_dev = add_eatt_device(bda);
}
@@ -178,7 +179,7 @@
chan->EattChannelSetState(EattChannelState::EATT_CHANNEL_OPENED);
eatt_dev->eatt_tcb_->eatt++;
- LOG(INFO) << __func__ << " Channel connected CID " << loghex(cid);
+ log::info("Channel connected CID {}", loghex(cid));
}
return true;
@@ -190,8 +191,8 @@
eatt_device* eatt_dev = find_device_by_address(bda);
auto num_of_sdu =
stack_config_get_interface()->get_pts_l2cap_ecoc_send_num_of_sdu();
- LOG_INFO(" device %s, num: %d", ADDRESS_TO_LOGGABLE_CSTR(eatt_dev->bda_),
- num_of_sdu);
+ log::info("device {}, num: {}", ADDRESS_TO_LOGGABLE_CSTR(eatt_dev->bda_),
+ num_of_sdu);
if (num_of_sdu <= 0) {
return;
@@ -213,7 +214,7 @@
}
if (cid == 0 || mtu == 0) {
- LOG_ERROR("There is no OPEN cid or MTU is 0");
+ log::error("There is no OPEN cid or MTU is 0");
return;
}
@@ -223,16 +224,17 @@
p_buf->len = mtu;
auto status = L2CA_DataWrite(cid, p_buf);
- LOG_INFO("Data num: %d sent with status %d", i, static_cast<int>(status));
+ log::info("Data num: {} sent with status {}", i,
+ static_cast<int>(status));
}
}
/* This is for the L2CAP ECoC Testing. */
void upper_tester_delay_connect_cb(const RawAddress& bda) {
- LOG_INFO("device %s", ADDRESS_TO_LOGGABLE_CSTR(bda));
+ log::info("device {}", ADDRESS_TO_LOGGABLE_CSTR(bda));
eatt_device* eatt_dev = find_device_by_address(bda);
if (eatt_dev == nullptr) {
- LOG_ERROR(" device is not available");
+ log::error("device is not available");
return;
}
@@ -246,8 +248,8 @@
weak_factory_.GetWeakPtr(), bda),
std::chrono::milliseconds(timeout_ms));
- LOG_INFO("Scheduled peripheral connect eatt for device with status: %d",
- (int)status);
+ log::info("Scheduled peripheral connect eatt for device with status: {}",
+ (int)status);
}
void upper_tester_l2cap_connect_ind(const RawAddress& bda,
@@ -261,8 +263,8 @@
auto key_size = btm_ble_read_sec_key_size(bda);
if (key_size < min_key_size) {
std::vector<uint16_t> empty;
- LOG_ERROR("Insufficient key size (%d<%d) for device %s", key_size,
- min_key_size, ADDRESS_TO_LOGGABLE_CSTR(bda));
+ log::error("Insufficient key size ({}<{}) for device {}", key_size,
+ min_key_size, ADDRESS_TO_LOGGABLE_CSTR(bda));
L2CA_ConnectCreditBasedRsp(bda, identifier, empty,
L2CAP_LE_RESULT_INSUFFICIENT_ENCRYP_KEY_SIZE,
nullptr);
@@ -271,7 +273,7 @@
}
if (!eatt_l2cap_connect_ind_common(bda, lcids, psm, peer_mtu, identifier)) {
- LOG_DEBUG("Reject L2CAP Connection request.");
+ log::debug("Reject L2CAP Connection request.");
return;
}
@@ -292,16 +294,16 @@
base::BindOnce(&eatt_impl::reconfigure_all,
weak_factory_.GetWeakPtr(), bda, 300),
std::chrono::seconds(4));
- LOG_INFO("Scheduled ECOC reconfiguration with status: %d", (int)status);
+ log::info("Scheduled ECOC reconfiguration with status: {}", (int)status);
}
}
void eatt_l2cap_connect_ind(const RawAddress& bda,
std::vector<uint16_t>& lcids, uint16_t psm,
uint16_t peer_mtu, uint8_t identifier) {
- LOG_INFO("Device %s, num of cids: %d, psm 0x%04x, peer_mtu %d",
- ADDRESS_TO_LOGGABLE_CSTR(bda), static_cast<int>(lcids.size()), psm,
- peer_mtu);
+ log::info("Device {}, num of cids: {}, psm 0x{:04x}, peer_mtu {}",
+ ADDRESS_TO_LOGGABLE_CSTR(bda), static_cast<int>(lcids.size()),
+ psm, peer_mtu);
if (!stack_config_get_interface()
->get_pts_connect_eatt_before_encryption() &&
@@ -312,14 +314,14 @@
if (BTM_IsLinkKeyKnown(bda, BT_TRANSPORT_LE)) {
result = L2CAP_LE_RESULT_INSUFFICIENT_ENCRYP;
}
- LOG_ERROR("ACL to device %s is unencrypted.",
- ADDRESS_TO_LOGGABLE_CSTR(bda));
+ log::error("ACL to device {} is unencrypted.",
+ ADDRESS_TO_LOGGABLE_CSTR(bda));
L2CA_ConnectCreditBasedRsp(bda, identifier, empty, result, nullptr);
return;
}
if (stack_config_get_interface()->get_pts_l2cap_ecoc_upper_tester()) {
- LOG_INFO(" Upper tester for the L2CAP ECoC enabled");
+ log::info("Upper tester for the L2CAP ECoC enabled");
return upper_tester_l2cap_connect_ind(bda, lcids, psm, peer_mtu,
identifier);
}
@@ -329,22 +331,21 @@
void eatt_retry_after_collision_if_needed(eatt_device* eatt_dev) {
if (!eatt_dev->collision) {
- LOG_DEBUG("No collision.");
+ log::debug("No collision.");
return;
}
/* We are here, because remote device wanted to create channels when
* Android proceed its own EATT creation. How to handle it is described
* here: BT Core 5.3, Volume 3, Part G, 5.4
*/
- LOG_INFO(
- "EATT collision detected. If we are Central we will retry right "
- "away");
+ log::info(
+ "EATT collision detected. If we are Central we will retry right away");
eatt_dev->collision = false;
uint8_t role = L2CA_GetBleConnRole(eatt_dev->bda_);
if (role == HCI_ROLE_CENTRAL) {
- LOG_INFO("Retrying EATT setup due to previous collision for device %s",
- ADDRESS_TO_LOGGABLE_CSTR(eatt_dev->bda_));
+ log::info("Retrying EATT setup due to previous collision for device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(eatt_dev->bda_));
connect_eatt_wrap(eatt_dev);
} else if (stack_config_get_interface()
->get_pts_eatt_peripheral_collision_support()) {
@@ -357,19 +358,19 @@
/* This is for the L2CAP ECoC Testing. */
void upper_tester_l2cap_connect_cfm(eatt_device* eatt_dev) {
- LOG_INFO("Upper tester for L2CAP Ecoc %s",
- ADDRESS_TO_LOGGABLE_CSTR(eatt_dev->bda_));
+ log::info("Upper tester for L2CAP Ecoc {}",
+ ADDRESS_TO_LOGGABLE_CSTR(eatt_dev->bda_));
if (is_channel_connection_pending(eatt_dev)) {
- LOG_INFO(" Waiting for all channels to be connected");
+ log::info("Waiting for all channels to be connected");
return;
}
if (stack_config_get_interface()->get_pts_l2cap_ecoc_connect_remaining() &&
(static_cast<int>(eatt_dev->eatt_channels.size()) <
L2CAP_CREDIT_BASED_MAX_CIDS)) {
- LOG_INFO("Connecting remaining channels %d",
- L2CAP_CREDIT_BASED_MAX_CIDS -
- static_cast<int>(eatt_dev->eatt_channels.size()));
+ log::info("Connecting remaining channels {}",
+ L2CAP_CREDIT_BASED_MAX_CIDS -
+ static_cast<int>(eatt_dev->eatt_channels.size()));
upper_tester_delay_connect(eatt_dev->bda_, 1000);
return;
}
@@ -378,24 +379,23 @@
void eatt_l2cap_connect_cfm(const RawAddress& bda, uint16_t lcid,
uint16_t peer_mtu, uint16_t result) {
- LOG(INFO) << __func__ << " bda: " << bda << " cid: " << +lcid
- << "peer mtu: " << +peer_mtu << " result " << +result;
+ log::info("bda: {} cid: {}peer mtu: {} result {}",
+ ADDRESS_TO_LOGGABLE_STR(bda), +lcid, +peer_mtu, +result);
eatt_device* eatt_dev = find_device_by_address(bda);
if (!eatt_dev) {
- LOG(ERROR) << __func__ << " unknown device";
+ log::error("unknown device");
return;
}
EattChannel* channel = this->find_channel_by_cid(bda, lcid);
if (!channel) {
- LOG(ERROR) << __func__ << " unknown cid: " << loghex(lcid);
+ log::error("unknown cid: {}", loghex(lcid));
return;
}
if (result != L2CAP_CONN_OK) {
- LOG(ERROR) << __func__
- << " Could not connect CoC result: " << loghex(result);
+ log::error("Could not connect CoC result: {}", loghex(result));
remove_channel_by_cid(eatt_dev, lcid);
/* If there is no channels connected, check if there was collision */
@@ -412,7 +412,7 @@
CHECK(eatt_dev->bda_ == channel->bda_);
eatt_dev->eatt_tcb_->eatt++;
- LOG_INFO("Channel connected CID 0x%04x", lcid);
+ log::info("Channel connected CID 0x{:04x}", lcid);
if (stack_config_get_interface()->get_pts_l2cap_ecoc_upper_tester()) {
upper_tester_l2cap_connect_cfm(eatt_dev);
@@ -422,8 +422,7 @@
void eatt_l2cap_reconfig_completed(const RawAddress& bda, uint16_t lcid,
bool is_local_cfg,
tL2CAP_LE_CFG_INFO* p_cfg) {
- LOG(INFO) << __func__ << "lcid: " << loghex(lcid)
- << " local cfg?: " << is_local_cfg;
+ log::info("lcid: {} local cfg?: {}", loghex(lcid), is_local_cfg);
EattChannel* channel = find_channel_by_cid(bda, lcid);
if (!channel) return;
@@ -432,8 +431,8 @@
channel->EattChannelSetState(EattChannelState::EATT_CHANNEL_OPENED);
if (p_cfg->result != L2CAP_CFG_OK) {
- LOG(INFO) << __func__ << " reconfig failed lcid: " << loghex(lcid)
- << " result: " << loghex(p_cfg->result);
+ log::info("reconfig failed lcid: {} result: {}", loghex(lcid),
+ loghex(p_cfg->result));
return;
}
@@ -457,8 +456,8 @@
void eatt_l2cap_collision_ind(const RawAddress& bda) {
eatt_device* eatt_dev = find_device_by_address(bda);
if (!eatt_dev) {
- LOG_ERROR("Device %s not available anymore:",
- ADDRESS_TO_LOGGABLE_CSTR(bda));
+ log::error("Device {} not available anymore:",
+ ADDRESS_TO_LOGGABLE_CSTR(bda));
return;
}
/* Remote wanted to setup channels as well. Let's retry remote's request
@@ -467,14 +466,13 @@
}
void eatt_l2cap_error_cb(uint16_t lcid, uint16_t reason) {
- LOG(INFO) << __func__ << " cid: " << loghex(lcid) << " reason "
- << loghex(reason);
+ log::info("cid: {} reason {}", loghex(lcid), loghex(reason));
/*TODO: provide address in the L2CAP callback */
EattChannel* channel = find_channel_by_cid(lcid);
if (!channel) {
- LOG(ERROR) << __func__ << "Unknown lcid";
+ log::error("Unknown lcid");
return;
}
@@ -482,17 +480,16 @@
switch (channel->state_) {
case EattChannelState::EATT_CHANNEL_PENDING:
- LOG(ERROR) << "Connecting failed";
+ log::error("Connecting failed");
remove_channel_by_cid(eatt_dev, lcid);
break;
case EattChannelState::EATT_CHANNEL_RECONFIGURING:
/* Just go back to open state */
- LOG(ERROR) << "Reconfig failed";
+ log::error("Reconfig failed");
channel->EattChannelSetState(EattChannelState::EATT_CHANNEL_OPENED);
break;
default:
- LOG(ERROR) << __func__ << "Invalid state: "
- << static_cast<uint8_t>(channel->state_);
+ log::error("Invalid state: {}", static_cast<uint8_t>(channel->state_));
break;
}
@@ -502,10 +499,10 @@
}
void eatt_l2cap_disconnect_ind(uint16_t lcid, bool please_confirm) {
- LOG(INFO) << __func__ << " cid: " << loghex(lcid);
+ log::info("cid: {}", loghex(lcid));
eatt_device* eatt_dev = find_device_by_cid(lcid);
if (!eatt_dev) {
- LOG(ERROR) << __func__ << " unknown cid: " << loghex(lcid);
+ log::error("unknown cid: {}", loghex(lcid));
return;
}
@@ -514,17 +511,16 @@
}
void eatt_l2cap_data_ind(uint16_t lcid, BT_HDR* data_p) {
- LOG(INFO) << __func__ << " cid: " << loghex(lcid);
+ log::info("cid: {}", loghex(lcid));
eatt_device* eatt_dev = find_device_by_cid(lcid);
if (!eatt_dev) {
- LOG(ERROR) << __func__ << " unknown cid: " << loghex(lcid);
+ log::error("unknown cid: {}", loghex(lcid));
return;
}
EattChannel* channel = find_channel_by_cid(eatt_dev->bda_, lcid);
if (!channel) {
- LOG(ERROR) << __func__ << "Received data on closed channel "
- << loghex(lcid);
+ log::error("Received data on closed channel {}", loghex(lcid));
return;
}
@@ -554,8 +550,8 @@
if (stack_config_get_interface()
->get_pts_eatt_peripheral_collision_support()) {
/* For PTS case, lets assume we support only 5 channels */
- LOG_INFO("Number of existing channels %d",
- (int)eatt_dev->eatt_channels.size());
+ log::info("Number of existing channels {}",
+ (int)eatt_dev->eatt_channels.size());
connect_eatt(eatt_dev, L2CAP_CREDIT_BASED_MAX_CIDS -
(int)eatt_dev->eatt_channels.size());
return;
@@ -577,24 +573,23 @@
.number_of_channels = num_of_channels,
};
- LOG_INFO("Connecting device %s, cnt count %d",
- ADDRESS_TO_LOGGABLE_CSTR(eatt_dev->bda_), num_of_channels);
+ log::info("Connecting device {}, cnt count {}",
+ ADDRESS_TO_LOGGABLE_CSTR(eatt_dev->bda_), num_of_channels);
/* Warning! CIDs in Android are unique across the ACL connections */
std::vector<uint16_t> connecting_cids =
L2CA_ConnectCreditBasedReq(psm_, eatt_dev->bda_, &local_coc_cfg);
if (connecting_cids.size() == 0) {
- LOG(ERROR) << "Unable to get cid";
+ log::error("Unable to get cid");
return;
}
- LOG(INFO) << __func__
- << "Successfully sent CoC request, number of channel: "
- << +connecting_cids.size();
+ log::info("Successfully sent CoC request, number of channel: {}",
+ +connecting_cids.size());
for (uint16_t cid : connecting_cids) {
- LOG(INFO) << " \t cid: " << loghex(cid);
+ log::info(" \t cid: {}", loghex(cid));
auto chan = std::make_shared<EattChannel>(eatt_dev->bda_, cid, 0,
eatt_dev->rx_mtu_);
@@ -602,7 +597,7 @@
}
if (eatt_dev->eatt_tcb_) {
- LOG(INFO) << __func__ << " has tcb ? " << eatt_dev->eatt_tcb_;
+ log::info("has tcb ? {}", eatt_dev->eatt_tcb_ == nullptr);
return;
}
@@ -733,7 +728,7 @@
EattChannel* channel = (EattChannel*)data;
tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(channel->bda_, BT_TRANSPORT_LE);
- LOG(WARNING) << __func__ << ": send ack now";
+ log::warn("send ack now");
attp_send_cl_confirmation_msg(*p_tcb, channel->cid_);
}
@@ -741,15 +736,15 @@
EattChannel* channel = (EattChannel*)data;
tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(channel->bda_, BT_TRANSPORT_LE);
- LOG(WARNING) << __func__ << " disconnecting...";
+ log::warn("disconnecting...");
gatt_disconnect(p_tcb);
}
void start_indication_confirm_timer(const RawAddress& bd_addr, uint16_t cid) {
EattChannel* channel = find_eatt_channel_by_cid(bd_addr, cid);
if (!channel) {
- LOG(ERROR) << __func__ << "Unknown cid: " << loghex(cid) << " or device "
- << bd_addr;
+ log::error("Unknown cid: {} or device {}", loghex(cid),
+ ADDRESS_TO_LOGGABLE_STR(bd_addr));
return;
}
@@ -761,8 +756,8 @@
void stop_indication_confirm_timer(const RawAddress& bd_addr, uint16_t cid) {
EattChannel* channel = find_eatt_channel_by_cid(bd_addr, cid);
if (!channel) {
- LOG(ERROR) << __func__ << "Unknown cid: " << loghex(cid) << " or device "
- << bd_addr;
+ log::error("Unknown cid: {} or device {}", loghex(cid),
+ ADDRESS_TO_LOGGABLE_STR(bd_addr));
return;
}
@@ -772,8 +767,8 @@
void start_app_indication_timer(const RawAddress& bd_addr, uint16_t cid) {
EattChannel* channel = find_eatt_channel_by_cid(bd_addr, cid);
if (!channel) {
- LOG(ERROR) << __func__ << "Unknown cid: " << loghex(cid) << " or device "
- << bd_addr;
+ log::error("Unknown cid: {} or device {}", loghex(cid),
+ ADDRESS_TO_LOGGABLE_STR(bd_addr));
return;
}
@@ -784,8 +779,8 @@
void stop_app_indication_timer(const RawAddress& bd_addr, uint16_t cid) {
EattChannel* channel = find_eatt_channel_by_cid(bd_addr, cid);
if (!channel) {
- LOG(ERROR) << __func__ << "Unknown cid: " << loghex(cid) << " or device "
- << bd_addr;
+ log::error("Unknown cid: {} or device {}", loghex(cid),
+ ADDRESS_TO_LOGGABLE_STR(bd_addr));
return;
}
@@ -795,19 +790,19 @@
void reconfigure(const RawAddress& bd_addr, uint16_t cid, uint16_t new_mtu) {
eatt_device* eatt_dev = find_device_by_address(bd_addr);
if (!eatt_dev) {
- LOG(ERROR) << __func__ << "Unknown device " << bd_addr;
+ log::error("Unknown device {}", ADDRESS_TO_LOGGABLE_STR(bd_addr));
return;
}
EattChannel* channel = find_eatt_channel_by_cid(bd_addr, cid);
if (!channel) {
- LOG(ERROR) << __func__ << "Unknown cid: " << loghex(cid) << " or device "
- << bd_addr;
+ log::error("Unknown cid: {} or device {}", loghex(cid),
+ ADDRESS_TO_LOGGABLE_STR(bd_addr));
return;
}
if (new_mtu <= channel->rx_mtu_) {
- LOG(ERROR) << __func__ << "Invalid mtu: " << loghex(new_mtu);
+ log::error("Invalid mtu: {}", loghex(new_mtu));
return;
}
@@ -816,8 +811,8 @@
tL2CAP_LE_CFG_INFO cfg = {.mtu = new_mtu, .mps = eatt_dev->rx_mps_};
if (!L2CA_ReconfigCreditBasedConnsReq(eatt_dev->bda_, cids, &cfg)) {
- LOG(ERROR) << __func__ << "Could not start reconfig cid: " << loghex(cid)
- << " or device " << bd_addr;
+ log::error("Could not start reconfig cid: {} or device {}", loghex(cid),
+ ADDRESS_TO_LOGGABLE_STR(bd_addr));
return;
}
@@ -825,17 +820,17 @@
}
void reconfigure_all(const RawAddress& bd_addr, uint16_t new_mtu) {
- LOG_INFO(" Device %s, new mtu %d", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
- new_mtu);
+ log::info("Device {}, new mtu {}", ADDRESS_TO_LOGGABLE_STR(bd_addr),
+ new_mtu);
eatt_device* eatt_dev = find_device_by_address(bd_addr);
if (!eatt_dev) {
- LOG(ERROR) << __func__ << "Unknown device " << bd_addr;
+ log::error("Unknown device {}", ADDRESS_TO_LOGGABLE_STR(bd_addr));
return;
}
uint8_t num_of_channels = eatt_dev->eatt_channels.size();
if (num_of_channels == 0) {
- LOG(ERROR) << __func__ << "No channels for device " << bd_addr;
+ log::error("No channels for device {}", ADDRESS_TO_LOGGABLE_STR(bd_addr));
return;
}
@@ -849,15 +844,15 @@
}
if (new_mtu <= EATT_MIN_MTU_MPS) {
- LOG(ERROR) << __func__ << "Invalid mtu: " << loghex(new_mtu);
+ log::error("Invalid mtu: {}", loghex(new_mtu));
return;
}
tL2CAP_LE_CFG_INFO cfg = {.mtu = new_mtu, .mps = eatt_dev->rx_mps_};
if (!L2CA_ReconfigCreditBasedConnsReq(eatt_dev->bda_, cids, &cfg)) {
- LOG(ERROR) << __func__ << "Could not start reconfig for device "
- << bd_addr;
+ log::error("Could not start reconfig for device {}",
+ ADDRESS_TO_LOGGABLE_STR(bd_addr));
return;
}
@@ -871,22 +866,21 @@
uint8_t features) {
bool is_eatt_supported = features & BLE_GATT_SVR_SUP_FEAT_EATT_BITMASK;
- LOG(INFO) << __func__ << " " << bd_addr
- << " is_eatt_supported = " << int(is_eatt_supported);
+ log::info("{} is_eatt_supported = {}", ADDRESS_TO_LOGGABLE_STR(bd_addr),
+ int(is_eatt_supported));
if (!is_eatt_supported) return;
eatt_device* eatt_dev = this->find_device_by_address(bd_addr);
if (!eatt_dev) {
- LOG(INFO) << __func__ << " Adding device: " << bd_addr
- << " on supported features callback.";
+ log::info("Adding device: {} on supported features callback.",
+ ADDRESS_TO_LOGGABLE_STR(bd_addr));
eatt_dev = add_eatt_device(bd_addr);
}
if (role != HCI_ROLE_CENTRAL) {
/* TODO For now do nothing, we could run a timer here and start EATT if
* not started by central */
- LOG(INFO)
- << " EATT Should be connected by the central. Let's wait for it.";
+ log::info(" EATT Should be connected by the central. Let's wait for it.");
return;
}
@@ -896,29 +890,29 @@
void disconnect_channel(uint16_t cid) { L2CA_DisconnectReq(cid); }
void disconnect(const RawAddress& bd_addr, uint16_t cid) {
- LOG_INFO(" Device: %s, cid: 0x%04x", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
- cid);
+ log::info("Device: {}, cid: 0x{:04x}", ADDRESS_TO_LOGGABLE_STR(bd_addr),
+ cid);
eatt_device* eatt_dev = find_device_by_address(bd_addr);
if (!eatt_dev) {
- LOG(WARNING) << __func__ << " no eatt device found";
+ log::warn("no eatt device found");
return;
}
if (!eatt_dev->eatt_tcb_) {
LOG_ASSERT(eatt_dev->eatt_channels.size() == 0);
- LOG(WARNING) << __func__ << " no eatt channels found";
+ log::warn("no eatt channels found");
return;
}
if (cid != EATT_ALL_CIDS) {
auto chan = find_channel_by_cid(cid);
if (!chan) {
- LOG_WARN("Cid %d not found for device %s", cid,
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::warn("Cid {} not found for device {}", cid,
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return;
}
- LOG_INFO("Disconnecting cid %d", cid);
+ log::info("Disconnecting cid {}", cid);
disconnect_channel(cid);
remove_channel_by_cid(cid);
return;
@@ -940,9 +934,9 @@
void upper_tester_connect(const RawAddress& bd_addr, eatt_device* eatt_dev,
uint8_t role) {
- LOG_INFO(
- "L2CAP Upper tester enabled, %s (%p), role: %s(%d)",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), eatt_dev,
+ log::info(
+ "L2CAP Upper tester enabled, {} ({}), role: {}({})",
+ ADDRESS_TO_LOGGABLE_STR(bd_addr), fmt::ptr(eatt_dev),
role == HCI_ROLE_CENTRAL ? "HCI_ROLE_CENTRAL" : "HCI_ROLE_PERIPHERAL",
role);
@@ -972,8 +966,8 @@
bd_addr, base::BindOnce(&eatt_impl::supported_features_cb,
weak_factory_.GetWeakPtr(), role)) ==
false) {
- LOG_INFO("Read server supported features failed for device %s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::info("Read server supported features failed for device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
}
}
@@ -982,7 +976,8 @@
uint8_t role = L2CA_GetBleConnRole(bd_addr);
if (role == HCI_ROLE_UNKNOWN) {
- LOG(ERROR) << __func__ << "Could not get device role" << bd_addr;
+ log::error("Could not get device role{}",
+ ADDRESS_TO_LOGGABLE_STR(bd_addr));
return;
}
@@ -991,18 +986,18 @@
return;
}
- LOG_INFO("Device %s, role %s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
- (role == HCI_ROLE_CENTRAL ? "central" : "peripheral"));
+ log::info("Device {}, role {}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ (role == HCI_ROLE_CENTRAL ? "central" : "peripheral"));
if (eatt_dev) {
/* We are reconnecting device we know that support EATT.
* Just connect CoC
*/
- LOG(INFO) << __func__ << " Known device, connect eCoC";
+ log::info("Known device, connect eCoC");
if (role != HCI_ROLE_CENTRAL) {
- LOG(INFO)
- << " EATT Should be connected by the central. Let's wait for it.";
+ log::info(
+ " EATT Should be connected by the central. Let's wait for it.");
return;
}
@@ -1013,8 +1008,8 @@
if (role != HCI_ROLE_CENTRAL) return;
if (gatt_profile_get_eatt_support(bd_addr)) {
- LOG_DEBUG("Eatt is supported for device %s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::debug("Eatt is supported for device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
supported_features_cb(role, bd_addr, BLE_GATT_SVR_SUP_FEAT_EATT_BITMASK);
return;
}
@@ -1024,15 +1019,15 @@
bd_addr, base::BindOnce(&eatt_impl::supported_features_cb,
weak_factory_.GetWeakPtr(), role)) ==
false) {
- LOG_INFO("Read server supported features failed for device %s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::info("Read server supported features failed for device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
}
}
void add_from_storage(const RawAddress& bd_addr) {
eatt_device* eatt_dev = find_device_by_address(bd_addr);
- LOG(INFO) << __func__ << ", restoring: " << bd_addr;
+ log::info("restoring: {}", ADDRESS_TO_LOGGABLE_STR(bd_addr));
if (!eatt_dev) add_eatt_device(bd_addr);
}
diff --git a/system/stack/gap/gap_ble.cc b/system/stack/gap/gap_ble.cc
index b580110..4e99d5d 100644
--- a/system/stack/gap/gap_ble.cc
+++ b/system/stack/gap/gap_ble.cc
@@ -16,8 +16,7 @@
*
******************************************************************************/
-#include <base/logging.h>
-#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <string.h>
#include <array>
@@ -34,8 +33,8 @@
#include "types/bt_transport.h"
#include "types/raw_address.h"
-using base::StringPrintf;
using bluetooth::Uuid;
+using namespace bluetooth;
namespace {
@@ -222,17 +221,16 @@
case GATTS_REQ_TYPE_WRITE_EXEC:
ignore = true;
- VLOG(1) << "Ignore GATTS_REQ_TYPE_WRITE_EXEC";
+ log::verbose("Ignore GATTS_REQ_TYPE_WRITE_EXEC");
break;
case GATTS_REQ_TYPE_MTU:
- VLOG(1) << "Get MTU exchange new mtu size: " << +p_data->mtu;
+ log::verbose("Get MTU exchange new mtu size: {}", +p_data->mtu);
ignore = true;
break;
default:
- VLOG(1) << StringPrintf("Unknown/unexpected LE GAP ATT request: 0x%02x",
- type);
+ log::verbose("Unknown/unexpected LE GAP ATT request: 0x{:02x}", type);
break;
}
@@ -295,19 +293,20 @@
tBT_TRANSPORT) {
tGAP_CLCB* p_clcb = find_clcb_by_bd_addr(bda);
if (p_clcb == NULL) {
- LOG_INFO("No active GAP service found for peer:%s callback:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bda), (connected) ? "Connected" : "Disconnected");
+ log::info("No active GAP service found for peer:{} callback:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bda),
+ (connected) ? "Connected" : "Disconnected");
return;
}
if (connected) {
- LOG_DEBUG("Connected GAP to remote device");
+ log::debug("Connected GAP to remote device");
p_clcb->conn_id = conn_id;
p_clcb->connected = true;
/* start operation is pending */
send_cl_read_request(*p_clcb);
} else {
- LOG_WARN("Disconnected GAP from remote device");
+ log::warn("Disconnected GAP from remote device");
p_clcb->connected = false;
cl_op_cmpl(*p_clcb, false, 0, NULL);
/* clean up clcb */
@@ -545,13 +544,13 @@
tGAP_CLCB* p_clcb = find_clcb_by_bd_addr(peer_bda);
if (p_clcb == NULL) {
- LOG(ERROR) << "Cannot cancel current op is not get dev name";
+ log::error("Cannot cancel current op is not get dev name");
return false;
}
if (!p_clcb->connected) {
if (!GATT_CancelConnect(gatt_if, peer_bda, true)) {
- LOG(ERROR) << "Cannot cancel where No connection id";
+ log::error("Cannot cancel where No connection id");
return false;
}
}
diff --git a/system/stack/gap/gap_conn.cc b/system/stack/gap/gap_conn.cc
index e42ff22..bb1b7c0 100644
--- a/system/stack/gap/gap_conn.cc
+++ b/system/stack/gap/gap_conn.cc
@@ -16,8 +16,7 @@
*
******************************************************************************/
-#include <base/logging.h>
-#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <string.h>
#include "device/include/controller.h"
@@ -32,7 +31,7 @@
#include "stack/include/bt_hdr.h"
#include "types/raw_address.h"
-using base::StringPrintf;
+using namespace bluetooth;
/* Define the GAP Connection Control Block */
typedef struct {
@@ -197,8 +196,8 @@
/* A client MUST have specified a bd addr to connect with */
if (!p_ccb->rem_addr_specified && !is_server) {
gap_release_ccb(p_ccb);
- LOG(ERROR)
- << "GAP ERROR: Client must specify a remote BD ADDR to connect to!";
+ log::error(
+ "GAP ERROR: Client must specify a remote BD ADDR to connect to!");
return (GAP_INVALID_HANDLE);
}
@@ -212,7 +211,7 @@
uint16_t max_mps = controller_get_interface()->get_acl_data_size_ble();
if (le_mps > max_mps) {
- LOG(INFO) << "Limiting MPS to one buffer size - " << max_mps;
+ log::info("Limiting MPS to one buffer size - {}", max_mps);
le_mps = max_mps;
}
p_ccb->local_coc_cfg.mps = le_mps;
@@ -241,8 +240,7 @@
L2CA_Register2(psm, conn.reg_info, false /* enable_snoop */,
&p_ccb->ertm_info, L2CAP_SDU_LENGTH_MAX, 0, security);
if (p_ccb->psm == 0) {
- LOG(ERROR) << StringPrintf("%s: Failure registering PSM 0x%04x", __func__,
- psm);
+ log::error("Failure registering PSM 0x{:04x}", psm);
gap_release_ccb(p_ccb);
return (GAP_INVALID_HANDLE);
}
@@ -252,8 +250,7 @@
p_ccb->psm =
L2CA_RegisterLECoc(psm, conn.reg_info, security, p_ccb->local_coc_cfg);
if (p_ccb->psm == 0) {
- LOG(ERROR) << StringPrintf("%s: Failure registering PSM 0x%04x", __func__,
- psm);
+ log::error("Failure registering PSM 0x{:04x}", psm);
gap_release_ccb(p_ccb);
return (GAP_INVALID_HANDLE);
}
@@ -593,10 +590,10 @@
}
if (xx == GAP_MAX_CONNECTIONS) {
- LOG(WARNING) << "*******";
- LOG(WARNING) << "WARNING: GAP Conn Indication for Unexpected Bd "
- "Addr...Disconnecting";
- LOG(WARNING) << "*******";
+ log::warn("*******");
+ log::warn(
+ "WARNING: GAP Conn Indication for Unexpected Bd Addr...Disconnecting");
+ log::warn("*******");
/* Disconnect because it is an unexpected connection */
if (BTM_UseLeLink(bd_addr)) {
@@ -829,10 +826,8 @@
fixed_queue_enqueue(p_ccb->rx_queue, p_msg);
p_ccb->rx_queue_size += p_msg->len;
- /*
- VLOG(1) << StringPrintf ("gap_data_ind - rx_queue_size=%d, msg len=%d",
- p_ccb->rx_queue_size, p_msg->len);
- */
+ // log::verbose("gap_data_ind - rx_queue_size={}, msg len={}",
+ // p_ccb->rx_queue_size, p_msg->len);
p_ccb->p_callback(p_ccb->gap_handle, GAP_EVT_CONN_DATA_AVAIL, nullptr);
} else {
diff --git a/system/stack/gatt/att_protocol.cc b/system/stack/gatt/att_protocol.cc
index ae86bb9..e6a9601 100644
--- a/system/stack/gatt/att_protocol.cc
+++ b/system/stack/gatt/att_protocol.cc
@@ -23,6 +23,7 @@
******************************************************************************/
#include <base/logging.h>
+#include <bluetooth/log.h>
#include "gatt_int.h"
#include "internal_include/bt_target.h"
@@ -39,6 +40,8 @@
using base::StringPrintf;
using bluetooth::Uuid;
+using namespace bluetooth;
+
/**********************************************************************
* ATT protocl message building utility *
**********************************************************************/
@@ -312,8 +315,7 @@
/* update handle value pair length */
if (op_code == GATT_RSP_READ_BY_TYPE) *p_pair_len = (len + 2);
- LOG(WARNING) << StringPrintf(
- "attribute value too long, to be truncated to %d", len);
+ log::warn("attribute value too long, to be truncated to {}", len);
}
ARRAY_TO_STREAM(p, p_data, len);
@@ -335,18 +337,18 @@
uint16_t l2cap_ret;
if (lcid == L2CAP_ATT_CID) {
- LOG_DEBUG("Sending ATT message on att fixed channel");
+ log::debug("Sending ATT message on att fixed channel");
l2cap_ret = L2CA_SendFixedChnlData(lcid, tcb.peer_bda, p_toL2CAP);
} else {
- LOG_DEBUG("Sending ATT message on lcid:%hu", lcid);
+ log::debug("Sending ATT message on lcid:{}", lcid);
l2cap_ret = (uint16_t)L2CA_DataWrite(lcid, p_toL2CAP);
}
if (l2cap_ret == L2CAP_DW_FAILED) {
- LOG(ERROR) << __func__ << ": failed to write data to L2CAP";
+ log::error("failed to write data to L2CAP");
return GATT_INTERNAL_ERROR;
} else if (l2cap_ret == L2CAP_DW_CONGESTED) {
- VLOG(1) << StringPrintf("ATT congested, message accepted");
+ log::verbose("ATT congested, message accepted");
return GATT_CONGESTED;
}
return GATT_SUCCESS;
@@ -358,16 +360,17 @@
uint16_t offset = 0;
if (payload_size == 0) {
- LOG_ERROR("Cannot send response (op: 0x%02x) due to payload size = 0, %s",
- op_code, ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda));
+ log::error(
+ "Cannot send response (op: 0x{:02x}) due to payload size = 0, {}",
+ op_code, ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda));
return nullptr;
}
switch (op_code) {
case GATT_RSP_READ_BLOB:
case GATT_RSP_PREPARE_WRITE:
- VLOG(1) << StringPrintf(
- "ATT_RSP_READ_BLOB/GATT_RSP_PREPARE_WRITE: len = %d offset = %d",
+ log::verbose(
+ "ATT_RSP_READ_BLOB/GATT_RSP_PREPARE_WRITE: len = {} offset = {}",
p_msg->attr_value.len, p_msg->attr_value.offset);
offset = p_msg->attr_value.offset;
FALLTHROUGH_INTENDED; /* FALLTHROUGH */
@@ -393,7 +396,7 @@
return attp_build_mtu_cmd(op_code, p_msg->mtu);
default:
- LOG(FATAL) << "attp_build_sr_msg: unknown op code = " << +op_code;
+ log::fatal("attp_build_sr_msg: unknown op code = {}", +op_code);
return nullptr;
}
}
@@ -414,11 +417,11 @@
******************************************************************************/
tGATT_STATUS attp_send_sr_msg(tGATT_TCB& tcb, uint16_t cid, BT_HDR* p_msg) {
if (p_msg == NULL) {
- LOG_WARN("Unable to send empty message");
+ log::warn("Unable to send empty message");
return GATT_NO_RESOURCES;
}
- LOG_DEBUG("Sending server response or indication message to client");
+ log::debug("Sending server response or indication message to client");
p_msg->offset = L2CAP_MIN_OFFSET;
return attp_send_msg_to_l2cap(tcb, cid, p_msg);
}
@@ -442,24 +445,24 @@
if (gatt_tcb_is_cid_busy(tcb, p_clcb->cid) &&
cmd_code != GATT_HANDLE_VALUE_CONF) {
if (gatt_cmd_enq(tcb, p_clcb, true, cmd_code, p_cmd)) {
- LOG_DEBUG("Enqueued ATT command %p conn_id=0x%04x, cid=%d", p_clcb,
- p_clcb->conn_id, p_clcb->cid);
+ log::debug("Enqueued ATT command {} conn_id=0x{:04x}, cid={}",
+ fmt::ptr(p_clcb), p_clcb->conn_id, p_clcb->cid);
return GATT_CMD_STARTED;
}
- LOG_ERROR("%s, cid 0x%02x already disconnected",
- ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), p_clcb->cid);
+ log::error("{}, cid 0x{:02x} already disconnected",
+ ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), p_clcb->cid);
return GATT_INTERNAL_ERROR;
}
- LOG_DEBUG(
- "Sending ATT command to l2cap cid:0x%04x eatt_channels:%u transport:%s",
- p_clcb->cid, tcb.eatt, bt_transport_text(tcb.transport).c_str());
+ log::debug(
+ "Sending ATT command to l2cap cid:0x{:04x} eatt_channels:{} transport:{}",
+ p_clcb->cid, tcb.eatt, bt_transport_text(tcb.transport));
tGATT_STATUS att_ret = attp_send_msg_to_l2cap(tcb, p_clcb->cid, p_cmd);
if (att_ret != GATT_CONGESTED && att_ret != GATT_SUCCESS) {
- LOG_WARN(
- "Unable to send ATT command to l2cap layer %p conn_id=0x%04x, cid=%d",
- p_clcb, p_clcb->conn_id, p_clcb->cid);
+ log::warn(
+ "Unable to send ATT command to l2cap layer {} conn_id=0x{:04x}, cid={}",
+ fmt::ptr(p_clcb), p_clcb->conn_id, p_clcb->cid);
return GATT_INTERNAL_ERROR;
}
@@ -467,12 +470,13 @@
return att_ret;
}
- LOG_DEBUG("Starting ATT response timer %p conn_id=0x%04x, cid=%d", p_clcb,
- p_clcb->conn_id, p_clcb->cid);
+ log::debug("Starting ATT response timer {} conn_id=0x{:04x}, cid={}",
+ fmt::ptr(p_clcb), p_clcb->conn_id, p_clcb->cid);
gatt_start_rsp_timer(p_clcb);
if (!gatt_cmd_enq(tcb, p_clcb, false, cmd_code, NULL)) {
- LOG_ERROR("Could not queue sent request. %s, cid 0x%02x already disconnected",
- ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), p_clcb->cid);
+ log::error(
+ "Could not queue sent request. {}, cid 0x{:02x} already disconnected",
+ ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), p_clcb->cid);
return GATT_INTERNAL_ERROR;
}
@@ -530,22 +534,22 @@
uint16_t offset = 0, handle;
if (!p_clcb) {
- LOG_ERROR("Missing p_clcb");
+ log::error("Missing p_clcb");
return GATT_ILLEGAL_PARAMETER;
}
uint16_t payload_size = gatt_tcb_get_payload_size(tcb, p_clcb->cid);
if (payload_size == 0) {
- LOG_ERROR("Cannot send request (op: 0x%02x) due to payload size = 0, %s",
- op_code, ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda));
+ log::error("Cannot send request (op: 0x{:02x}) due to payload size = 0, {}",
+ op_code, ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda));
return GATT_NO_RESOURCES;
}
switch (op_code) {
case GATT_REQ_MTU:
if (p_msg->mtu > GATT_MAX_MTU_SIZE) {
- LOG_WARN(
- "GATT message MTU is larger than max GATT MTU size op_code:%hhu",
+ log::warn(
+ "GATT message MTU is larger than max GATT MTU size op_code:{}",
op_code);
return GATT_ILLEGAL_PARAMETER;
}
@@ -558,7 +562,7 @@
if (!GATT_HANDLE_IS_VALID(p_msg->browse.s_handle) ||
!GATT_HANDLE_IS_VALID(p_msg->browse.e_handle) ||
p_msg->browse.s_handle > p_msg->browse.e_handle) {
- LOG_WARN("GATT message has invalid handle op_code:%hhu", op_code);
+ log::warn("GATT message has invalid handle op_code:{}", op_code);
return GATT_ILLEGAL_PARAMETER;
}
@@ -574,7 +578,7 @@
(op_code == GATT_REQ_READ) ? p_msg->handle : p_msg->read_blob.handle;
/* handle checking */
if (!GATT_HANDLE_IS_VALID(handle)) {
- LOG_WARN("GATT message has invalid handle op_code:%hhu", op_code);
+ log::warn("GATT message has invalid handle op_code:{}", op_code);
return GATT_ILLEGAL_PARAMETER;
}
@@ -588,7 +592,7 @@
case GATT_CMD_WRITE:
case GATT_SIGN_CMD_WRITE:
if (!GATT_HANDLE_IS_VALID(p_msg->attr_value.handle)) {
- LOG_WARN("GATT message has invalid handle op_code:%hhu", op_code);
+ log::warn("GATT message has invalid handle op_code:{}", op_code);
return GATT_ILLEGAL_PARAMETER;
}
@@ -618,9 +622,8 @@
}
if (p_cmd == NULL) {
- LOG_WARN(
- "Unable to build proper GATT message to send to peer device "
- "op_code:%hhu",
+ log::warn(
+ "Unable to build proper GATT message to send to peer device op_code:{}",
op_code);
return GATT_NO_RESOURCES;
}
diff --git a/system/stack/gatt/connection_manager.cc b/system/stack/gatt/connection_manager.cc
index 047988e..2deee85 100644
--- a/system/stack/gatt/connection_manager.cc
+++ b/system/stack/gatt/connection_manager.cc
@@ -22,6 +22,7 @@
#include <base/functional/callback.h>
#include <base/location.h>
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <map>
#include <memory>
@@ -41,6 +42,8 @@
#define DIRECT_CONNECT_TIMEOUT (30 * 1000) /* 30 seconds */
+using namespace bluetooth;
+
constexpr char kBtmLogTag[] = "TA";
struct closure_data {
@@ -50,7 +53,7 @@
static void alarm_closure_cb(void* p) {
closure_data* data = (closure_data*)p;
- VLOG(1) << "executing timer scheduled at %s" << data->posted_from.ToString();
+ log::verbose("executing timer scheduled at {}", data->posted_from.ToString());
std::move(data->user_task).Run();
delete data;
}
@@ -61,7 +64,7 @@
closure_data* data = new closure_data;
data->posted_from = posted_from;
data->user_task = std::move(user_task);
- VLOG(1) << "scheduling timer %s" << data->posted_from.ToString();
+ log::verbose("scheduling timer {}", data->posted_from.ToString());
alarm_set_on_mloop(alarm, interval_ms, alarm_closure_cb, data);
}
@@ -112,7 +115,7 @@
/** background connection device from the list. Returns pointer to the device
* record, or nullptr if not found */
std::set<tAPP_ID> get_apps_connecting_to(const RawAddress& address) {
- LOG_DEBUG("address=%s", ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::debug("address={}", ADDRESS_TO_LOGGABLE_CSTR(address));
auto it = bgconn_dev.find(address);
return (it != bgconn_dev.end()) ? it->second.doing_bg_conn
: std::set<tAPP_ID>();
@@ -135,14 +138,14 @@
}
STREAM_TO_UINT16(uuid, p_tmp);
- LOG_DEBUG("Found UUID 0x%04x", uuid);
+ log::debug("Found UUID 0x{:04x}", uuid);
if (uuid != 0x184E && uuid != 0x1853) {
continue;
}
STREAM_TO_UINT8(announcement_type, p_tmp);
- LOG_DEBUG("Found announcement_type 0x%02x", announcement_type);
+ log::debug("Found announcement_type 0x{:02x}", announcement_type);
if (announcement_type == 0x01) {
return true;
}
@@ -164,21 +167,22 @@
}
if (!IsTargetedAnnouncement(p_eir, eir_len)) {
- LOG_DEBUG("Not a targeted announcement for device %s",
+ log::debug("Not a targeted announcement for device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(addr));
+ return;
+ }
+
+ log::info("Found targeted announcement for device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(addr));
+
+ if (it->second.is_in_accept_list) {
+ log::info("Device {} is already connecting",
ADDRESS_TO_LOGGABLE_CSTR(addr));
return;
}
- LOG_INFO("Found targeted announcement for device %s",
- ADDRESS_TO_LOGGABLE_CSTR(addr));
-
- if (it->second.is_in_accept_list) {
- LOG_INFO("Device %s is already connecting", ADDRESS_TO_LOGGABLE_CSTR(addr));
- return;
- }
-
if (BTM_GetHCIConnHandle(addr, BT_TRANSPORT_LE) != 0xFFFF) {
- LOG_DEBUG("Device %s already connected", ADDRESS_TO_LOGGABLE_CSTR(addr));
+ log::debug("Device {} already connected", ADDRESS_TO_LOGGABLE_CSTR(addr));
return;
}
@@ -193,7 +197,7 @@
}
void target_announcements_filtering_set(bool enable) {
- LOG_DEBUG("enable %d", enable);
+ log::debug("enable {}", enable);
BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty,
(enable ? "Start filtering" : "Stop filtering"));
@@ -211,8 +215,8 @@
*/
bool background_connect_targeted_announcement_add(tAPP_ID app_id,
const RawAddress& address) {
- LOG_INFO("app_id=%d, address=%s", static_cast<int>(app_id),
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::info("app_id={}, address={}", static_cast<int>(app_id),
+ ADDRESS_TO_LOGGABLE_CSTR(address));
bool disable_accept_list = false;
@@ -220,9 +224,9 @@
if (it != bgconn_dev.end()) {
// check if filtering already enabled
if (it->second.doing_targeted_announcements_conn.count(app_id)) {
- LOG_INFO(
- "app_id=%d, already doing targeted announcement filtering to "
- "address=%s",
+ log::info(
+ "app_id={}, already doing targeted announcement filtering to "
+ "address={}",
static_cast<int>(app_id), ADDRESS_TO_LOGGABLE_CSTR(address));
return true;
}
@@ -232,14 +236,14 @@
// Check if connecting
if (!it->second.doing_direct_conn.empty()) {
- LOG_INFO("app_id=%d, address=%s, already in direct connection",
- static_cast<int>(app_id), ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::info("app_id={}, address={}, already in direct connection",
+ static_cast<int>(app_id), ADDRESS_TO_LOGGABLE_CSTR(address));
} else if (!targeted_filtering_enabled &&
!it->second.doing_bg_conn.empty()) {
// device is already in the acceptlist so we would have to remove it
- LOG_INFO(
- "already doing background connection to address=%s. Need to disable "
+ log::info(
+ "already doing background connection to address={}. Need to disable "
"it.",
ADDRESS_TO_LOGGABLE_CSTR(address));
disable_accept_list = true;
@@ -266,23 +270,23 @@
/** Add a device from the background connection list. Returns true if device
* added to the list, or already in list, false otherwise */
bool background_connect_add(uint8_t app_id, const RawAddress& address) {
- LOG_DEBUG("app_id=%d, address=%s", static_cast<int>(app_id),
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::debug("app_id={}, address={}", static_cast<int>(app_id),
+ ADDRESS_TO_LOGGABLE_CSTR(address));
auto it = bgconn_dev.find(address);
bool in_acceptlist = false;
bool is_targeted_announcement_enabled = false;
if (it != bgconn_dev.end()) {
// device already in the acceptlist, just add interested app to the list
if (it->second.doing_bg_conn.count(app_id)) {
- LOG_DEBUG("app_id=%d, already doing background connection to address=%s",
- static_cast<int>(app_id), ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::debug("app_id={}, already doing background connection to address={}",
+ static_cast<int>(app_id), ADDRESS_TO_LOGGABLE_CSTR(address));
return true;
}
// Already in acceptlist ?
if (it->second.is_in_accept_list) {
- LOG_DEBUG("app_id=%d, address=%s, already in accept list",
- static_cast<int>(app_id), ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::debug("app_id={}, address={}, already in accept list",
+ static_cast<int>(app_id), ADDRESS_TO_LOGGABLE_CSTR(address));
in_acceptlist = true;
} else {
is_targeted_announcement_enabled =
@@ -293,11 +297,11 @@
if (!in_acceptlist) {
// the device is not in the acceptlist
if (is_targeted_announcement_enabled) {
- LOG_DEBUG("Targeted announcement enabled, do not add to AcceptList");
+ log::debug("Targeted announcement enabled, do not add to AcceptList");
} else {
if (!BTM_AcceptlistAdd(address)) {
- LOG_WARN("Failed to add device %s to accept list for app %d",
- ADDRESS_TO_LOGGABLE_CSTR(address), static_cast<int>(app_id));
+ log::warn("Failed to add device {} to accept list for app {}",
+ ADDRESS_TO_LOGGABLE_CSTR(address), static_cast<int>(app_id));
return false;
}
bgconn_dev[address].is_in_accept_list = true;
@@ -313,10 +317,10 @@
/** Removes all registrations for connection for given device.
* Returns true if anything was removed, false otherwise */
bool remove_unconditional(const RawAddress& address) {
- LOG_DEBUG("address=%s", ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::debug("address={}", ADDRESS_TO_LOGGABLE_CSTR(address));
auto it = bgconn_dev.find(address);
if (it == bgconn_dev.end()) {
- LOG_WARN("address %s is not found", ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::warn("address {} is not found", ADDRESS_TO_LOGGABLE_CSTR(address));
return false;
}
@@ -329,11 +333,11 @@
* advertising list. Returns true if device was on the list and was
* successfully removed */
bool background_connect_remove(uint8_t app_id, const RawAddress& address) {
- LOG_DEBUG("app_id=%d, address=%s", static_cast<int>(app_id),
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::debug("app_id={}, address={}", static_cast<int>(app_id),
+ ADDRESS_TO_LOGGABLE_CSTR(address));
auto it = bgconn_dev.find(address);
if (it == bgconn_dev.end()) {
- LOG_WARN("address %s is not found", ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::warn("address {} is not found", ADDRESS_TO_LOGGABLE_CSTR(address));
return false;
}
@@ -345,8 +349,8 @@
bool removed_from_ta =
(it->second.doing_targeted_announcements_conn.erase(app_id) > 0);
if (!removed_from_bg_conn && !removed_from_ta) {
- LOG_WARN("Failed to remove background connection app %d for address %s",
- static_cast<int>(app_id), ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::warn("Failed to remove background connection app {} for address {}",
+ static_cast<int>(app_id), ADDRESS_TO_LOGGABLE_CSTR(address));
return false;
}
@@ -356,17 +360,17 @@
}
if (is_anyone_connecting(it)) {
- LOG_DEBUG("some device is still connecting, app_id=%d, address=%s",
- static_cast<int>(app_id), ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::debug("some device is still connecting, app_id={}, address={}",
+ static_cast<int>(app_id), ADDRESS_TO_LOGGABLE_CSTR(address));
/* Check which method should be used now.*/
if (!accept_list_enabled) {
/* Accept list was not used */
if (!it->second.doing_targeted_announcements_conn.empty()) {
/* Keep using filtering */
- LOG_DEBUG(" Keep using target announcement filtering");
+ log::debug("Keep using target announcement filtering");
} else if (!it->second.doing_bg_conn.empty()) {
if (!BTM_AcceptlistAdd(address)) {
- LOG_WARN("Could not re add device to accept list");
+ log::warn("Could not re add device to accept list");
} else {
bgconn_dev[address].is_in_accept_list = true;
}
@@ -397,7 +401,7 @@
/** deregister all related background connetion device. */
void on_app_deregistered(uint8_t app_id) {
- LOG_DEBUG("app_id=%d", static_cast<int>(app_id));
+ log::debug("app_id={}", static_cast<int>(app_id));
auto it = bgconn_dev.begin();
auto end = bgconn_dev.end();
/* update the BG conn device list */
@@ -418,7 +422,7 @@
static void remove_all_clients_with_pending_connections(
const RawAddress& address) {
- LOG_DEBUG("address=%s", ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::debug("address={}", ADDRESS_TO_LOGGABLE_CSTR(address));
auto it = bgconn_dev.find(address);
while (it != bgconn_dev.end() && !it->second.doing_direct_conn.empty()) {
uint8_t app_id = it->second.doing_direct_conn.begin()->first;
@@ -428,14 +432,14 @@
}
void on_connection_complete(const RawAddress& address) {
- LOG_INFO("Le connection completed to device:%s",
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::info("Le connection completed to device:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(address));
remove_all_clients_with_pending_connections(address);
}
void on_connection_timed_out_from_shim(const RawAddress& address) {
- LOG_INFO("Connection failed %s", ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::info("Connection failed {}", ADDRESS_TO_LOGGABLE_CSTR(address));
on_connection_timed_out(0x00, address);
}
@@ -450,8 +454,8 @@
}
void wl_direct_connect_timeout_cb(uint8_t app_id, const RawAddress& address) {
- LOG_DEBUG("app_id=%d, address=%s", static_cast<int>(app_id),
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::debug("app_id={}, address={}", static_cast<int>(app_id),
+ ADDRESS_TO_LOGGABLE_CSTR(address));
on_connection_timed_out(app_id, address);
// TODO: this would free the timer, from within the timer callback, which is
@@ -462,22 +466,22 @@
/** Add a device to the direct connection list. Returns true if device
* added to the list, false otherwise */
bool direct_connect_add(uint8_t app_id, const RawAddress& address) {
- LOG_DEBUG("app_id=%d, address=%s", static_cast<int>(app_id),
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::debug("app_id={}, address={}", static_cast<int>(app_id),
+ ADDRESS_TO_LOGGABLE_CSTR(address));
bool in_acceptlist = false;
auto it = bgconn_dev.find(address);
if (it != bgconn_dev.end()) {
// app already trying to connect to this particular device
if (it->second.doing_direct_conn.count(app_id)) {
- LOG(INFO) << "direct connect attempt from app_id=" << loghex(app_id)
- << " already in progress";
+ log::info("direct connect attempt from app_id={} already in progress",
+ loghex(app_id));
return false;
}
// are we already in the acceptlist ?
if (it->second.is_in_accept_list) {
- LOG_WARN("Background connection attempt already in progress app_id=%x",
- app_id);
+ log::warn("Background connection attempt already in progress app_id={:x}",
+ app_id);
in_acceptlist = true;
}
}
@@ -485,7 +489,7 @@
if (!in_acceptlist) {
if (!BTM_AcceptlistAdd(address, true)) {
// if we can't add to acceptlist, turn parameters back to slow.
- LOG_WARN("Unable to add le device to acceptlist");
+ log::warn("Unable to add le device to acceptlist");
return false;
}
bgconn_dev[address].is_in_accept_list = true;
@@ -510,19 +514,19 @@
bool direct_connect_remove(uint8_t app_id, const RawAddress& address,
bool connection_timeout) {
- LOG_DEBUG("app_id=%d, address=%s", static_cast<int>(app_id),
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::debug("app_id={}, address={}", static_cast<int>(app_id),
+ ADDRESS_TO_LOGGABLE_CSTR(address));
auto it = bgconn_dev.find(address);
if (it == bgconn_dev.end()) {
- LOG_WARN("Unable to find background connection to remove peer:%s",
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::warn("Unable to find background connection to remove peer:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(address));
return false;
}
auto app_it = it->second.doing_direct_conn.find(app_id);
if (app_it == it->second.doing_direct_conn.end()) {
- LOG_WARN("Unable to find direct connection to remove peer:%s",
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::warn("Unable to find direct connection to remove peer:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(address));
return false;
}
@@ -540,8 +544,8 @@
* the allow list.
*/
if (!BTM_AcceptlistAdd(address)) {
- LOG_WARN(
- "Failed to re-add device %s to accept list after connection "
+ log::warn(
+ "Failed to re-add device {} to accept list after connection "
"timeout",
ADDRESS_TO_LOGGABLE_CSTR(address));
}
diff --git a/system/stack/gatt/gatt_api.cc b/system/stack/gatt/gatt_api.cc
index 6c079e4..0061b96 100644
--- a/system/stack/gatt/gatt_api.cc
+++ b/system/stack/gatt/gatt_api.cc
@@ -27,6 +27,7 @@
#include <base/logging.h>
#include <base/strings/string_number_conversions.h>
+#include <bluetooth/log.h>
#include <string>
@@ -52,6 +53,7 @@
#include "types/raw_address.h"
using namespace bluetooth::legacy::stack::sdp;
+using namespace bluetooth;
using bluetooth::Uuid;
@@ -115,7 +117,7 @@
// if present, Characteristic Extended Properties takes one handle
if (el->properties & GATT_CHAR_PROP_BIT_EXT_PROP) db_size++;
} else {
- LOG(ERROR) << __func__ << ": Unknown element type: " << el->type;
+ log::error("Unknown element type: {}", el->type);
}
return db_size;
@@ -175,10 +177,10 @@
bool is_pri = (service->type == BTGATT_DB_PRIMARY_SERVICE) ? true : false;
Uuid svc_uuid = service->uuid;
- LOG(INFO) << __func__;
+ log::info("");
if (!p_reg) {
- LOG(ERROR) << "Inavlid gatt_if=" << +gatt_if;
+ log::error("Inavlid gatt_if={}", gatt_if);
return GATT_INTERNAL_ERROR;
}
@@ -207,8 +209,7 @@
/* check for space */
if (num_handles > (0xFFFF - s_hdl + 1)) {
- LOG(ERROR) << __func__ << ": no handles, s_hdl=" << +s_hdl
- << " needed=" << num_handles;
+ log::error("no handles, s_hdl={} needed={}", s_hdl, num_handles);
return GATT_INTERNAL_ERROR;
}
@@ -226,11 +227,10 @@
gatts_init_service_db(list.svc_db, svc_uuid, is_pri, s_hdl, num_handles);
- VLOG(1) << __func__ << ": handles needed=" << num_handles
- << ", s_hdl=" << loghex(list.asgn_range.s_handle)
- << ", e_hdl=" << loghex(list.asgn_range.e_handle)
- << ", uuid=" << list.asgn_range.svc_uuid
- << ", is_primary=" << +list.asgn_range.is_primary;
+ log::verbose("handles needed={}, s_hdl={}, e_hdl={}, uuid={}, is_primary={}",
+ num_handles, loghex(list.asgn_range.s_handle),
+ loghex(list.asgn_range.e_handle), list.asgn_range.svc_uuid,
+ list.asgn_range.is_primary);
service->attribute_handle = s_hdl;
@@ -244,16 +244,16 @@
!(el->permissions & GATT_WRITE_SIGNED_PERM)) ||
((el->permissions & GATT_WRITE_SIGNED_PERM) &&
!(el->properties & GATT_CHAR_PROP_BIT_AUTH))) {
- VLOG(1) << "Invalid configuration property=" << loghex(el->properties)
- << ", perm=" << loghex(el->permissions);
+ log::verbose("Invalid configuration property={}, perm={}",
+ loghex(el->properties), loghex(el->permissions));
return GATT_INTERNAL_ERROR;
}
if (is_gatt_attr_type(uuid)) {
- LOG(ERROR) << __func__
- << ": attept to add characteristic with UUID equal to GATT "
- "Attribute Type "
- << uuid;
+ log::error(
+ "attept to add characteristic with UUID equal to GATT Attribute "
+ "Type {}",
+ uuid);
return GATT_INTERNAL_ERROR;
}
@@ -267,10 +267,10 @@
} else if (el->type == BTGATT_DB_DESCRIPTOR) {
if (is_gatt_attr_type(uuid)) {
- LOG(ERROR) << __func__
- << ": attept to add descriptor with UUID equal to GATT "
- "Attribute Type "
- << uuid;
+ log::error(
+ "attept to add descriptor with UUID equal to GATT Attribute Type "
+ "{}",
+ uuid);
return GATT_INTERNAL_ERROR;
}
@@ -280,7 +280,7 @@
tGATT_HDL_LIST_ELEM* p_incl_decl;
p_incl_decl = gatt_find_hdl_buffer_by_handle(el->attribute_handle);
if (p_incl_decl == nullptr) {
- VLOG(1) << "Included Service not created";
+ log::verbose("Included Service not created");
return GATT_INTERNAL_ERROR;
}
@@ -290,7 +290,7 @@
}
}
- LOG(INFO) << __func__ << ": service parsed correctly, now starting";
+ log::info("service parsed correctly, now starting");
/*this is a new application service start */
@@ -327,9 +327,9 @@
gatt_update_last_srv_info();
- VLOG(1) << __func__ << ": allocated el s_hdl=" << loghex(elem.s_hdl)
- << ", e_hdl=" << loghex(elem.e_hdl) << ", type=" << loghex(elem.type)
- << ", sdp_hdl=" << loghex(elem.sdp_handle);
+ log::verbose("allocated el s_hdl={}, e_hdl={}, type={}, sdp_hdl={}",
+ loghex(elem.s_hdl), loghex(elem.e_hdl), loghex(elem.type),
+ loghex(elem.sdp_handle));
gatt_update_for_database_change();
gatt_proc_srv_chg();
@@ -344,7 +344,7 @@
if (p_this_uuid && app_uuid128 == info.app_uuid &&
*p_svc_uuid == *p_this_uuid && (start_handle == info.s_hdl)) {
- LOG(ERROR) << "Active Service Found: " << *p_svc_uuid;
+ log::error("Active Service Found: {}", *p_svc_uuid);
return true;
}
}
@@ -367,18 +367,18 @@
******************************************************************************/
bool GATTS_DeleteService(tGATT_IF gatt_if, Uuid* p_svc_uuid,
uint16_t svc_inst) {
- VLOG(1) << __func__;
+ log::verbose("");
tGATT_REG* p_reg = gatt_get_regcb(gatt_if);
if (p_reg == NULL) {
- LOG(ERROR) << "Applicaiton not foud";
+ log::error("Applicaiton not foud");
return false;
}
auto it =
gatt_find_hdl_buffer_by_app_id(p_reg->app_uuid128, p_svc_uuid, svc_inst);
if (it == gatt_cb.hdl_list_info->end()) {
- LOG(ERROR) << "No Service found";
+ log::error("No Service found");
return false;
}
@@ -389,8 +389,9 @@
gatt_update_for_database_change();
gatt_proc_srv_chg();
- VLOG(1) << "released handles s_hdl=" << loghex(it->asgn_range.s_handle)
- << ", e_hdl=" << loghex(it->asgn_range.e_handle);
+ log::verbose("released handles s_hdl={}, e_hdl={}",
+ loghex(it->asgn_range.s_handle),
+ loghex(it->asgn_range.e_handle));
if ((it->asgn_range.s_handle >= gatt_cb.hdl_cfg.app_start_hdl) &&
gatt_cb.cb_info.p_nv_save_callback)
@@ -412,12 +413,11 @@
*
******************************************************************************/
void GATTS_StopService(uint16_t service_handle) {
- LOG(INFO) << __func__ << ": service = " << loghex(service_handle);
+ log::info("service = {}", loghex(service_handle));
auto it = gatt_sr_find_i_rcb_by_handle(service_handle);
if (it == gatt_cb.srv_list_info->end()) {
- LOG(ERROR) << __func__ << ": service_handle=" << loghex(service_handle)
- << " is not in use";
+ log::error("service_handle={} is not in use", loghex(service_handle));
return;
}
@@ -451,9 +451,9 @@
tGATT_REG* p_reg = gatt_get_regcb(gatt_if);
tGATT_TCB* p_tcb = gatt_get_tcb_by_idx(tcb_idx);
- VLOG(1) << __func__;
+ log::verbose("");
if ((p_reg == NULL) || (p_tcb == NULL)) {
- LOG(ERROR) << __func__ << ": Unknown conn_id=" << loghex(conn_id);
+ log::error("Unknown conn_id={}", loghex(conn_id));
return (tGATT_STATUS)GATT_INVALID_CONN_ID;
}
@@ -471,7 +471,7 @@
if (!gatt_tcb_get_cid_available_for_indication(p_tcb, p_reg->eatt_support,
&indicate_handle_p, &cid)) {
- VLOG(1) << "Add a pending indication";
+ log::verbose("Add a pending indication");
gatt_add_pending_ind(p_tcb, &indication);
return GATT_SUCCESS;
}
@@ -495,7 +495,7 @@
#if (GATT_UPPER_TESTER_MULT_VARIABLE_LENGTH_NOTIF == TRUE)
static tGATT_STATUS GATTS_HandleMultileValueNotification(
tGATT_TCB* p_tcb, std::vector<tGATT_VALUE> gatt_notif_vector) {
- LOG_INFO("");
+ log::info("");
uint16_t cid = gatt_tcb_get_att_cid(*p_tcb, true /* eatt support */);
uint16_t payload_size = gatt_tcb_get_payload_size(*p_tcb, cid);
@@ -510,7 +510,7 @@
p_buf->offset = L2CAP_MIN_OFFSET;
p_buf->len = 1;
for (auto notif : gatt_notif_vector) {
- LOG_INFO("Adding handle: 0x%04x, val len %d", notif.handle, notif.len);
+ log::info("Adding handle: 0x{:04x}, val len {}", notif.handle, notif.len);
UINT16_TO_STREAM(p, notif.handle);
p_buf->len += 2;
UINT16_TO_STREAM(p, notif.len);
@@ -519,7 +519,7 @@
p_buf->len += notif.len;
}
- LOG_INFO("Total len: %d", p_buf->len);
+ log::info("Total len: {}", p_buf->len);
return attp_send_sr_msg(*p_tcb, cid, p_buf);
}
@@ -553,10 +553,10 @@
tGATT_VALUE* p_gatt_notif;
#endif
- VLOG(1) << __func__;
+ log::verbose("");
if ((p_reg == NULL) || (p_tcb == NULL)) {
- LOG(ERROR) << __func__ << "Unknown conn_id: " << conn_id;
+ log::error("Unknown conn_id: {}", conn_id);
return (tGATT_STATUS)GATT_INVALID_CONN_ID;
}
@@ -569,7 +569,7 @@
if (stack_config_get_interface()->get_pts_force_eatt_for_notifications() &&
gatt_sr_is_cl_multi_variable_len_notif_supported(*p_tcb)) {
if (cached_tcb_idx == 0xFF) {
- LOG_INFO("Storing first notification");
+ log::info("Storing first notification");
p_gatt_notif = &gatt_notif_vector[0];
p_gatt_notif->handle = attr_handle;
@@ -583,7 +583,7 @@
}
if (cached_tcb_idx == tcb_idx) {
- LOG_INFO("Storing second notification");
+ log::info("Storing second notification");
cached_tcb_idx = 0xFF;
p_gatt_notif = &gatt_notif_vector[1];
@@ -596,8 +596,8 @@
return GATTS_HandleMultileValueNotification(p_tcb, gatt_notif_vector);
}
- LOG_ERROR("PTS Mode: Invalid tcb_idx: %d, cached_tcb_idx: %d", tcb_idx,
- cached_tcb_idx);
+ log::error("PTS Mode: Invalid tcb_idx: {}, cached_tcb_idx: {}", tcb_idx,
+ cached_tcb_idx);
}
#endif
@@ -645,20 +645,18 @@
tGATT_REG* p_reg = gatt_get_regcb(gatt_if);
tGATT_TCB* p_tcb = gatt_get_tcb_by_idx(tcb_idx);
- VLOG(1) << __func__ << ": conn_id=" << loghex(conn_id)
- << ", trans_id=" << loghex(trans_id)
- << ", status=" << loghex(static_cast<uint8_t>(status));
+ log::verbose("conn_id={}, trans_id={}, status={}", loghex(conn_id),
+ loghex(trans_id), loghex(static_cast<uint8_t>(status)));
if ((p_reg == NULL) || (p_tcb == NULL)) {
- LOG(ERROR) << "Unknown conn_id=" << loghex(conn_id);
+ log::error("Unknown conn_id={}", loghex(conn_id));
return (tGATT_STATUS)GATT_INVALID_CONN_ID;
}
tGATT_SR_CMD* sr_res_p = gatt_sr_get_cmd_by_trans_id(p_tcb, trans_id);
if (!sr_res_p) {
- LOG(ERROR) << "conn_id=" << loghex(conn_id)
- << " waiting for other op_code ";
+ log::error("conn_id={} waiting for other op_code ", loghex(conn_id));
return (GATT_WRONG_STATE);
}
@@ -697,9 +695,9 @@
if ((p_tcb == NULL) || (p_reg == NULL) || (mtu < GATT_DEF_BLE_MTU_SIZE) ||
(mtu > GATT_MAX_MTU_SIZE)) {
- LOG_WARN(
- "Unable to configure ATT mtu size illegal parameter conn_id:%hu "
- "mtu:%hu tcb:%s reg:%s",
+ log::warn(
+ "Unable to configure ATT mtu size illegal parameter conn_id:{} mtu:{} "
+ "tcb:{} reg:{}",
conn_id, mtu, (p_tcb == nullptr) ? "BAD" : "ok",
(p_reg == nullptr) ? "BAD" : "ok");
return GATT_ILLEGAL_PARAMETER;
@@ -712,7 +710,7 @@
tGATT_CLCB* p_clcb = gatt_clcb_alloc(conn_id);
if (!p_clcb) {
- LOG_WARN("Unable to allocate connection link control block");
+ log::warn("Unable to allocate connection link control block");
return GATT_NO_RESOURCES;
}
@@ -728,8 +726,8 @@
* default MTU in the request. */
gatt_cl_msg.mtu = gatt_get_local_mtu();
- LOG_INFO("Configuring ATT mtu size conn_id:%hu mtu:%hu user mtu %hu", conn_id,
- gatt_cl_msg.mtu, mtu);
+ log::info("Configuring ATT mtu size conn_id:{} mtu:{} user mtu {}", conn_id,
+ gatt_cl_msg.mtu, mtu);
auto result =
attp_send_cl_msg(*p_clcb->p_tcb, p_clcb, GATT_REQ_MTU, &gatt_cl_msg);
@@ -769,24 +767,24 @@
tBT_TRANSPORT transport,
uint16_t conn_id,
uint16_t* current_mtu) {
- LOG_INFO("%s conn_id=0x%04x", remote_bda.ToString().c_str(), conn_id);
+ log::info("{} conn_id=0x{:04x}", remote_bda.ToString(), conn_id);
*current_mtu = GATT_DEF_BLE_MTU_SIZE;
if (transport == BT_TRANSPORT_BR_EDR) {
- LOG_ERROR("Device %s connected over BR/EDR",
- ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
+ log::error("Device {} connected over BR/EDR",
+ ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
return MTU_EXCHANGE_NOT_ALLOWED;
}
tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(remote_bda, transport);
if (!p_tcb) {
- LOG_ERROR("Device %s is not connected ",
- ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
+ log::error("Device {} is not connected ",
+ ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
return MTU_EXCHANGE_DEVICE_DISCONNECTED;
}
if (gatt_is_pending_mtu_exchange(p_tcb)) {
- LOG_DEBUG("Continue MTU pending for other client.");
+ log::debug("Continue MTU pending for other client.");
/* MTU Exchange is in progress, started by other GATT Client.
* Wait until it is completed.
*/
@@ -796,8 +794,8 @@
uint16_t mtu = gatt_get_mtu(remote_bda, transport);
if (mtu == GATT_DEF_BLE_MTU_SIZE || mtu == 0) {
- LOG_DEBUG("MTU not yet updated for %s",
- ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
+ log::debug("MTU not yet updated for {}",
+ ADDRESS_TO_LOGGABLE_CSTR(remote_bda));
return MTU_EXCHANGE_NOT_DONE_YET;
}
@@ -821,19 +819,19 @@
void GATTC_UpdateUserAttMtuIfNeeded(const RawAddress& remote_bda,
tBT_TRANSPORT transport,
uint16_t user_mtu) {
- LOG_INFO("%s, mtu=%hu", ADDRESS_TO_LOGGABLE_CSTR(remote_bda), user_mtu);
+ log::info("{}, mtu={}", ADDRESS_TO_LOGGABLE_CSTR(remote_bda), user_mtu);
tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(remote_bda, transport);
if (!p_tcb) {
- LOG_WARN("Transport control block not found");
+ log::warn("Transport control block not found");
return;
}
- LOG_INFO("%s, current mtu: %d, max_user_mtu:%d, user_mtu: %d",
- ADDRESS_TO_LOGGABLE_CSTR(remote_bda), p_tcb->payload_size,
- p_tcb->max_user_mtu, user_mtu);
+ log::info("{}, current mtu: {}, max_user_mtu:{}, user_mtu: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(remote_bda), p_tcb->payload_size,
+ p_tcb->max_user_mtu, user_mtu);
if (p_tcb->payload_size < user_mtu) {
- LOG_INFO("User requested more than what GATT can handle. Trim it.");
+ log::info("User requested more than what GATT can handle. Trim it.");
user_mtu = p_tcb->payload_size;
}
@@ -883,8 +881,8 @@
tGATT_REG* p_reg = gatt_get_regcb(gatt_if);
if ((p_tcb == NULL) || (p_reg == NULL) || (disc_type >= GATT_DISC_MAX)) {
- LOG(ERROR) << __func__ << " Illegal param: disc_type=" << +disc_type
- << " conn_id=" << loghex(conn_id);
+ log::error("Illegal param: disc_type={} conn_id={}", disc_type,
+ loghex(conn_id));
return GATT_ILLEGAL_PARAMETER;
}
@@ -892,19 +890,17 @@
!GATT_HANDLE_IS_VALID(end_handle) ||
/* search by type does not have a valid UUID param */
(disc_type == GATT_DISC_SRVC_BY_UUID && uuid.IsEmpty())) {
- LOG(WARNING) << __func__ << " Illegal parameter conn_id=" << loghex(conn_id)
- << ", disc_type=" << +disc_type
- << ", s_handle=" << loghex(start_handle)
- << ", e_handle=" << loghex(end_handle);
+ log::warn(
+ "Illegal parameter conn_id={}, disc_type={}, s_handle={}, e_handle={}",
+ loghex(conn_id), disc_type, loghex(start_handle), loghex(end_handle));
return GATT_ILLEGAL_PARAMETER;
}
tGATT_CLCB* p_clcb = gatt_clcb_alloc(conn_id);
if (!p_clcb) {
- LOG(WARNING) << __func__ << " No resources conn_id=" << loghex(conn_id)
- << ", disc_type=" << +disc_type
- << ", s_handle=" << loghex(start_handle)
- << ", e_handle=" << loghex(end_handle);
+ log::warn("No resources conn_id={}, disc_type={}, s_handle={}, e_handle={}",
+ loghex(conn_id), disc_type, loghex(start_handle),
+ loghex(end_handle));
return GATT_NO_RESOURCES;
}
@@ -914,10 +910,9 @@
p_clcb->e_handle = end_handle;
p_clcb->uuid = uuid;
- LOG(INFO) << __func__ << " conn_id=" << loghex(conn_id)
- << ", disc_type=" << +disc_type
- << ", s_handle=" << loghex(start_handle)
- << ", e_handle=" << loghex(end_handle);
+ log::info("conn_id={}, disc_type={}, s_handle={}, e_handle={}",
+ loghex(conn_id), disc_type, loghex(start_handle),
+ loghex(end_handle));
gatt_act_discovery(p_clcb);
return GATT_SUCCESS;
@@ -954,13 +949,12 @@
static int cached_tcb_idx = -1;
#endif
- VLOG(1) << __func__ << ": conn_id=" << loghex(conn_id)
- << ", type=" << loghex(type);
+ log::verbose("conn_id={}, type={}", loghex(conn_id), loghex(type));
if ((p_tcb == NULL) || (p_reg == NULL) || (p_read == NULL) ||
((type >= GATT_READ_MAX) || (type == 0))) {
- LOG(ERROR) << ": illegal param: conn_id=" << loghex(conn_id)
- << "type=" << loghex(type);
+ log::error("illegal param: conn_id={}, type={}", loghex(conn_id),
+ loghex(type));
return GATT_ILLEGAL_PARAMETER;
}
@@ -992,15 +986,15 @@
}
case GATT_READ_BY_HANDLE:
#if (GATT_UPPER_TESTER_MULT_VARIABLE_LENGTH_READ == TRUE)
- LOG_INFO("Upper tester: Handle read 0x%04x", p_read->by_handle.handle);
+ log::info("Upper tester: Handle read 0x{:04x}", p_read->by_handle.handle);
/* This is upper tester for the Multi Read stuff as this is mandatory for
* EATT, even Android is not making use of this operation :/ */
if (cached_tcb_idx < 0) {
cached_tcb_idx = tcb_idx;
- LOG_INFO("Upper tester: Read multiple - first read");
+ log::info("Upper tester: Read multiple - first read");
cached_read_handle = p_read->by_handle.handle;
} else if (cached_tcb_idx == tcb_idx) {
- LOG_INFO("Upper tester: Read multiple - second read");
+ log::info("Upper tester: Read multiple - second read");
cached_tcb_idx = -1;
tGATT_READ_MULTI* p_read_multi =
(tGATT_READ_MULTI*)osi_malloc(sizeof(tGATT_READ_MULTI));
@@ -1062,8 +1056,8 @@
if ((p_tcb == NULL) || (p_reg == NULL) || (p_write == NULL) ||
((type != GATT_WRITE) && (type != GATT_WRITE_PREPARE) &&
(type != GATT_WRITE_NO_RSP))) {
- LOG(ERROR) << __func__ << " Illegal param: conn_id=" << loghex(conn_id)
- << ", type=" << loghex(type);
+ log::error("Illegal param: conn_id={}, type={}", loghex(conn_id),
+ loghex(type));
return GATT_ILLEGAL_PARAMETER;
}
@@ -1108,11 +1102,10 @@
tGATT_TCB* p_tcb = gatt_get_tcb_by_idx(tcb_idx);
tGATT_REG* p_reg = gatt_get_regcb(gatt_if);
- VLOG(1) << __func__ << ": conn_id=" << loghex(conn_id)
- << ", is_execute=" << +is_execute;
+ log::verbose("conn_id={}, is_execute={}", loghex(conn_id), is_execute);
if ((p_tcb == NULL) || (p_reg == NULL)) {
- LOG(ERROR) << " Illegal param: conn_id=" << loghex(conn_id);
+ log::error(" Illegal param: conn_id={}", loghex(conn_id));
return GATT_ILLEGAL_PARAMETER;
}
@@ -1140,21 +1133,22 @@
*
******************************************************************************/
tGATT_STATUS GATTC_SendHandleValueConfirm(uint16_t conn_id, uint16_t cid) {
- LOG_INFO(" conn_id=0x%04x , cid=0x%04x", conn_id, cid);
+ log::info("conn_id=0x{:04x} , cid=0x{:04x}", conn_id, cid);
tGATT_TCB* p_tcb = gatt_get_tcb_by_idx(GATT_GET_TCB_IDX(conn_id));
if (!p_tcb) {
- LOG(ERROR) << "Unknown conn_id=" << loghex(conn_id);
+ log::error("Unknown conn_id={}", loghex(conn_id));
return GATT_ILLEGAL_PARAMETER;
}
if (p_tcb->ind_count == 0) {
- LOG_INFO("conn_id: 0x%04x ignored not waiting for indicaiton ack", conn_id);
+ log::info("conn_id: 0x{:04x} ignored not waiting for indicaiton ack",
+ conn_id);
return GATT_SUCCESS;
}
- LOG_INFO("Received confirmation, ind_count= %d, sending confirmation",
- p_tcb->ind_count);
+ log::info("Received confirmation, ind_count= {}, sending confirmation",
+ p_tcb->ind_count);
/* Just wait for first confirmation.*/
p_tcb->ind_count = 0;
@@ -1206,8 +1200,8 @@
}
}
- LOG_INFO("idle_timeout=%d, is_active=%d, status=%d (1-OK 0-not performed)",
- idle_tout, is_active, +status);
+ log::info("idle_timeout={}, is_active={}, status={} (1-OK 0-not performed)",
+ idle_tout, is_active, status);
}
/*******************************************************************************
@@ -1234,14 +1228,14 @@
for (i_gatt_if = 0, p_reg = gatt_cb.cl_rcb; i_gatt_if < GATT_MAX_APPS;
i_gatt_if++, p_reg++) {
if (p_reg->in_use && p_reg->app_uuid128 == app_uuid128) {
- LOG_ERROR("Application already registered, uuid=%s",
- app_uuid128.ToString().c_str());
+ log::error("Application already registered, uuid={}",
+ app_uuid128.ToString());
return 0;
}
}
if (stack_config_get_interface()->get_pts_use_eatt_for_all_services()) {
- LOG_INFO("PTS: Force to use EATT for servers");
+ log::info("PTS: Force to use EATT for servers");
eatt_support = true;
}
@@ -1256,15 +1250,14 @@
p_reg->in_use = true;
p_reg->eatt_support = eatt_support;
p_reg->name = name;
- LOG_INFO("Allocated name:%s uuid:%s gatt_if:%hhu eatt_support:%u",
- name.c_str(), app_uuid128.ToString().c_str(), gatt_if,
- eatt_support);
+ log::info("Allocated name:{} uuid:{} gatt_if:{} eatt_support:{}", name,
+ app_uuid128.ToString(), gatt_if, eatt_support);
return gatt_if;
}
}
- LOG_ERROR("Unable to register GATT client, MAX client reached: %d",
- GATT_MAX_APPS);
+ log::error("Unable to register GATT client, MAX client reached: {}",
+ GATT_MAX_APPS);
return 0;
}
@@ -1280,14 +1273,12 @@
*
******************************************************************************/
void GATT_Deregister(tGATT_IF gatt_if) {
- LOG(INFO) << __func__ << " gatt_if=" << +gatt_if;
+ log::info("gatt_if={}", +gatt_if);
tGATT_REG* p_reg = gatt_get_regcb(gatt_if);
/* Index 0 is GAP and is never deregistered */
if ((gatt_if == 0) || (p_reg == NULL)) {
- LOG(ERROR) << __func__
- << ": Unable to deregister client with invalid gatt_if="
- << +gatt_if;
+ log::error("Unable to deregister client with invalid gatt_if={}", gatt_if);
return;
}
@@ -1363,7 +1354,7 @@
uint16_t conn_id;
tBT_TRANSPORT transport;
- LOG_DEBUG("Starting GATT interface gatt_if_:%hu", gatt_if);
+ log::debug("Starting GATT interface gatt_if_:{}", gatt_if);
p_reg = gatt_get_regcb(gatt_if);
if (p_reg != NULL) {
@@ -1371,15 +1362,15 @@
while (
gatt_find_the_connected_bda(start_idx, bda, &found_idx, &transport)) {
p_tcb = gatt_find_tcb_by_addr(bda, transport);
- LOG_INFO("GATT interface %d already has connected device %s", +gatt_if,
- ADDRESS_TO_LOGGABLE_CSTR(bda));
+ log::info("GATT interface {} already has connected device {}", gatt_if,
+ ADDRESS_TO_LOGGABLE_CSTR(bda));
if (p_reg->app_cb.p_conn_cb && p_tcb) {
conn_id = GATT_CREATE_CONN_ID(p_tcb->tcb_idx, gatt_if);
- LOG_INFO("Invoking callback with connection id %d", conn_id);
+ log::info("Invoking callback with connection id {}", conn_id);
(*p_reg->app_cb.p_conn_cb)(gatt_if, bda, conn_id, true, GATT_CONN_OK,
transport);
} else {
- LOG_INFO("Skipping callback as none is registered");
+ log::info("Skipping callback as none is registered");
}
start_idx = ++found_idx;
}
@@ -1417,42 +1408,42 @@
/* Make sure app is registered */
tGATT_REG* p_reg = gatt_get_regcb(gatt_if);
if (!p_reg) {
- LOG_ERROR("Unable to find registered app gatt_if=%d", +gatt_if);
+ log::error("Unable to find registered app gatt_if={}", gatt_if);
return false;
}
bool is_direct = (connection_type == BTM_BLE_DIRECT_CONNECTION);
if (!is_direct && transport != BT_TRANSPORT_LE) {
- LOG_WARN("Unsupported transport for background connection gatt_if=%d",
- +gatt_if);
+ log::warn("Unsupported transport for background connection gatt_if={}",
+ gatt_if);
return false;
}
if (opportunistic) {
- LOG_INFO("Registered for opportunistic connection gatt_if=%d", +gatt_if);
+ log::info("Registered for opportunistic connection gatt_if={}", gatt_if);
return true;
}
- bool ret;
+ bool ret = false;
if (is_direct) {
- LOG_DEBUG("Starting direct connect gatt_if=%u address=%s", gatt_if,
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::debug("Starting direct connect gatt_if={} address={}", gatt_if,
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
ret =
gatt_act_connect(p_reg, bd_addr, addr_type, transport, initiating_phys);
} else {
- LOG_DEBUG("Starting background connect gatt_if=%u address=%s", gatt_if,
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::debug("Starting background connect gatt_if={} address={}", gatt_if,
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
if (!BTM_Sec_AddressKnown(bd_addr)) {
// RPA can rotate, causing address to "expire" in the background
// connection list. RPA is allowed for direct connect, as such request
// times out after 30 seconds
- LOG_WARN("Unable to add RPA %s to background connection gatt_if=%d",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), +gatt_if);
+ log::warn("Unable to add RPA {} to background connection gatt_if={}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr), gatt_if);
ret = false;
} else {
- LOG_DEBUG("Adding to background connect to device:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::debug("Adding to background connect to device:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
if (bluetooth::common::init_flags::
use_unified_connection_manager_is_enabled()) {
if (connection_type == BTM_BLE_BKG_CONNECT_ALLOW_LIST) {
@@ -1461,7 +1452,7 @@
gatt_if, bluetooth::connection::ResolveRawAddress(bd_addr));
ret = true; // TODO(aryarahul): error handling
} else {
- LOG_ALWAYS_FATAL("unimplemented, TODO(aryarahul)");
+ log::fatal("unimplemented, TODO(aryarahul)");
}
} else {
if (connection_type == BTM_BLE_BKG_CONNECT_ALLOW_LIST) {
@@ -1481,10 +1472,10 @@
gatt_update_app_use_link_flag(p_reg->gatt_if, p_tcb, true, !is_direct);
} else {
if (p_tcb == nullptr) {
- LOG_DEBUG("p_tcb is null");
+ log::debug("p_tcb is null");
}
if (!ret) {
- LOG_DEBUG("Previous step returned false");
+ log::debug("Previous step returned false");
}
}
@@ -1515,15 +1506,14 @@
******************************************************************************/
bool GATT_CancelConnect(tGATT_IF gatt_if, const RawAddress& bd_addr,
bool is_direct) {
- LOG(INFO) << __func__ << ": gatt_if:" << +gatt_if
- << ", address: " << ADDRESS_TO_LOGGABLE_CSTR(bd_addr)
- << ", direct:" << is_direct;
+ log::info("gatt_if:{}, address: {}, direct:{}", gatt_if,
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr), is_direct);
tGATT_REG* p_reg;
if (gatt_if) {
p_reg = gatt_get_regcb(gatt_if);
if (!p_reg) {
- LOG(ERROR) << "gatt_if=" << +gatt_if << " is not registered";
+ log::error("gatt_if={} is not registered", gatt_if);
return false;
}
@@ -1534,7 +1524,7 @@
}
}
- VLOG(1) << " unconditional";
+ log::verbose(" unconditional");
/* only LE connection can be cancelled */
tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bd_addr, BT_TRANSPORT_LE);
@@ -1556,9 +1546,8 @@
bluetooth::connection::ResolveRawAddress(bd_addr));
} else {
if (!connection_manager::remove_unconditional(bd_addr)) {
- LOG(ERROR) << __func__
- << ": no app associated with the bg device for unconditional "
- "removal ";
+ log::error(
+ "no app associated with the bg device for unconditional removal");
return false;
}
}
@@ -1579,12 +1568,12 @@
*
******************************************************************************/
tGATT_STATUS GATT_Disconnect(uint16_t conn_id) {
- LOG_INFO("conn_id=%d", +conn_id);
+ log::info("conn_id={}", conn_id);
uint8_t tcb_idx = GATT_GET_TCB_IDX(conn_id);
tGATT_TCB* p_tcb = gatt_get_tcb_by_idx(tcb_idx);
if (!p_tcb) {
- LOG_WARN("Cannot find TCB for connection %d", conn_id);
+ log::warn("Cannot find TCB for connection {}", conn_id);
return GATT_ILLEGAL_PARAMETER;
}
@@ -1614,7 +1603,7 @@
uint8_t tcb_idx = GATT_GET_TCB_IDX(conn_id);
tGATT_TCB* p_tcb = gatt_get_tcb_by_idx(tcb_idx);
- VLOG(1) << __func__ << " conn_id=" << loghex(conn_id);
+ log::verbose("conn_id={}", loghex(conn_id));
if (!p_tcb || !p_reg) return false;
@@ -1650,7 +1639,7 @@
status = true;
}
- LOG_DEBUG("status=%d", status);
+ log::debug("status={}", status);
return status;
}
@@ -1680,19 +1669,19 @@
*/
void gatt_load_bonded(void) {
const bool load_bonded = gatt_load_bonded_is_enabled();
- LOG_INFO("load bonded: %s", load_bonded ? "True" : "False");
+ log::info("load bonded: {}", load_bonded ? "True" : "False");
if (!load_bonded) {
return;
}
for (tBTM_SEC_DEV_REC* p_dev_rec : btm_get_sec_dev_rec()) {
if (p_dev_rec->sec_rec.is_link_key_known()) {
- LOG_VERBOSE("Add bonded BR/EDR transport %s",
- ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr));
+ log::verbose("Add bonded BR/EDR transport {}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->bd_addr));
gatt_bonded_check_add_address(p_dev_rec->bd_addr);
}
if (p_dev_rec->sec_rec.is_le_link_key_known()) {
- LOG_VERBOSE("Add bonded BLE %s",
- ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->ble.pseudo_addr));
+ log::verbose("Add bonded BLE {}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_dev_rec->ble.pseudo_addr));
gatt_bonded_check_add_address(p_dev_rec->ble.pseudo_addr);
}
}
diff --git a/system/stack/gatt/gatt_attr.cc b/system/stack/gatt/gatt_attr.cc
index 3fa1647..526fb05 100644
--- a/system/stack/gatt/gatt_attr.cc
+++ b/system/stack/gatt/gatt_attr.cc
@@ -24,6 +24,7 @@
******************************************************************************/
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <deque>
#include <map>
@@ -46,6 +47,7 @@
using base::StringPrintf;
using bluetooth::Uuid;
+using namespace bluetooth;
#define BLE_GATT_SVR_SUP_FEAT_EATT_BITMASK 0x01
@@ -329,12 +331,12 @@
break;
case GATTS_REQ_TYPE_MTU:
- VLOG(1) << "Get MTU exchange new mtu size: " << +p_data->mtu;
+ log::verbose("Get MTU exchange new mtu size: {}", p_data->mtu);
rsp_needed = false;
break;
default:
- VLOG(1) << "Unknown/unexpected LE GAP ATT request: " << loghex(type);
+ log::verbose("Unknown/unexpected LE GAP ATT request: {}", loghex(type));
break;
}
@@ -354,13 +356,13 @@
const RawAddress& bda, uint16_t conn_id,
bool connected, tGATT_DISCONN_REASON reason,
tBT_TRANSPORT transport) {
- VLOG(1) << __func__ << ": from " << ADDRESS_TO_LOGGABLE_STR(bda)
- << " connected: " << connected << ", conn_id: " << loghex(conn_id);
+ log::verbose("from {} connected: {}, conn_id: {}",
+ ADDRESS_TO_LOGGABLE_STR(bda), connected, loghex(conn_id));
// if the device is not trusted, remove data when the link is disconnected
if (!connected && !btm_sec_is_a_bonded_dev(bda)) {
- LOG(INFO) << __func__ << ": remove untrusted client status, bda="
- << ADDRESS_TO_LOGGABLE_STR(bda);
+ log::info("remove untrusted client status, bda={}",
+ ADDRESS_TO_LOGGABLE_STR(bda));
btif_storage_remove_gatt_cl_supp_feat(bda);
btif_storage_remove_gatt_cl_db_hash(bda);
}
@@ -452,7 +454,7 @@
if (gatt_cl_is_robust_caching_enabled())
gatt_cb.gatt_cl_supported_feat_mask |= BLE_GATT_CL_SUP_FEAT_CACHING_BITMASK;
- VLOG(1) << __func__ << ": gatt_if=" << gatt_cb.gatt_if << " EATT supported";
+ log::verbose("gatt_if={} EATT supported", gatt_cb.gatt_if);
}
/*******************************************************************************
@@ -491,7 +493,7 @@
case GATT_DISC_SRVC_ALL:
case GATT_DISC_INC_SRVC:
case GATT_DISC_MAX:
- LOG_ERROR("Illegal discovery item handled");
+ log::error("Illegal discovery item handled");
break;
}
}
@@ -509,17 +511,17 @@
tGATT_STATUS status) {
tGATT_PROFILE_CLCB* p_clcb = gatt_profile_find_clcb_by_conn_id(conn_id);
if (p_clcb == NULL) {
- LOG_WARN("Unable to find gatt profile after discovery complete");
+ log::warn("Unable to find gatt profile after discovery complete");
return;
}
if (status != GATT_SUCCESS) {
- LOG_WARN("Gatt discovery completed with errors status:%u", status);
+ log::warn("Gatt discovery completed with errors status:{}", status);
return;
}
if (p_clcb->ccc_result == 0) {
- LOG_WARN("Gatt discovery completed but connection was idle id:%hu",
- conn_id);
+ log::warn("Gatt discovery completed but connection was idle id:{}",
+ conn_id);
return;
}
@@ -541,8 +543,7 @@
tGATT_STATUS status = GATTC_Read(conn_id, GATT_READ_BY_TYPE, ¶m);
if (status != GATT_SUCCESS) {
- LOG(ERROR) << __func__ << " Read failed. Status: "
- << loghex(static_cast<uint8_t>(status));
+ log::error("Read failed. Status: {}", loghex(static_cast<uint8_t>(status)));
return false;
}
@@ -568,8 +569,8 @@
tGATT_STATUS status = GATTC_Write(conn_id, GATT_WRITE, &attr);
if (status != GATT_SUCCESS) {
- LOG(ERROR) << __func__ << " Write failed. Status: "
- << loghex(static_cast<uint8_t>(status));
+ log::error("Write failed. Status: {}",
+ loghex(static_cast<uint8_t>(status)));
return false;
}
@@ -590,19 +591,19 @@
tGATT_CL_COMPLETE* p_data) {
auto iter = OngoingOps.find(conn_id);
- VLOG(1) << __func__ << " opcode: " << loghex(static_cast<uint8_t>(op))
- << " status: " << status
- << " conn id: " << loghex(static_cast<uint8_t>(conn_id));
+ log::verbose("opcode: {} status: {} conn id: {}",
+ loghex(static_cast<uint8_t>(op)), status,
+ loghex(static_cast<uint8_t>(conn_id)));
if (op != GATTC_OPTYPE_READ && op != GATTC_OPTYPE_WRITE) {
- LOG_DEBUG("Not interested in opcode %d", op);
+ log::debug("Not interested in opcode {}", op);
return;
}
if (iter == OngoingOps.end() || (iter->second.size() == 0)) {
/* If OngoingOps is empty it means we are not interested in the result here.
*/
- LOG_DEBUG("Unexpected read complete");
+ log::debug("Unexpected read complete");
return;
}
@@ -610,14 +611,14 @@
if (op == GATTC_OPTYPE_WRITE) {
if (cl_op_uuid == GATT_UUID_GATT_SRV_CHGD) {
- LOG_DEBUG("Write response from Service Changed CCC");
+ log::debug("Write response from Service Changed CCC");
iter->second.pop_front();
/* Read server supported features here supported */
read_sr_supported_feat_req(
conn_id, base::BindOnce([](const RawAddress& bdaddr,
uint8_t support) { return; }));
} else {
- LOG_DEBUG("Not interested in that write response");
+ log::debug("Not interested in that write response");
}
return;
}
@@ -625,7 +626,7 @@
/* Handle Read operations */
uint8_t* pp = p_data->att_value.value;
- VLOG(1) << __func__ << " cl_op_uuid " << loghex(cl_op_uuid);
+ log::verbose("cl_op_uuid {}", loghex(cl_op_uuid));
switch (cl_op_uuid) {
case GATT_UUID_SERVER_SUP_FEAT: {
@@ -677,8 +678,7 @@
iter->second.pop_front();
if (status != GATT_SUCCESS) {
- LOG(INFO) << __func__
- << " Client supported features charcteristic not found";
+ log::info("Client supported features charcteristic not found");
return;
}
@@ -698,8 +698,7 @@
*
******************************************************************************/
static void gatt_cl_start_config_ccc(tGATT_PROFILE_CLCB* p_clcb) {
-
- VLOG(1) << __func__ << ": stage: " << +p_clcb->ccc_stage;
+ log::verbose("stage: {}", p_clcb->ccc_stage);
switch (p_clcb->ccc_stage) {
case GATT_SVC_CHANGED_SERVICE: /* discover GATT service */
@@ -801,7 +800,7 @@
param.service.uuid = bluetooth::Uuid::From16Bit(GATT_UUID_SERVER_SUP_FEAT);
if (GATTC_Read(conn_id, GATT_READ_BY_TYPE, ¶m) != GATT_SUCCESS) {
- LOG_ERROR("Read GATT Support features GATT_Read Failed");
+ log::error("Read GATT Support features GATT_Read Failed");
return false;
}
@@ -828,8 +827,8 @@
param.service.uuid = bluetooth::Uuid::From16Bit(GATT_UUID_CSIS_SIRK);
if (GATTC_Read(conn_id, GATT_READ_BY_TYPE, ¶m) != GATT_SUCCESS) {
- LOG_ERROR("Read GATT Support features GATT_Read Failed, conn_id: %d",
- static_cast<int>(conn_id));
+ log::error("Read GATT Support features GATT_Read Failed, conn_id: {}",
+ static_cast<int>(conn_id));
return false;
}
@@ -859,8 +858,8 @@
if (!cb) return false;
- VLOG(1) << __func__ << " BDA: " << ADDRESS_TO_LOGGABLE_STR(peer_bda)
- << " read gatt supported features";
+ log::verbose("BDA: {} read gatt supported features",
+ ADDRESS_TO_LOGGABLE_STR(peer_bda));
GATT_GetConnIdIfConnected(gatt_cb.gatt_if, peer_bda, &conn_id,
BT_TRANSPORT_LE);
@@ -872,7 +871,7 @@
}
if (!p_clcb) {
- VLOG(1) << __func__ << " p_clcb is NULL " << loghex(conn_id);
+ log::verbose("p_clcb is NULL {}", loghex(conn_id));
return false;
}
@@ -903,7 +902,7 @@
if (!cb) return false;
- LOG_DEBUG("BDA: %s, read SIRK", ADDRESS_TO_LOGGABLE_CSTR(peer_bda));
+ log::debug("BDA: {}, read SIRK", ADDRESS_TO_LOGGABLE_CSTR(peer_bda));
GATT_GetConnIdIfConnected(gatt_cb.gatt_if, peer_bda, &conn_id,
BT_TRANSPORT_LE);
@@ -915,7 +914,7 @@
}
if (!p_clcb) {
- LOG_VERBOSE("p_clcb is NULL, conn_id: %04x", conn_id);
+ log::verbose("p_clcb is NULL, conn_id: {:04x}", conn_id);
return false;
}
@@ -940,8 +939,8 @@
bool gatt_profile_get_eatt_support(const RawAddress& remote_bda) {
uint16_t conn_id;
- VLOG(1) << __func__ << " BDA: " << ADDRESS_TO_LOGGABLE_STR(remote_bda)
- << " read GATT support";
+ log::verbose("BDA: {} read GATT support",
+ ADDRESS_TO_LOGGABLE_STR(remote_bda));
GATT_GetConnIdIfConnected(gatt_cb.gatt_if, remote_bda, &conn_id,
BT_TRANSPORT_LE);
@@ -1049,9 +1048,9 @@
tcb.is_robust_cache_change_aware = true;
}
- LOG(INFO) << __func__ << ": bda=" << ADDRESS_TO_LOGGABLE_STR(tcb.peer_bda)
- << ", cl_supp_feat=" << loghex(tcb.cl_supp_feat)
- << ", aware=" << tcb.is_robust_cache_change_aware;
+ log::info("bda={}, cl_supp_feat={}, aware={}",
+ ADDRESS_TO_LOGGABLE_STR(tcb.peer_bda), loghex(tcb.cl_supp_feat),
+ tcb.is_robust_cache_change_aware);
}
/*******************************************************************************
@@ -1075,8 +1074,8 @@
// only when the status is changed, print the log
if (tcb.is_robust_cache_change_aware != chg_aware) {
- LOG(INFO) << __func__ << ": bda=" << ADDRESS_TO_LOGGABLE_STR(tcb.peer_bda)
- << ", chg_aware=" << chg_aware;
+ log::info("bda={}, chg_aware={}", ADDRESS_TO_LOGGABLE_STR(tcb.peer_bda),
+ chg_aware);
}
tcb.is_robust_cache_change_aware = chg_aware;
@@ -1085,7 +1084,7 @@
/* handle request for reading database hash */
static tGATT_STATUS gatt_sr_read_db_hash(uint16_t conn_id,
tGATT_VALUE* p_value) {
- LOG(INFO) << __func__ << ": conn_id=" << loghex(conn_id);
+ log::info("conn_id={}", loghex(conn_id));
uint8_t* p = p_value->value;
Octet16& db_hash = gatt_cb.database_hash;
@@ -1139,14 +1138,14 @@
// If input length is zero, return value_not_allowed
if (tmp.empty()) {
- LOG(INFO) << __func__ << ": zero length, conn_id=" << loghex(conn_id)
- << ", bda=" << ADDRESS_TO_LOGGABLE_STR(tcb.peer_bda);
+ log::info("zero length, conn_id={}, bda={}", loghex(conn_id),
+ ADDRESS_TO_LOGGABLE_STR(tcb.peer_bda));
return GATT_VALUE_NOT_ALLOWED;
}
// if original length is longer than new one, it must be the bit reset case.
if (feature_list.size() > tmp.size()) {
- LOG(INFO) << __func__ << ": shorter length, conn_id=" << loghex(conn_id)
- << ", bda=" << ADDRESS_TO_LOGGABLE_STR(tcb.peer_bda);
+ log::info("shorter length, conn_id={}, bda={}", loghex(conn_id),
+ ADDRESS_TO_LOGGABLE_STR(tcb.peer_bda));
return GATT_VALUE_NOT_ALLOWED;
}
// new length is longer or equals to the original, need to check bits
@@ -1160,9 +1159,8 @@
uint8_t val_xor = *it_old ^ *it_new;
uint8_t val_and = val_xor & *it_new;
if (val_and != val_xor) {
- LOG(INFO) << __func__
- << ": bit cannot be reset, conn_id=" << loghex(conn_id)
- << ", bda=" << ADDRESS_TO_LOGGABLE_STR(tcb.peer_bda);
+ log::info("bit cannot be reset, conn_id={}, bda={}", loghex(conn_id),
+ ADDRESS_TO_LOGGABLE_STR(tcb.peer_bda));
return GATT_VALUE_NOT_ALLOWED;
}
}
@@ -1174,9 +1172,8 @@
if (!gatt_sr_is_robust_caching_enabled()) {
// remove robust caching bit
tcb.cl_supp_feat &= ~BLE_GATT_CL_SUP_FEAT_CACHING_BITMASK;
- LOG(INFO) << __func__
- << ": reset robust caching bit, conn_id=" << loghex(conn_id)
- << ", bda=" << ADDRESS_TO_LOGGABLE_STR(tcb.peer_bda);
+ log::info("reset robust caching bit, conn_id={}, bda={}", loghex(conn_id),
+ ADDRESS_TO_LOGGABLE_STR(tcb.peer_bda));
}
// TODO(hylo): save data as byte array
btif_storage_set_gatt_cl_supp_feat(tcb.peer_bda, tcb.cl_supp_feat);
@@ -1185,8 +1182,7 @@
bool new_caching_state = gatt_sr_is_cl_robust_caching_supported(tcb);
// only when the first time robust caching request, print the log
if (!curr_caching_state && new_caching_state) {
- LOG(INFO) << __func__ << ": robust caching enabled by client"
- << ", conn_id=" << loghex(conn_id);
+ log::info("robust caching enabled by client, conn_id={}", loghex(conn_id));
}
return GATT_SUCCESS;
diff --git a/system/stack/gatt/gatt_auth.cc b/system/stack/gatt/gatt_auth.cc
index c19b2d8..0b2cceb 100644
--- a/system/stack/gatt/gatt_auth.cc
+++ b/system/stack/gatt/gatt_auth.cc
@@ -22,6 +22,7 @@
*
******************************************************************************/
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <string.h>
#include "gatt_api.h"
@@ -36,7 +37,7 @@
#include "stack/include/btm_ble_sec_api.h"
#include "types/raw_address.h"
-using base::StringPrintf;
+using namespace bluetooth;
/*******************************************************************************
*
@@ -104,8 +105,8 @@
uint32_t counter;
if (p_buf->len < GATT_AUTH_SIGN_LEN + 4) {
- LOG(ERROR) << StringPrintf("%s: Data length %u less than expected %u",
- __func__, p_buf->len, GATT_AUTH_SIGN_LEN + 4);
+ log::error("Data length {} less than expected {}", p_buf->len,
+ GATT_AUTH_SIGN_LEN + 4);
return;
}
cmd_len = p_buf->len - GATT_AUTH_SIGN_LEN + 4;
@@ -114,7 +115,7 @@
if (!BTM_BleVerifySignature(tcb.peer_bda, p_orig, cmd_len, counter, p)) {
/* if this is a bad signature, assume from attacker, ignore it */
- LOG(ERROR) << StringPrintf("Signature Verification Failed, data ignored");
+ log::error("Signature Verification Failed, data ignored");
return;
}
@@ -158,19 +159,17 @@
tBT_TRANSPORT transport,
UNUSED_ATTR void* p_ref_data,
tBTM_STATUS result) {
- VLOG(1) << StringPrintf("gatt_enc_cmpl_cback");
+ log::verbose("");
tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(*bd_addr, transport);
if (!p_tcb) {
- LOG(ERROR) << StringPrintf("%s: enc callback for unknown bd_addr",
- __func__);
+ log::error("enc callback for unknown bd_addr");
return;
}
if (gatt_get_sec_act(p_tcb) == GATT_SEC_ENC_PENDING) return;
if (p_tcb->pending_enc_clcb.empty()) {
- LOG(ERROR) << StringPrintf("%s: no operation waiting for encrypting",
- __func__);
+ log::error("no operation waiting for encrypting");
return;
}
@@ -214,8 +213,7 @@
void gatt_notify_enc_cmpl(const RawAddress& bd_addr) {
tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bd_addr, BT_TRANSPORT_LE);
if (!p_tcb) {
- VLOG(1) << StringPrintf(
- "notify GATT for encryption completion of unknown device");
+ log::verbose("notify GATT for encryption completion of unknown device");
return;
}
@@ -365,8 +363,7 @@
}
}
- VLOG(1) << StringPrintf("gatt_get_link_encrypt_status status=0x%x",
- encrypt_status);
+ log::verbose("gatt_get_link_encrypt_status status=0x{:x}", encrypt_status);
return encrypt_status;
}
@@ -412,24 +409,21 @@
switch (gatt_sec_act) {
case GATT_SEC_SIGN_DATA:
- VLOG(1) << StringPrintf("%s: Do data signing", __func__);
+ log::verbose("Do data signing");
gatt_sign_data(p_clcb);
break;
case GATT_SEC_ENCRYPT:
case GATT_SEC_ENCRYPT_NO_MITM:
case GATT_SEC_ENCRYPT_MITM:
if (sec_act_old < GATT_SEC_ENCRYPT) {
- VLOG(1) << StringPrintf("%s: Encrypt now or key upgreade first",
- __func__);
+ log::verbose("Encrypt now or key upgreade first");
tBTM_BLE_SEC_ACT btm_ble_sec_act;
gatt_convert_sec_action(gatt_sec_act, &btm_ble_sec_act);
tBTM_STATUS btm_status =
BTM_SetEncryption(p_tcb->peer_bda, p_tcb->transport,
gatt_enc_cmpl_cback, NULL, btm_ble_sec_act);
if ((btm_status != BTM_SUCCESS) && (btm_status != BTM_CMD_STARTED)) {
- LOG(ERROR) << StringPrintf(
- "%s BTM_SetEncryption failed btm_status=%d", __func__,
- btm_status);
+ log::error("BTM_SetEncryption failed btm_status={}", btm_status);
gatt_set_sec_act(p_tcb, GATT_SEC_NONE);
gatt_set_ch_state(p_tcb, GATT_CH_OPEN);
diff --git a/system/stack/gatt/gatt_cl.cc b/system/stack/gatt/gatt_cl.cc
index 1acbb55..f273f62 100644
--- a/system/stack/gatt/gatt_cl.cc
+++ b/system/stack/gatt/gatt_cl.cc
@@ -25,6 +25,7 @@
#define LOG_TAG "bluetooth"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <string.h>
#include "gatt_int.h"
@@ -53,7 +54,7 @@
#define L2CAP_PKT_OVERHEAD 4
-using base::StringPrintf;
+using namespace bluetooth;
using bluetooth::Uuid;
using bluetooth::eatt::EattExtension;
using bluetooth::eatt::EattChannel;
@@ -94,7 +95,7 @@
uint8_t op_code = disc_type_to_att_opcode[p_clcb->op_subtype];
if (p_clcb->s_handle > p_clcb->e_handle || p_clcb->s_handle == 0) {
- LOG_DEBUG("Completed GATT discovery of all handle ranges");
+ log::debug("Completed GATT discovery of all handle ranges");
gatt_end_operation(p_clcb, GATT_SUCCESS, NULL);
return;
}
@@ -135,7 +136,7 @@
tGATT_STATUS st = attp_send_cl_msg(*p_clcb->p_tcb, p_clcb, op_code, &cl_req);
if (st != GATT_SUCCESS && st != GATT_CMD_STARTED) {
- LOG_WARN("Unable to send ATT message");
+ log::warn("Unable to send ATT message");
gatt_end_operation(p_clcb, GATT_ERROR, NULL);
}
}
@@ -181,8 +182,8 @@
else
p_clcb->first_read_blob_after_read = false;
- VLOG(1) << __func__ << ": first_read_blob_after_read="
- << p_clcb->first_read_blob_after_read;
+ log::verbose("first_read_blob_after_read={}",
+ p_clcb->first_read_blob_after_read);
op_code = GATT_REQ_READ_BLOB;
msg.read_blob.offset = offset;
msg.read_blob.handle = p_clcb->s_handle;
@@ -213,7 +214,7 @@
break;
default:
- LOG(ERROR) << "Unknown read type:" << +p_clcb->op_subtype;
+ log::error("Unknown read type:{}", p_clcb->op_subtype);
break;
}
@@ -242,8 +243,8 @@
attr.len, 0, attr.value);
if (rt != GATT_CMD_STARTED) {
if (rt != GATT_SUCCESS) {
- LOG(ERROR) << StringPrintf(
- "gatt_act_write() failed op_code=0x%x rt=%d", op_code, rt);
+ log::error("gatt_act_write() failed op_code=0x{:x} rt={}", op_code,
+ rt);
}
gatt_end_operation(p_clcb, rt, NULL);
}
@@ -259,9 +260,8 @@
if (rt != GATT_SUCCESS && rt != GATT_CMD_STARTED &&
rt != GATT_CONGESTED) {
if (rt != GATT_SUCCESS) {
- LOG(ERROR) << StringPrintf(
- "gatt_act_write() failed op_code=0x%x rt=%d", GATT_REQ_WRITE,
- rt);
+ log::error("gatt_act_write() failed op_code=0x{:x} rt={}",
+ GATT_REQ_WRITE, rt);
}
gatt_end_operation(p_clcb, rt, NULL);
}
@@ -295,7 +295,7 @@
tGATT_EXEC_FLAG flag) {
tGATT_STATUS rt;
- VLOG(1) << __func__;
+ log::verbose("");
tGATT_CL_MSG gatt_cl_msg;
gatt_cl_msg.exec_write = flag;
@@ -320,7 +320,7 @@
bool terminate = false;
tGATT_EXEC_FLAG flag = GATT_PREP_WRITE_EXEC;
- VLOG(1) << __func__;
+ log::verbose("");
/* check the first write response status */
if (p_rsp_value != NULL) {
if (p_rsp_value->handle != p_attr->handle ||
@@ -349,7 +349,7 @@
tGATT_VALUE* p_attr = (tGATT_VALUE*)p_clcb->p_attr_buf;
uint8_t type = p_clcb->op_subtype;
- VLOG(1) << __func__ << StringPrintf(" type=0x%x", type);
+ log::verbose("type=0x{:x}", type);
uint16_t to_send = p_attr->len - p_attr->offset;
uint16_t payload_size = gatt_tcb_get_payload_size(tcb, p_clcb->cid);
@@ -364,7 +364,7 @@
offset += p_clcb->start_offset;
}
- VLOG(1) << StringPrintf("offset =0x%x len=%d", offset, to_send);
+ log::verbose("offset =0x{:x} len={}", offset, to_send);
tGATT_STATUS rt = gatt_send_write_msg(
tcb, p_clcb, GATT_REQ_PREPARE_WRITE, p_attr->handle, to_send, /* length */
@@ -395,7 +395,7 @@
tGATT_DISC_RES result;
uint8_t* p = p_data;
- VLOG(1) << __func__;
+ log::verbose("");
/* unexpected response */
if (p_clcb->operation != GATTC_OPTYPE_DISCOVERY ||
p_clcb->op_subtype != GATT_DISC_SRVC_BY_UUID)
@@ -443,7 +443,7 @@
uint8_t *p = p_data, uuid_len = 0, type;
if (len < GATT_INFO_RSP_MIN_LEN) {
- LOG(ERROR) << "invalid Info Response PDU received, discard.";
+ log::error("invalid Info Response PDU received, discard.");
gatt_end_operation(p_clcb, GATT_INVALID_PDU, NULL);
return;
}
@@ -495,8 +495,7 @@
uint8_t reason) {
tGATT_STATUS status = (tGATT_STATUS)reason;
- VLOG(1) << __func__
- << StringPrintf("reason: %02x cmd_code %04x", reason, opcode);
+ log::verbose("reason: {:02x} cmd_code {:04x}", reason, opcode);
switch (opcode) {
case GATT_REQ_READ_BY_GRP_TYPE:
@@ -505,11 +504,11 @@
case GATT_REQ_FIND_INFO:
if (reason == GATT_NOT_FOUND) {
status = GATT_SUCCESS;
- VLOG(1) << "Discovery completed";
+ log::verbose("Discovery completed");
}
break;
default:
- LOG(ERROR) << StringPrintf("Incorrect discovery opcode %04x", opcode);
+ log::error("Incorrect discovery opcode {:04x}", opcode);
break;
}
@@ -534,10 +533,10 @@
uint16_t handle;
tGATT_VALUE* p_attr = (tGATT_VALUE*)p_clcb->p_attr_buf;
- VLOG(1) << __func__;
+ log::verbose("");
if (len < 4) {
- LOG(ERROR) << "Error response too short";
+ log::error("Error response too short");
// Specification does not clearly define what should happen if error
// response is too short. General rule in BT Spec 5.0 Vol 3, Part F 3.4.1.1
// is: "If an error code is received in the Error Response that is not
@@ -593,12 +592,12 @@
.conn_id = p_clcb->conn_id, .auth_req = GATT_AUTH_REQ_NONE,
};
- VLOG(1) << StringPrintf("value resp op_code = %s len = %d",
- gatt_dbg_op_name(op_code), len);
+ log::verbose("value resp op_code = {} len = {}", gatt_dbg_op_name(op_code),
+ len);
if (len < GATT_PREP_WRITE_RSP_MIN_LEN ||
len > GATT_PREP_WRITE_RSP_MIN_LEN + sizeof(value.value)) {
- LOG(ERROR) << "illegal prepare write response length, discard";
+ log::error("illegal prepare write response length, discard");
gatt_end_operation(p_clcb, GATT_INVALID_PDU, &value);
return;
}
@@ -648,11 +647,11 @@
? GATTC_OPTYPE_INDICATION
: GATTC_OPTYPE_NOTIFICATION;
- VLOG(1) << __func__;
+ log::verbose("");
// Ensure our packet has enough data (2 bytes)
if (len < GATT_NOTIFICATION_MIN_LEN) {
- LOG(ERROR) << "illegal notification PDU length, discard";
+ log::error("illegal notification PDU length, discard");
return;
}
@@ -671,7 +670,7 @@
if (op_code == GATT_HANDLE_MULTI_VALUE_NOTIF) {
// Ensure our packet has enough data; MIN + 2 more bytes for len value
if (len < GATT_NOTIFICATION_MIN_LEN + 2) {
- LOG(ERROR) << "illegal notification PDU length, discard";
+ log::error("illegal notification PDU length, discard");
return;
}
@@ -679,8 +678,8 @@
STREAM_TO_UINT16(value.len, p);
if (value.len > len - 4) {
- LOG(ERROR) << "value.len (" << value.len << ") greater than length ("
- << (len - 4);
+ log::error("value.len ({}) greater than length ({})", value.len,
+ (len - 4));
return;
}
@@ -691,7 +690,7 @@
// Verify the new calculated length
if (value.len > GATT_MAX_ATTR_LEN) {
- LOG(ERROR) << "value.len larger than GATT_MAX_ATTR_LEN, discard";
+ log::error("value.len larger than GATT_MAX_ATTR_LEN, discard");
return;
}
@@ -703,8 +702,8 @@
For now, just log the error reset the counter.
Later we need to disconnect the link unconditionally.
*/
- LOG(ERROR) << __func__ << " rcv Ind. but ind_count=" << tcb.ind_count
- << " (will reset ind_count)";
+ log::error("rcv Ind. but ind_count={} (will reset ind_count)",
+ tcb.ind_count);
}
// Zero out the ind_count
@@ -764,7 +763,7 @@
// we can Also need to watch comparing the int16_t with the uint16_t
value.len = std::min((uint16_t)rem_len, value.len);
if (value.len > sizeof(value.value)) {
- LOG(ERROR) << "Unexpected value.len (>GATT_MAX_ATTR_LEN), stop";
+ log::error("Unexpected value.len (>GATT_MAX_ATTR_LEN), stop");
return ;
}
STREAM_TO_ARRAY(value.value, p, value.len);
@@ -809,7 +808,7 @@
return;
if (len < GATT_READ_BY_TYPE_RSP_MIN_LEN) {
- LOG(ERROR) << "Illegal ReadByType/ReadByGroupType Response length, discard";
+ log::error("Illegal ReadByType/ReadByGroupType Response length, discard");
gatt_end_operation(p_clcb, GATT_INVALID_PDU, NULL);
return;
}
@@ -820,11 +819,9 @@
/* this is an error case that server's response containing a value length
which is larger than MTU-2
or value_len > message total length -1 */
- LOG(ERROR) << __func__
- << StringPrintf(
- ": Discard response op_code=%d "
- "vale_len=%d > (MTU-2=%d or msg_len-1=%d)",
- op_code, value_len, (payload_size - 2), (len - 1));
+ log::error(
+ "Discard response op_code={} vale_len={} > (MTU-2={} or msg_len-1={})",
+ op_code, value_len, (payload_size - 2), (len - 1));
gatt_end_operation(p_clcb, GATT_ERROR, NULL);
return;
}
@@ -862,7 +859,7 @@
record_value.group_value.e_handle = handle;
if (!gatt_parse_uuid_from_cmd(&record_value.group_value.service_type,
value_len, &p)) {
- LOG(ERROR) << "discover all service response parsing failure";
+ log::error("discover all service response parsing failure");
break;
}
}
@@ -871,7 +868,7 @@
else if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY &&
p_clcb->op_subtype == GATT_DISC_INC_SRVC) {
if (value_len < 4) {
- LOG(ERROR) << __func__ << " Illegal Response length, must be at least 4.";
+ log::error("Illegal Response length, must be at least 4.");
gatt_end_operation(p_clcb, GATT_INVALID_PDU, NULL);
return;
}
@@ -900,9 +897,8 @@
gatt_act_read(p_clcb, 0);
return;
} else {
- LOG(ERROR) << __func__
- << ": INCL_SRVC failed with invalid data value_len="
- << +value_len;
+ log::error("INCL_SRVC failed with invalid data value_len={}",
+ value_len);
gatt_end_operation(p_clcb, GATT_INVALID_PDU, (void*)p);
return;
}
@@ -929,7 +925,7 @@
} else /* discover characteristic */
{
if (value_len < 3) {
- LOG(ERROR) << __func__ << " Illegal Response length, must be at least 3.";
+ log::error("Illegal Response length, must be at least 3.");
gatt_end_operation(p_clcb, GATT_INVALID_PDU, NULL);
return;
}
@@ -1037,9 +1033,9 @@
/* send next request if needed */
if (packet_is_full && (len + offset < GATT_MAX_ATTR_LEN)) {
- VLOG(1) << StringPrintf(
- "full pkt issue read blob for remaining bytes old offset=%d "
- "len=%d new offset=%d",
+ log::verbose(
+ "full pkt issue read blob for remaining bytes old offset={} "
+ "len={} new offset={}",
offset, len, p_clcb->counter);
gatt_act_read(p_clcb, p_clcb->counter);
} else /* end of request, send callback */
@@ -1048,8 +1044,8 @@
}
} else /* exception, should not happen */
{
- LOG(ERROR) << "attr offset = " << +offset
- << " p_attr_buf = " << p_clcb->p_attr_buf;
+ log::error("attr offset = {} p_attr_buf = {}", offset,
+ fmt::ptr(p_clcb->p_attr_buf));
gatt_end_operation(p_clcb, GATT_NO_RESOURCES,
(void*)p_clcb->p_attr_buf);
}
@@ -1104,14 +1100,14 @@
tGATT_STATUS status = GATT_SUCCESS;
if (len < GATT_MTU_RSP_MIN_LEN) {
- LOG(ERROR) << "invalid MTU response PDU received, discard.";
+ log::error("invalid MTU response PDU received, discard.");
status = GATT_INVALID_PDU;
} else {
STREAM_TO_UINT16(mtu, p_data);
- LOG_INFO("Local pending MTU %d, Remote (%s) MTU %d",
- tcb.pending_user_mtu_exchange_value,
- tcb.peer_bda.ToString().c_str(), mtu);
+ log::info("Local pending MTU {}, Remote ({}) MTU {}",
+ tcb.pending_user_mtu_exchange_value,
+ ADDRESS_TO_LOGGABLE_STR(tcb.peer_bda), mtu);
/* Aim for default as we did in the request */
if (mtu < GATT_DEF_BLE_MTU_SIZE) {
@@ -1133,7 +1129,7 @@
}
tcb.pending_user_mtu_exchange_value = 0;
- LOG_INFO("MTU Exchange resulted in: %d", tcb.payload_size);
+ log::info("MTU Exchange resulted in: {}", tcb.payload_size);
BTM_SetBleDataLength(tcb.peer_bda, tcb.max_user_mtu + L2CAP_PKT_OVERHEAD);
}
@@ -1184,7 +1180,7 @@
att_ret = attp_send_msg_to_l2cap(tcb, cmd.cid, cmd.p_cmd);
if (att_ret != GATT_SUCCESS && att_ret != GATT_CONGESTED) {
- LOG(ERROR) << __func__ << ": L2CAP sent error";
+ log::error("L2CAP sent error");
cl_cmd_q->pop_front();
continue;
}
@@ -1217,16 +1213,15 @@
void gatt_client_handle_server_rsp(tGATT_TCB& tcb, uint16_t cid,
uint8_t op_code, uint16_t len,
uint8_t* p_data) {
- VLOG(1) << __func__ << " opcode: " << loghex(op_code) << " cid" << +cid;
+ log::verbose("opcode: {} cid{}", loghex(op_code), cid);
uint16_t payload_size = gatt_tcb_get_payload_size(tcb, cid);
if (op_code == GATT_HANDLE_VALUE_IND || op_code == GATT_HANDLE_VALUE_NOTIF ||
op_code == GATT_HANDLE_MULTI_VALUE_NOTIF) {
if (len >= payload_size) {
- LOG(ERROR) << StringPrintf(
- "%s: invalid indicate pkt size: %d, PDU size: %d", __func__, len + 1,
- payload_size);
+ log::error("invalid indicate pkt size: {}, PDU size: {}", len + 1,
+ payload_size);
return;
}
@@ -1237,21 +1232,22 @@
uint8_t cmd_code = 0;
tGATT_CLCB* p_clcb = gatt_cmd_dequeue(tcb, cid, &cmd_code);
if (!p_clcb) {
- LOG_WARN("ATT - clcb already not in use, ignoring response");
+ log::warn("ATT - clcb already not in use, ignoring response");
gatt_cl_send_next_cmd_inq(tcb);
return;
}
uint8_t rsp_code = gatt_cmd_to_rsp_code(cmd_code);
if (!p_clcb) {
- LOG_WARN("ATT - clcb already not in use, ignoring response");
+ log::warn("ATT - clcb already not in use, ignoring response");
gatt_cl_send_next_cmd_inq(tcb);
return;
}
if (rsp_code != op_code && op_code != GATT_RSP_ERROR) {
- LOG(WARNING) << StringPrintf(
- "ATT - Ignore wrong response. Receives (%02x) Request(%02x) Ignored",
+ log::warn(
+ "ATT - Ignore wrong response. Receives ({:02x}) Request({:02x}) "
+ "Ignored",
op_code, rsp_code);
return;
}
@@ -1263,9 +1259,8 @@
/* The message has to be smaller than the agreed MTU, len does not count
* op_code */
if (len >= payload_size) {
- LOG(ERROR) << StringPrintf(
- "%s: invalid response pkt size: %d, PDU size: %d", __func__, len + 1,
- payload_size);
+ log::error("invalid response pkt size: {}, PDU size: {}", len + 1,
+ payload_size);
gatt_end_operation(p_clcb, GATT_ERROR, NULL);
} else {
switch (op_code) {
@@ -1310,7 +1305,7 @@
break;
default:
- LOG(ERROR) << __func__ << ": Unknown opcode = " << std::hex << op_code;
+ log::error("Unknown opcode = {:x}", op_code);
break;
}
}
diff --git a/system/stack/gatt/gatt_db.cc b/system/stack/gatt/gatt_db.cc
index 30aee99..55ded60 100644
--- a/system/stack/gatt/gatt_db.cc
+++ b/system/stack/gatt/gatt_db.cc
@@ -23,6 +23,7 @@
******************************************************************************/
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <log/log.h>
#include <stdio.h>
#include <string.h>
@@ -34,8 +35,8 @@
#include "stack/include/bt_types.h"
#include "types/bluetooth/uuid.h"
-using base::StringPrintf;
using bluetooth::Uuid;
+using namespace bluetooth;
/*******************************************************************************
* L O C A L F U N C T I O N P R O T O T Y P E S *
@@ -53,8 +54,7 @@
bool is_pri, uint16_t s_hdl, uint16_t num_handle) {
db.attr_list.reserve(num_handle);
- VLOG(1) << StringPrintf("%s: s_hdl= %d num_handle= %d", __func__, s_hdl,
- num_handle);
+ log::verbose("s_hdl= {} num_handle= {}", s_hdl, num_handle);
/* update service database information */
db.next_handle = s_hdl;
@@ -70,7 +70,7 @@
Uuid* gatts_get_service_uuid(tGATT_SVC_DB* p_db) {
if (!p_db || p_db->attr_list.empty()) {
- LOG(ERROR) << "service DB empty";
+ log::error("service DB empty");
return NULL;
} else {
return &p_db->attr_list[0].p_value->uuid;
@@ -92,29 +92,29 @@
}
if (!(perm & GATT_READ_ALLOWED)) {
- LOG(ERROR) << __func__ << ": GATT_READ_NOT_PERMIT";
+ log::error("GATT_READ_NOT_PERMIT");
return GATT_READ_NOT_PERMIT;
}
if ((perm & GATT_READ_AUTH_REQUIRED) && !sec_flag.is_link_key_known &&
!sec_flag.is_encrypted) {
- LOG(ERROR) << __func__ << ": GATT_INSUF_AUTHENTICATION";
+ log::error("GATT_INSUF_AUTHENTICATION");
return GATT_INSUF_AUTHENTICATION;
}
if ((perm & GATT_READ_MITM_REQUIRED) && !sec_flag.is_link_key_authed) {
- LOG(ERROR) << __func__ << ": GATT_INSUF_AUTHENTICATION: MITM Required";
+ log::error("GATT_INSUF_AUTHENTICATION: MITM Required");
return GATT_INSUF_AUTHENTICATION;
}
if ((perm & GATT_READ_ENCRYPTED_REQUIRED) && !sec_flag.is_encrypted) {
- LOG(ERROR) << __func__ << ": GATT_INSUF_ENCRYPTION";
+ log::error("GATT_INSUF_ENCRYPTION");
return GATT_INSUF_ENCRYPTION;
}
if ((perm & GATT_READ_ENCRYPTED_REQUIRED) && sec_flag.is_encrypted &&
(key_size < min_key_size)) {
- LOG(ERROR) << __func__ << ": GATT_INSUF_KEY_SIZE";
+ log::error("GATT_INSUF_KEY_SIZE");
return GATT_INSUF_KEY_SIZE;
}
@@ -141,7 +141,7 @@
case GATT_UUID_CHAR_CLIENT_CONFIG:
case GATT_UUID_CHAR_SRVR_CONFIG:
case GATT_UUID_CHAR_PRESENT_FORMAT:
- LOG(ERROR) << __func__ << ": GATT_NOT_LONG";
+ log::error("GATT_NOT_LONG");
return GATT_NOT_LONG;
default:
@@ -176,9 +176,8 @@
tGATT_SEC_FLAG sec_flag, uint8_t key_size) {
uint8_t* p = *p_data;
- VLOG(1) << __func__ << " uuid=" << attr16.uuid
- << StringPrintf(" perm=0x%02x offset=%d read_long=%d",
- attr16.permission, offset, read_long);
+ log::verbose("uuid={} perm=0x{:02x} offset={} read_long={}", attr16.uuid,
+ attr16.permission, offset, read_long);
tGATT_STATUS status = gatts_check_attr_readability(attr16, offset, read_long,
sec_flag, key_size);
@@ -312,7 +311,7 @@
p_rsp->len += (len + 2);
*p_len -= (len + 2);
} else {
- LOG(ERROR) << "format mismatch";
+ log::error("format mismatch");
status = GATT_NO_RESOURCES;
break;
}
@@ -340,12 +339,11 @@
uint16_t e_handle, const Uuid& service) {
Uuid uuid = Uuid::From16Bit(GATT_UUID_INCLUDE_SERVICE);
- VLOG(1) << __func__
- << StringPrintf(": s_hdl=0x%04x e_hdl=0x%04x ", s_handle, e_handle)
- << "service uuid = " << service;
+ log::verbose("s_hdl=0x{:04x} e_hdl=0x{:04x} service uuid = {}", s_handle,
+ e_handle, service);
if (service.IsEmpty() || s_handle == 0 || e_handle == 0) {
- LOG(ERROR) << __func__ << ": Illegal Params.";
+ log::error("Illegal Params.");
return 0;
}
@@ -380,8 +378,7 @@
const Uuid& char_uuid) {
Uuid uuid = Uuid::From16Bit(GATT_UUID_CHAR_DECLARE);
- VLOG(1) << StringPrintf("%s: perm=0x%0x property=0x%0x", __func__, perm,
- property);
+ log::verbose("perm=0x{:0x} property=0x{:0x}", perm, property);
tGATT_ATTR& char_decl = allocate_attr_in_db(db, uuid, GATT_PERM_READ);
tGATT_ATTR& char_val = allocate_attr_in_db(db, char_uuid, perm);
@@ -410,8 +407,7 @@
tGATT_SVC_DB& db, uint16_t extended_properties) {
Uuid descr_uuid = Uuid::From16Bit(GATT_UUID_CHAR_EXT_PROP);
- VLOG(1) << StringPrintf("gatts_add_char_ext_prop_descr uuid=%s",
- descr_uuid.ToString().c_str());
+ log::verbose("gatts_add_char_ext_prop_descr uuid={}", descr_uuid.ToString());
tGATT_ATTR& char_dscptr = allocate_attr_in_db(db, descr_uuid, GATT_PERM_READ);
char_dscptr.gatt_type = BTGATT_DB_DESCRIPTOR;
@@ -437,8 +433,7 @@
******************************************************************************/
uint16_t gatts_add_char_descr(tGATT_SVC_DB& db, tGATT_PERM perm,
const Uuid& descr_uuid) {
- VLOG(1) << StringPrintf("gatts_add_char_descr uuid=%s",
- descr_uuid.ToString().c_str());
+ log::verbose("gatts_add_char_descr uuid={}", descr_uuid.ToString());
/* Add characteristic descriptors */
tGATT_ATTR& char_dscptr = allocate_attr_in_db(db, descr_uuid, perm);
@@ -551,10 +546,8 @@
uint8_t* p_data, uint16_t len,
tGATT_SEC_FLAG sec_flag,
uint8_t key_size) {
- VLOG(1) << StringPrintf(
- "%s: op_code=0x%0x handle=0x%04x offset=%d len=%d "
- "key_size=%d",
- __func__, op_code, handle, offset, len, key_size);
+ log::verbose("op_code=0x%{:x} handle=0x{:04x} offset={} len={} key_size={}",
+ op_code, handle, offset, len, key_size);
tGATT_ATTR* p_attr = find_attr_by_handle(p_db, handle);
if (!p_attr) return GATT_NOT_FOUND;
@@ -564,8 +557,8 @@
if (min_key_size != 0) {
min_key_size += 6;
}
- VLOG(1) << StringPrintf("%s: p_attr->permission =0x%04x min_key_size==0x%04x",
- __func__, p_attr->permission, min_key_size);
+ log::verbose("p_attr->permission =0x{:04x} min_key_size==0x{:04x}",
+ p_attr->permission, min_key_size);
if ((op_code == GATT_CMD_WRITE || op_code == GATT_REQ_WRITE) &&
(perm & GATT_WRITE_SIGNED_PERM)) {
@@ -589,38 +582,36 @@
tGATT_STATUS status = GATT_NOT_FOUND;
if ((op_code == GATT_SIGN_CMD_WRITE) && !(perm & GATT_WRITE_SIGNED_PERM)) {
status = GATT_WRITE_NOT_PERMIT;
- VLOG(1) << __func__ << ": sign cmd write not allowed";
+ log::verbose("sign cmd write not allowed");
}
if ((op_code == GATT_SIGN_CMD_WRITE) && sec_flag.is_encrypted) {
status = GATT_INVALID_PDU;
- LOG(ERROR) << __func__
- << ": Error!! sign cmd write sent on a encypted link";
+ log::error("Error!! sign cmd write sent on a encypted link");
} else if (!(perm & GATT_WRITE_ALLOWED)) {
status = GATT_WRITE_NOT_PERMIT;
- LOG(ERROR) << __func__ << ": 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) {
status = GATT_INSUF_AUTHENTICATION;
- LOG(ERROR) << __func__ << ": GATT_INSUF_AUTHENTICATION";
+ log::error("GATT_INSUF_AUTHENTICATION");
} else if ((perm & GATT_WRITE_MITM_REQUIRED) &&
!sec_flag.is_link_key_authed) {
status = GATT_INSUF_AUTHENTICATION;
- LOG(ERROR) << __func__ << ": GATT_INSUF_AUTHENTICATION: MITM required";
+ log::error("GATT_INSUF_AUTHENTICATION: MITM required");
} else if ((perm & GATT_WRITE_ENCRYPTED_PERM) && !sec_flag.is_encrypted) {
status = GATT_INSUF_ENCRYPTION;
- LOG(ERROR) << __func__ << ": GATT_INSUF_ENCRYPTION";
+ log::error("GATT_INSUF_ENCRYPTION");
} else if ((perm & GATT_WRITE_ENCRYPTED_PERM) && sec_flag.is_encrypted &&
(key_size < min_key_size)) {
status = GATT_INSUF_KEY_SIZE;
- LOG(ERROR) << __func__ << ": 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) {
status = GATT_INSUF_AUTHENTICATION;
- LOG(ERROR) << __func__
- << ": GATT_INSUF_AUTHENTICATION: LE security mode 2 required";
+ log::error("GATT_INSUF_AUTHENTICATION: LE security mode 2 required");
} else /* writable: must be char value declaration or char descritpors */
{
uint16_t max_size = 0;
@@ -661,11 +652,11 @@
if (op_code == GATT_REQ_PREPARE_WRITE && offset != 0) {
/* does not allow write blob */
status = GATT_NOT_LONG;
- LOG(ERROR) << __func__ << ": GATT_NOT_LONG";
+ log::error("GATT_NOT_LONG");
} else if (len != max_size) {
/* data does not match the required format */
status = GATT_INVALID_ATTR_LEN;
- LOG(ERROR) << __func__ << ": GATT_INVALID_PDU";
+ log::error("GATT_INVALID_PDU");
} else {
return GATT_SUCCESS;
}
@@ -689,9 +680,8 @@
static tGATT_ATTR& allocate_attr_in_db(tGATT_SVC_DB& db, const Uuid& uuid,
tGATT_PERM perm) {
if (db.next_handle >= db.end_handle) {
- LOG(FATAL) << __func__
- << " wrong number of handles! handle_max = " << +db.end_handle
- << ", next_handle = " << +db.next_handle;
+ log::fatal("wrong number of handles! handle_max = {}, next_handle = {}",
+ db.end_handle, db.next_handle);
}
db.attr_list.emplace_back();
@@ -736,9 +726,9 @@
} else if (gatt_type == BTGATT_DB_CHARACTERISTIC) {
opcode = GATTS_REQ_TYPE_READ_CHARACTERISTIC;
} else {
- LOG(ERROR) << __func__
- << ": Attempt to read attribute that's not tied with "
- "characteristic or descriptor value.";
+ log::error(
+ "Attempt to read attribute that's not tied with characteristic or "
+ "descriptor value.");
return GATT_ERROR;
}
diff --git a/system/stack/gatt/gatt_int.h b/system/stack/gatt/gatt_int.h
index 1e4867c..8a1c023 100644
--- a/system/stack/gatt/gatt_int.h
+++ b/system/stack/gatt/gatt_int.h
@@ -21,6 +21,7 @@
#include <base/functional/bind.h>
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <deque>
#include <list>
@@ -518,7 +519,7 @@
/* utility functions */
uint16_t gatt_get_local_mtu(void);
-uint8_t* gatt_dbg_op_name(uint8_t op_code);
+char const* gatt_dbg_op_name(uint8_t op_code);
uint32_t gatt_add_sdp_record(const bluetooth::Uuid& uuid, uint16_t start_hdl,
uint16_t end_hdl);
bool gatt_parse_uuid_from_cmd(bluetooth::Uuid* p_uuid, uint16_t len,
@@ -690,4 +691,9 @@
/* gatt_sr_hash.cc */
Octet16 gatts_calculate_database_hash(std::list<tGATT_SRV_LIST_ELEM>* lst_ptr);
+namespace fmt {
+template <>
+struct formatter<tGATT_CH_STATE> : enum_formatter<tGATT_CH_STATE> {};
+} // namespace fmt
+
#endif
diff --git a/system/stack/gatt/gatt_main.cc b/system/stack/gatt/gatt_main.cc
index ac8f2ac..959df25 100644
--- a/system/stack/gatt/gatt_main.cc
+++ b/system/stack/gatt/gatt_main.cc
@@ -24,6 +24,7 @@
#include <android_bluetooth_flags.h>
#include <base/logging.h>
+#include <bluetooth/log.h>
#include "btif/include/btif_dm.h"
#include "btif/include/btif_storage.h"
@@ -51,8 +52,8 @@
#include "stack/include/srvc_api.h" // tDIS_VALUE
#include "types/raw_address.h"
-using base::StringPrintf;
using bluetooth::eatt::EattExtension;
+using namespace bluetooth;
/******************************************************************************/
/* L O C A L F U N C T I O N P R O T O T Y P E S */
@@ -112,7 +113,7 @@
void gatt_init(void) {
tL2CAP_FIXED_CHNL_REG fixed_reg;
- VLOG(1) << __func__;
+ log::verbose("");
gatt_cb = tGATT_CB();
connection_manager::reset(true);
@@ -138,7 +139,7 @@
if (gatt_cb.over_br_enabled &&
!L2CA_Register2(BT_PSM_ATT, dyn_info, false /* enable_snoop */, nullptr,
GATT_MAX_MTU_SIZE, 0, BTM_SEC_NONE)) {
- LOG(ERROR) << "ATT Dynamic Registration failed";
+ log::error("ATT Dynamic Registration failed");
}
gatt_cb.hdl_cfg.gatt_start_hdl = GATT_GATT_START_HANDLE;
@@ -166,7 +167,7 @@
******************************************************************************/
void gatt_free(void) {
int i;
- VLOG(1) << __func__;
+ log::verbose("");
fixed_queue_free(gatt_cb.sign_op_queue, NULL);
gatt_cb.sign_op_queue = NULL;
@@ -253,18 +254,18 @@
*
******************************************************************************/
bool gatt_disconnect(tGATT_TCB* p_tcb) {
- VLOG(1) << __func__;
+ log::verbose("");
if (!p_tcb) {
- LOG_WARN("Unable to disconnect an unknown device");
+ log::warn("Unable to disconnect an unknown device");
return false;
}
tGATT_CH_STATE ch_state = gatt_get_ch_state(p_tcb);
if (ch_state == GATT_CH_CLOSING) {
- LOG_DEBUG("Device already in closing state peer:%s",
- ADDRESS_TO_LOGGABLE_CSTR(p_tcb->peer_bda));
- VLOG(1) << __func__ << " already in closing state";
+ log::debug("Device already in closing state peer:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_tcb->peer_bda));
+ log::verbose("already in closing state");
return true;
}
@@ -284,10 +285,9 @@
if (!connection_manager::direct_connect_remove(CONN_MGR_ID_L2CAP,
p_tcb->peer_bda)) {
BTM_AcceptlistRemove(p_tcb->peer_bda);
- LOG_INFO(
+ log::info(
"GATT connection manager has no record but removed filter "
- "acceptlist "
- "gatt_if:%hhu peer:%s",
+ "acceptlist gatt_if:{} peer:{}",
static_cast<uint8_t>(CONN_MGR_ID_L2CAP),
ADDRESS_TO_LOGGABLE_CSTR(p_tcb->peer_bda));
}
@@ -300,7 +300,7 @@
if ((ch_state == GATT_CH_OPEN) || (ch_state == GATT_CH_CFG)) {
gatt_l2cif_disconnect(p_tcb->att_lcid);
} else {
- VLOG(1) << __func__ << " gatt_disconnect channel not opened";
+ log::verbose("gatt_disconnect channel not opened");
}
}
@@ -319,27 +319,27 @@
******************************************************************************/
bool gatt_update_app_hold_link_status(tGATT_IF gatt_if, tGATT_TCB* p_tcb,
bool is_add) {
- LOG_DEBUG("gatt_if=%d, is_add=%d, peer_bda=%s", +gatt_if, is_add,
- ADDRESS_TO_LOGGABLE_CSTR(p_tcb->peer_bda));
+ log::debug("gatt_if={}, is_add={}, peer_bda={}", gatt_if, is_add,
+ ADDRESS_TO_LOGGABLE_CSTR(p_tcb->peer_bda));
auto& holders = p_tcb->app_hold_link;
if (is_add) {
auto ret = holders.insert(gatt_if);
if (ret.second) {
- LOG_DEBUG("added gatt_if=%d", +gatt_if);
+ log::debug("added gatt_if={}", gatt_if);
} else {
- LOG_DEBUG("attempt to add already existing gatt_if=%d", +gatt_if);
+ log::debug("attempt to add already existing gatt_if={}", gatt_if);
}
return true;
}
//! is_add
if (!holders.erase(gatt_if)) {
- LOG_WARN("attempt to remove non-existing gatt_if=%d", +gatt_if);
+ log::warn("attempt to remove non-existing gatt_if={}", gatt_if);
return false;
}
- LOG_INFO("removed gatt_if=%d", +gatt_if);
+ log::info("removed gatt_if={}", gatt_if);
return true;
}
@@ -356,23 +356,23 @@
******************************************************************************/
void gatt_update_app_use_link_flag(tGATT_IF gatt_if, tGATT_TCB* p_tcb,
bool is_add, bool check_acl_link) {
- LOG_DEBUG("gatt_if=%d, is_add=%d chk_link=%d", +gatt_if, is_add,
- check_acl_link);
+ log::debug("gatt_if={}, is_add={} chk_link={}", gatt_if, is_add,
+ check_acl_link);
if (!p_tcb) {
- LOG_WARN("p_tcb is null");
+ log::warn("p_tcb is null");
return;
}
// If we make no modification, i.e. kill app that was never connected to a
// device, skip updating the device state.
if (!gatt_update_app_hold_link_status(gatt_if, p_tcb, is_add)) {
- LOG_INFO("App status is not updated for gatt_if=%d", +gatt_if);
+ log::info("App status is not updated for gatt_if={}", gatt_if);
return;
}
if (!check_acl_link) {
- LOG_INFO("check_acl_link is false, no need to check");
+ log::info("check_acl_link is false, no need to check");
return;
}
@@ -382,14 +382,14 @@
if (is_add) {
if (p_tcb->att_lcid == L2CAP_ATT_CID && is_valid_handle) {
- LOG_INFO("disable link idle timer for %s",
- ADDRESS_TO_LOGGABLE_CSTR(p_tcb->peer_bda));
+ log::info("disable link idle timer for {}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_tcb->peer_bda));
/* acl link is connected disable the idle timeout */
GATT_SetIdleTimeout(p_tcb->peer_bda, GATT_LINK_NO_IDLE_TIMEOUT,
p_tcb->transport, true /* is_active */);
} else {
- LOG_INFO("invalid handle %d or dynamic CID %d", is_valid_handle,
- p_tcb->att_lcid);
+ log::info("invalid handle {} or dynamic CID {}", is_valid_handle,
+ p_tcb->att_lcid);
}
} else {
if (p_tcb->app_hold_link.empty()) {
@@ -400,19 +400,19 @@
/* for fixed channel, set the timeout value to
GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP seconds */
- LOG_INFO(
+ log::info(
"GATT fixed channel is no longer useful, start link idle timer for "
- "%d seconds",
+ "{} seconds",
GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP);
GATT_SetIdleTimeout(p_tcb->peer_bda, GATT_LINK_IDLE_TIMEOUT_WHEN_NO_APP,
p_tcb->transport, false /* is_active */);
} else {
// disconnect the dynamic channel
- LOG_INFO("disconnect GATT dynamic channel");
+ log::info("disconnect GATT dynamic channel");
gatt_disconnect(p_tcb);
}
} else {
- LOG_INFO("is_add=false, but some app is still using the ACL link");
+ log::info("is_add=false, but some app is still using the ACL link");
}
}
}
@@ -431,7 +431,7 @@
p_reg->gatt_if))
return false;
} else if (st == GATT_CH_CLOSING) {
- LOG(INFO) << "Must finish disconnection before new connection";
+ log::info("Must finish disconnection before new connection");
/* need to complete the closing first */
return false;
}
@@ -441,13 +441,13 @@
p_tcb = gatt_allocate_tcb_by_bdaddr(bd_addr, transport);
if (!p_tcb) {
- LOG(ERROR) << "Max TCB for gatt_if [ " << +p_reg->gatt_if << "] reached.";
+ log::error("Max TCB for gatt_if [ {}] reached.", p_reg->gatt_if);
return false;
}
if (!gatt_connect(bd_addr, addr_type, p_tcb, transport, initiating_phys,
p_reg->gatt_if)) {
- LOG(ERROR) << "gatt_connect failed";
+ log::error("gatt_connect failed");
fixed_queue_free(p_tcb->pending_ind_q, NULL);
*p_tcb = tGATT_TCB();
return false;
@@ -483,13 +483,13 @@
tGATTS_SRV_CHG* p_srv_chg_clt = NULL;
if (transport == BT_TRANSPORT_BR_EDR) {
- LOG_WARN("Ignoring fixed channel connect/disconnect on br_edr for GATT");
+ log::warn("Ignoring fixed channel connect/disconnect on br_edr for GATT");
return;
}
- VLOG(1) << "GATT ATT protocol channel with BDA: "
- << ADDRESS_TO_LOGGABLE_STR(bd_addr) << " is "
- << ((connected) ? "connected" : "disconnected");
+ log::verbose("GATT ATT protocol channel with BDA: {} is {}",
+ ADDRESS_TO_LOGGABLE_STR(bd_addr),
+ ((connected) ? "connected" : "disconnected"));
p_srv_chg_clt = gatt_is_bda_in_the_srv_chg_clt_list(bd_addr);
if (p_srv_chg_clt != NULL) {
@@ -525,7 +525,7 @@
else {
p_tcb = gatt_allocate_tcb_by_bdaddr(bd_addr, BT_TRANSPORT_LE);
if (!p_tcb) {
- LOG(ERROR) << "CCB max out, no rsources";
+ log::error("CCB max out, no rsources");
return;
}
@@ -550,18 +550,18 @@
}
if (is_device_le_audio_capable(bd_addr)) {
- LOG_INFO("Read model name for le audio capable device");
+ log::info("Read model name for le audio capable device");
if (!check_cached_model_name(bd_addr)) {
if (!DIS_ReadDISInfo(bd_addr, read_dis_cback, DIS_ATTR_MODEL_NUM_BIT)) {
- LOG_WARN("Read DIS failed");
+ log::warn("Read DIS failed");
}
}
} else if (check_cached_model_name(bd_addr)) {
- LOG_INFO("Get cache model name for device");
+ log::info("Get cache model name for device");
}
if (stack_config_get_interface()->get_pts_connect_eatt_before_encryption()) {
- LOG_INFO(" Start EATT before encryption ");
+ log::info("Start EATT before encryption ");
EattExtension::GetInstance()->Connect(bd_addr);
}
}
@@ -575,8 +575,8 @@
if (btif_storage_get_remote_device_property(&bd_addr, &prop) !=
BT_STATUS_SUCCESS ||
prop.len == 0) {
- LOG_INFO("Device %s no cached model name",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::info("Device {} no cached model name",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return false;
}
@@ -587,7 +587,7 @@
static void read_dis_cback(const RawAddress& bd_addr, tDIS_VALUE* p_dis_value) {
if (p_dis_value == NULL) {
- LOG_ERROR("received unexpected/error DIS callback");
+ log::error("received unexpected/error DIS callback");
return;
}
@@ -599,8 +599,8 @@
prop.val = p_dis_value->data_string[i];
prop.len = strlen((char*)prop.val);
- LOG_INFO("Device %s, model name: %s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
- ((char*)prop.val));
+ log::info("Device {}, model name: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr), ((char*)prop.val));
btif_storage_set_remote_device_property(&bd_addr, &prop);
GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(
@@ -608,7 +608,7 @@
}
}
} else {
- LOG_ERROR("unknown bit, mask: %d", (int)p_dis_value->attr_mask);
+ log::error("unknown bit, mask: {}", (int)p_dis_value->attr_mask);
}
}
@@ -637,7 +637,7 @@
uint8_t tx_phy, uint8_t rx_phy) {
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
if (!p_dev_rec) {
- LOG_WARN("No Device Found!");
+ log::warn("No Device Found!");
return;
}
@@ -681,7 +681,7 @@
uint16_t timeout, uint8_t status) {
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
if (!p_dev_rec) {
- LOG_WARN("No Device Found!");
+ log::warn("No Device Found!");
return;
}
@@ -738,8 +738,8 @@
if (decision == bluetooth::shim::arbiter::InterceptAction::DROP) {
// do nothing, just free it at the end
} else if (gatt_get_ch_state(p_tcb) < GATT_CH_OPEN) {
- LOG(WARNING) << "ATT - Ignored L2CAP data while in state: "
- << +gatt_get_ch_state(p_tcb);
+ log::warn("ATT - Ignored L2CAP data while in state: {}",
+ gatt_get_ch_state(p_tcb));
} else
gatt_data_process(*p_tcb, L2CAP_ATT_CID, p_buf);
}
@@ -762,7 +762,7 @@
uint16_t lcid,
UNUSED_ATTR uint16_t psm, uint8_t id) {
uint8_t result = L2CAP_CONN_OK;
- LOG(INFO) << "Connection indication cid = " << +lcid;
+ log::info("Connection indication cid = {}", lcid);
/* new connection ? */
tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bd_addr, BT_TRANSPORT_BR_EDR);
@@ -809,9 +809,8 @@
p_tcb = gatt_find_tcb_by_cid(lcid);
if (!p_tcb) return;
- VLOG(1) << __func__
- << StringPrintf(" result: %d ch_state: %d, lcid:0x%x", result,
- gatt_get_ch_state(p_tcb), p_tcb->att_lcid);
+ log::verbose("result: {} ch_state: {}, lcid:0x{:x}", result,
+ gatt_get_ch_state(p_tcb), p_tcb->att_lcid);
if (gatt_get_ch_state(p_tcb) == GATT_CH_CONN && result == L2CAP_CONN_OK) {
gatt_set_ch_state(p_tcb, GATT_CH_CFG);
@@ -968,8 +967,8 @@
tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(rpa, BT_TRANSPORT_LE);
if (p_tcb == NULL) return;
- LOG_INFO("consolidate %s -> %s", ADDRESS_TO_LOGGABLE_CSTR(rpa),
- ADDRESS_TO_LOGGABLE_CSTR(identity_addr));
+ log::info("consolidate {} -> {}", ADDRESS_TO_LOGGABLE_CSTR(rpa),
+ ADDRESS_TO_LOGGABLE_CSTR(identity_addr));
p_tcb->peer_bda = identity_addr;
// Address changed, notify GATT clients/servers device is available under new
@@ -997,7 +996,7 @@
uint8_t op_code, pseudo_op_code;
if (p_buf->len <= 0) {
- LOG(ERROR) << "invalid data length, ignore";
+ log::error("invalid data length, ignore");
return;
}
@@ -1010,8 +1009,7 @@
if (pseudo_op_code >= GATT_OP_CODE_MAX) {
/* Note: PTS: GATT/SR/UNS/BI-01-C mandates error on unsupported ATT request.
*/
- LOG(ERROR) << __func__
- << ": ATT - Rcvd L2CAP data, unknown cmd: " << loghex(op_code);
+ log::error("ATT - Rcvd L2CAP data, unknown cmd: {}", loghex(op_code));
gatt_send_error_rsp(tcb, cid, GATT_REQ_NOT_SUPPORTED, op_code, 0, false);
return;
}
@@ -1053,14 +1051,14 @@
static const uint16_t sGATT_LAST_HANDLE = (uint16_t)osi_property_get_int32(
"bluetooth.gatt.last_handle_for_srvc_change.value", 0xFFFF);
- VLOG(1) << __func__;
+ log::verbose("");
if (!gatt_cb.handle_of_h_r) return;
uint16_t conn_id = gatt_profile_find_conn_id_by_bd_addr(peer_bda);
if (conn_id == GATT_INVALID_CONN_ID) {
- LOG(ERROR) << "Unable to find conn_id for "
- << ADDRESS_TO_LOGGABLE_STR(peer_bda);
+ log::error("Unable to find conn_id for {}",
+ ADDRESS_TO_LOGGABLE_STR(peer_bda));
return;
}
@@ -1075,7 +1073,7 @@
/** Check sending service chnaged Indication is required or not if required then
* send the Indication */
void gatt_chk_srv_chg(tGATTS_SRV_CHG* p_srv_chg_clt) {
- VLOG(1) << __func__ << " srv_changed=" << +p_srv_chg_clt->srv_changed;
+ log::verbose("srv_changed={}", p_srv_chg_clt->srv_changed);
if (p_srv_chg_clt->srv_changed) {
gatt_send_srv_chg_ind(p_srv_chg_clt->bda);
@@ -1088,9 +1086,9 @@
tGATTS_SRV_CHG_RSP rsp;
tGATTS_SRV_CHG srv_chg_clt;
- VLOG(1) << __func__;
+ log::verbose("");
if (!gatt_cb.cb_info.p_srv_chg_callback) {
- VLOG(1) << __func__ << " callback not registered yet";
+ log::verbose("callback not registered yet");
return;
}
@@ -1099,7 +1097,7 @@
if (!(status && rsp.num_clients)) return;
- VLOG(1) << "num_srv_chg_clt_clients=" << +rsp.num_clients;
+ log::verbose("num_srv_chg_clt_clients={}", rsp.num_clients);
uint8_t num_clients = rsp.num_clients;
uint8_t i = 1; /* use one based index */
while ((i <= num_clients) && status) {
@@ -1109,7 +1107,7 @@
if (status) {
memcpy(&srv_chg_clt, &rsp.srv_chg, sizeof(tGATTS_SRV_CHG));
if (gatt_add_srv_chg_clt(&srv_chg_clt) == NULL) {
- LOG(ERROR) << "Unable to add a service change client";
+ log::error("Unable to add a service change client");
status = false;
}
}
@@ -1123,7 +1121,7 @@
tBT_TRANSPORT transport;
uint8_t found_idx;
- VLOG(1) << __func__;
+ log::verbose("");
if (!gatt_cb.cb_info.p_srv_chg_callback || !gatt_cb.handle_of_h_r) return;
@@ -1136,7 +1134,7 @@
if (gatt_is_srv_chg_ind_pending(p_tcb)) {
send_indication = false;
- VLOG(1) << "discard srv chg - already has one in the queue";
+ log::verbose("discard srv chg - already has one in the queue");
}
// Some LE GATT clients don't respond to service changed indications.
@@ -1145,7 +1143,7 @@
btif_storage_get_stored_remote_name(bda, remote_name)) {
if (interop_match_name(INTEROP_GATTC_NO_SERVICE_CHANGED_IND,
remote_name)) {
- VLOG(1) << "discard srv chg - interop matched " << remote_name;
+ log::verbose("discard srv chg - interop matched {}", remote_name);
send_indication = false;
}
}
@@ -1160,8 +1158,8 @@
void gatt_set_ch_state(tGATT_TCB* p_tcb, tGATT_CH_STATE ch_state) {
if (!p_tcb) return;
- VLOG(1) << __func__ << ": old=" << +p_tcb->ch_state
- << " new=" << loghex(static_cast<uint8_t>(ch_state));
+ log::verbose("old={} new={}", p_tcb->ch_state,
+ loghex(static_cast<uint8_t>(ch_state)));
p_tcb->ch_state = ch_state;
}
@@ -1169,6 +1167,6 @@
tGATT_CH_STATE gatt_get_ch_state(tGATT_TCB* p_tcb) {
if (!p_tcb) return GATT_CH_CLOSE;
- VLOG(1) << "gatt_get_ch_state: ch_state=" << +p_tcb->ch_state;
+ log::verbose("gatt_get_ch_state: ch_state={}", p_tcb->ch_state);
return p_tcb->ch_state;
}
diff --git a/system/stack/gatt/gatt_sr.cc b/system/stack/gatt/gatt_sr.cc
index 50a5693..e7809a1 100644
--- a/system/stack/gatt/gatt_sr.cc
+++ b/system/stack/gatt/gatt_sr.cc
@@ -22,6 +22,7 @@
*
******************************************************************************/
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <string.h>
#include <algorithm>
@@ -43,10 +44,10 @@
#define GATT_MTU_REQ_MIN_LEN 2
#define L2CAP_PKT_OVERHEAD 4
-using base::StringPrintf;
using bluetooth::Uuid;
using bluetooth::eatt::EattExtension;
using bluetooth::eatt::EattChannel;
+using namespace bluetooth;
/*******************************************************************************
*
@@ -68,8 +69,8 @@
EattChannel* channel =
EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid);
if (channel == nullptr) {
- LOG_WARN("%s, cid 0x%02x already disconnected",
- ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
+ log::warn("{}, cid 0x{:02x} already disconnected",
+ ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
return 0;
}
@@ -114,8 +115,8 @@
EattChannel* channel =
EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid);
if (channel == nullptr) {
- LOG_WARN("%s, cid 0x%02x already disconnected",
- ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
+ log::warn("{}, cid 0x{:02x} already disconnected",
+ ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
return false;
}
@@ -140,8 +141,8 @@
EattChannel* channel =
EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid);
if (channel == nullptr) {
- LOG_WARN("%s, cid 0x%02x already disconnected",
- ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
+ log::warn("{}, cid 0x{:02x} already disconnected",
+ ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
return;
}
@@ -149,10 +150,9 @@
}
/* Double check in case any buffers are queued */
- VLOG(1) << "gatt_dequeue_sr_cmd cid: " << loghex(cid);
+ log::verbose("gatt_dequeue_sr_cmd cid: {}", loghex(cid));
if (p_cmd->p_rsp_msg)
- LOG(ERROR) << "free tcb.sr_cmd.p_rsp_msg = "
- << p_cmd->p_rsp_msg;
+ log::error("free tcb.sr_cmd.p_rsp_msg = {}", fmt::ptr(p_cmd->p_rsp_msg));
osi_free_and_reset((void**)&p_cmd->p_rsp_msg);
while (!fixed_queue_is_empty(p_cmd->multi_rsp_q))
@@ -204,22 +204,21 @@
}
if (total_len > mtu) {
- VLOG(1) << "Buffer space not enough for this data item, skipping";
+ log::verbose("Buffer space not enough for this data item, skipping");
break;
}
len = std::min((size_t) p_rsp->attr_value.len, mtu - total_len);
if (len == 0) {
- VLOG(1) << "Buffer space not enough for this data item, skipping";
+ log::verbose("Buffer space not enough for this data item, skipping");
break;
}
if (len < p_rsp->attr_value.len) {
is_overflow = true;
- VLOG(1) << StringPrintf(
- "multi read overflow available len=%zu val_len=%d", len,
- p_rsp->attr_value.len);
+ log::verbose("multi read overflow available len={} val_len={}", len,
+ p_rsp->attr_value.len);
}
if (p_cmd->multi_req.variable_len) {
@@ -246,10 +245,10 @@
/* Sanity check on the buffer length */
if (p_buf->len == 0) {
- LOG(ERROR) << __func__ << " nothing found!!";
+ log::error("nothing found!!");
p_cmd->status = GATT_NOT_FOUND;
osi_free(p_buf);
- VLOG(1) << __func__ << "osi_free(p_buf)";
+ log::verbose("osi_free(p_buf)");
} else if (p_cmd->p_rsp_msg != NULL) {
osi_free(p_buf);
} else {
@@ -268,7 +267,7 @@
******************************************************************************/
static bool process_read_multi_rsp(tGATT_SR_CMD* p_cmd, tGATT_STATUS status,
tGATTS_RSP* p_msg, uint16_t mtu) {
- VLOG(1) << StringPrintf("%s status=%d mtu=%d", __func__, status, mtu);
+ log::verbose("status={} mtu={}", status, mtu);
if (p_cmd->multi_rsp_q == NULL)
p_cmd->multi_rsp_q = fixed_queue_new(SIZE_MAX);
@@ -280,9 +279,9 @@
p_cmd->status = status;
if (status == GATT_SUCCESS) {
- VLOG(1) << "Multi read count=" << fixed_queue_length(p_cmd->multi_rsp_q)
- << " num_hdls=" << p_cmd->multi_req.num_handles
- << " variable=" << p_cmd->multi_req.variable_len;
+ log::verbose("Multi read count={} num_hdls={} variable={}",
+ fixed_queue_length(p_cmd->multi_rsp_q),
+ p_cmd->multi_req.num_handles, p_cmd->multi_req.variable_len);
/* Wait till we get all the responses */
if (fixed_queue_length(p_cmd->multi_rsp_q) ==
p_cmd->multi_req.num_handles) {
@@ -316,7 +315,7 @@
tGATT_STATUS ret_code = GATT_SUCCESS;
uint16_t payload_size = gatt_tcb_get_payload_size(tcb, sr_res_p->cid);
- VLOG(1) << __func__ << " gatt_if=" << +gatt_if;
+ log::verbose("gatt_if={}", gatt_if);
gatt_sr_update_cback_cnt(tcb, sr_res_p->cid, gatt_if, false, false);
@@ -339,7 +338,7 @@
sr_res_p->p_rsp_msg = attp_build_sr_msg(
tcb, (uint8_t)(op_code + 1), (tGATT_SR_MSG*)p_msg, payload_size);
} else {
- LOG(ERROR) << "Exception!!! already has respond message";
+ log::error("Exception!!! already has respond message");
}
}
}
@@ -355,7 +354,7 @@
gatt_dequeue_sr_cmd(tcb, sr_res_p->cid);
}
- VLOG(1) << __func__ << " ret_code=" << +ret_code;
+ log::verbose("ret_code={}", ret_code);
return ret_code;
}
@@ -379,9 +378,9 @@
#if (GATT_CONFORMANCE_TESTING == TRUE)
if (gatt_cb.enable_err_rsp && gatt_cb.req_op_code == op_code) {
- VLOG(1)
- << "Conformance tst: forced err rspv for Execute Write: error status="
- << +gatt_cb.err_status;
+ log::verbose(
+ "Conformance tst: forced err rspv for Execute Write: error status={}",
+ gatt_cb.err_status);
gatt_send_error_rsp(tcb, cid, gatt_cb.err_status, gatt_cb.req_op_code,
gatt_cb.handle, false);
@@ -391,7 +390,7 @@
#endif
if (len < sizeof(flag)) {
- LOG(ERROR) << __func__ << "invalid length";
+ log::error("invalid length");
gatt_send_error_rsp(tcb, cid, GATT_INVALID_PDU, GATT_REQ_EXEC_WRITE, 0,
false);
return;
@@ -420,7 +419,7 @@
}
} else /* nothing needs to be executed , send response now */
{
- LOG(ERROR) << "gatt_process_exec_write_req: no prepare write pending";
+ log::error("gatt_process_exec_write_req: no prepare write pending");
gatt_send_error_rsp(tcb, cid, GATT_ERROR, GATT_REQ_EXEC_WRITE, 0, false);
}
}
@@ -444,12 +443,12 @@
tGATT_SEC_FLAG sec_flag;
uint8_t key_size;
- VLOG(1) << __func__;
+ log::verbose("");
tGATT_READ_MULTI* multi_req = gatt_sr_get_read_multi(tcb, cid);
if (multi_req == nullptr) {
- LOG_ERROR("Could not proceed request. %s, 0x%02x",
- ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
+ log::error("Could not proceed request. {}, 0x{:02x}",
+ ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
return;
}
multi_req->num_handles = 0;
@@ -458,8 +457,9 @@
#if (GATT_CONFORMANCE_TESTING == TRUE)
if (gatt_cb.enable_err_rsp && gatt_cb.req_op_code == op_code) {
- VLOG(1) << "Conformance tst: forced err rspvofr ReadMultiple: error status="
- << +gatt_cb.err_status;
+ log::verbose(
+ "Conformance tst: forced err rspvofr ReadMultiple: error status={}",
+ gatt_cb.err_status);
STREAM_TO_UINT16(handle, p);
@@ -481,7 +481,7 @@
err = gatts_read_attr_perm_check(it->p_db, false, handle, sec_flag,
key_size);
if (err != GATT_SUCCESS) {
- VLOG(1) << StringPrintf("read permission denied : 0x%02x", err);
+ log::verbose("read permission denied : 0x{:02x}", err);
break;
}
} else {
@@ -493,7 +493,7 @@
}
if (ll != 0) {
- LOG(ERROR) << "max attribute handle reached in ReadMultiple Request.";
+ log::error("max attribute handle reached in ReadMultiple Request.");
}
if (multi_req->num_handles == 0) err = GATT_INVALID_HANDLE;
@@ -503,8 +503,8 @@
if (trans_id != 0) {
tGATT_SR_CMD* sr_cmd_p = gatt_sr_get_cmd_by_cid(tcb, cid);
if (sr_cmd_p == nullptr) {
- LOG_ERROR(
- "Could not send response on CID were request arrived. %s, 0x%02x",
+ log::error(
+ "Could not send response on CID were request arrived. {}, 0x{:02x}",
ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
return;
}
@@ -595,7 +595,7 @@
if (gatt_cb.last_service_handle &&
gatt_cb.last_service_handle == el.s_hdl) {
- VLOG(1) << "Use 0xFFFF for the last primary attribute";
+ log::verbose("Use 0xFFFF for the last primary attribute");
/* see GATT ERRATA 4065, 4063, ATT ERRATA 4062 */
UINT16_TO_STREAM(p, 0xFFFF);
} else {
@@ -655,7 +655,7 @@
UINT16_TO_STREAM(p, attr.handle);
ARRAY_TO_STREAM(p, attr.uuid.To128BitLE(), (int)Uuid::kNumBytes128);
} else {
- LOG(ERROR) << "format mismatch";
+ log::error("format mismatch");
return GATT_NO_RESOURCES;
/* format mismatch */
}
@@ -697,7 +697,7 @@
CHECK(p_uuid);
uint16_t uuid_len = (op_code == GATT_REQ_FIND_TYPE_VALUE) ? 2 : len;
if (!gatt_parse_uuid_from_cmd(p_uuid, uuid_len, &p)) {
- VLOG(1) << "Bad UUID";
+ log::verbose("Bad UUID");
return GATT_INVALID_PDU;
}
@@ -733,15 +733,13 @@
if (op_code == GATT_REQ_READ_BY_GRP_TYPE) {
gatt_send_error_rsp(tcb, cid, GATT_UNSUPPORT_GRP_TYPE, op_code, s_hdl,
false);
- VLOG(1) << StringPrintf("unexpected ReadByGrpType Group: %s",
- uuid.ToString().c_str());
+ log::verbose("unexpected ReadByGrpType Group: {}", uuid.ToString());
return;
}
// we do not support ReadByTypeValue with any non-primamry_service type
gatt_send_error_rsp(tcb, cid, GATT_NOT_FOUND, op_code, s_hdl, false);
- VLOG(1) << StringPrintf("unexpected ReadByTypeValue type: %s",
- uuid.ToString().c_str());
+ log::verbose("unexpected ReadByTypeValue type: {}", uuid.ToString());
return;
}
@@ -843,7 +841,7 @@
}
if (len < GATT_MTU_REQ_MIN_LEN) {
- LOG(ERROR) << "invalid MTU request PDU received.";
+ log::error("invalid MTU request PDU received.");
gatt_send_error_rsp(tcb, cid, GATT_INVALID_PDU, GATT_REQ_MTU, 0, false);
return;
}
@@ -863,8 +861,8 @@
/* Always say to remote our default MTU. */
gatt_sr_msg.mtu = gatt_get_local_mtu();
- LOG_INFO("MTU %d request from remote (%s), resulted MTU %d", mtu,
- tcb.peer_bda.ToString().c_str(), tcb.payload_size);
+ log::info("MTU {} request from remote ({}), resulted MTU {}", mtu,
+ tcb.peer_bda.ToString(), tcb.payload_size);
BTM_SetBleDataLength(tcb.peer_bda, tcb.payload_size + L2CAP_PKT_OVERHEAD);
@@ -913,8 +911,9 @@
#if (GATT_CONFORMANCE_TESTING == TRUE)
if (gatt_cb.enable_err_rsp && gatt_cb.req_op_code == op_code) {
- VLOG(1) << "Conformance tst: forced err rsp for ReadByType: error status="
- << +gatt_cb.err_status;
+ log::verbose(
+ "Conformance tst: forced err rsp for ReadByType: error status={}",
+ gatt_cb.err_status);
gatt_send_error_rsp(tcb, cid, gatt_cb.err_status, gatt_cb.req_op_code,
s_hdl, false);
@@ -997,9 +996,9 @@
switch (op_code) {
case GATT_REQ_PREPARE_WRITE:
if (len < 2 || p == nullptr) {
- LOG(ERROR) << __func__
- << ": Prepare write request was invalid - missing offset, "
- "sending error response";
+ log::error(
+ "Prepare write request was invalid - missing offset, sending error "
+ "response");
gatt_send_error_rsp(tcb, cid, GATT_INVALID_PDU, op_code, handle, false);
return;
}
@@ -1009,7 +1008,7 @@
FALLTHROUGH_INTENDED; /* FALLTHROUGH */
case GATT_SIGN_CMD_WRITE:
if (op_code == GATT_SIGN_CMD_WRITE) {
- VLOG(1) << "Write CMD with data sigining";
+ log::verbose("Write CMD with data sigining");
len -= GATT_AUTH_SIGN_LEN;
}
FALLTHROUGH_INTENDED; /* FALLTHROUGH */
@@ -1043,9 +1042,9 @@
} else if (gatt_type == BTGATT_DB_CHARACTERISTIC) {
opcode = GATTS_REQ_TYPE_WRITE_CHARACTERISTIC;
} else {
- LOG(ERROR) << __func__
- << "%s: Attempt to write attribute that's not tied with"
- " characteristic or descriptor value.";
+ log::error(
+ "Attempt to write attribute that's not tied with "
+ "characteristic or descriptor value.");
status = GATT_ERROR;
}
@@ -1054,7 +1053,7 @@
status = GATT_PENDING;
}
} else {
- LOG(ERROR) << "max pending command, send error";
+ log::error("max pending command, send error");
status = GATT_BUSY; /* max pending command, application error */
}
}
@@ -1082,8 +1081,7 @@
if (op_code == GATT_REQ_READ_BLOB && len < sizeof(uint16_t)) {
/* Error: packet length is too short */
- LOG(ERROR) << __func__ << ": packet length=" << len
- << " too short. min=" << sizeof(uint16_t);
+ log::error("packet length={} too short. min={}", len, sizeof(uint16_t));
gatt_send_error_rsp(tcb, cid, GATT_INVALID_PDU, op_code, 0, false);
return;
}
@@ -1138,7 +1136,7 @@
tGATT_STATUS status = GATT_INVALID_HANDLE;
if (len < 2) {
- LOG(ERROR) << "Illegal PDU length, discard request";
+ log::error("Illegal PDU length, discard request");
status = GATT_INVALID_PDU;
} else {
STREAM_TO_UINT16(handle, p);
@@ -1148,8 +1146,8 @@
#if (GATT_CONFORMANCE_TESTING == TRUE)
gatt_cb.handle = handle;
if (gatt_cb.enable_err_rsp && gatt_cb.req_op_code == op_code) {
- VLOG(1) << "Conformance tst: forced err rsp: error status="
- << +gatt_cb.err_status;
+ log::verbose("Conformance tst: forced err rsp: error status={}",
+ gatt_cb.err_status);
gatt_send_error_rsp(tcb, cid, gatt_cb.err_status, cid, gatt_cb.req_op_code,
handle, false);
@@ -1206,11 +1204,11 @@
tGATTS_SRV_CHG_REQ req;
tGATTS_SRV_CHG* p_buf = NULL;
- VLOG(1) << __func__;
+ log::verbose("");
p_buf = gatt_is_bda_in_the_srv_chg_clt_list(tcb.peer_bda);
if (p_buf != NULL) {
- VLOG(1) << "NV update set srv chg = false";
+ log::verbose("NV update set srv chg = false");
p_buf->srv_changed = false;
memcpy(&req.srv_chg, p_buf, sizeof(tGATTS_SRV_CHG));
if (gatt_cb.cb_info.p_srv_chg_callback)
@@ -1230,7 +1228,7 @@
*
******************************************************************************/
static void gatts_chk_pending_ind(tGATT_TCB& tcb) {
- VLOG(1) << __func__;
+ log::verbose("");
tGATT_VALUE* p_buf =
(tGATT_VALUE*)fixed_queue_try_peek_first(tcb.pending_ind_q);
@@ -1254,7 +1252,7 @@
static bool gatts_proc_ind_ack(tGATT_TCB& tcb, uint16_t ack_handle) {
bool continue_processing = true;
- VLOG(1) << __func__ << " ack handle=%d" << ack_handle;
+ log::verbose("ack handle={}", ack_handle);
if (ack_handle == gatt_cb.handle_of_h_r) {
gatts_proc_srv_chg_ind_ack(tcb);
@@ -1284,7 +1282,7 @@
uint16_t handle;
if (!gatt_tcb_find_indicate_handle(tcb, cid, &handle)) {
- LOG(ERROR) << "unexpected handle value confirmation";
+ log::error("unexpected handle value confirmation");
return;
}
@@ -1371,10 +1369,9 @@
gatt_send_error_rsp(tcb, cid, GATT_DATABASE_OUT_OF_SYNC, op_code, 0x0000,
false);
}
- LOG(INFO) << __func__ << ": database out of sync, device="
- << ADDRESS_TO_LOGGABLE_STR(tcb.peer_bda)
- << ", op_code=" << loghex((uint16_t)op_code)
- << ", should_rsp=" << should_rsp;
+ log::info("database out of sync, device={}, op_code={}, should_rsp={}",
+ ADDRESS_TO_LOGGABLE_STR(tcb.peer_bda), loghex((uint16_t)op_code),
+ should_rsp);
gatt_sr_update_cl_status(tcb, /* chg_aware= */ should_rsp);
}
@@ -1394,8 +1391,8 @@
uint16_t payload_size = gatt_tcb_get_payload_size(tcb, cid);
if (len >= payload_size) {
- LOG(ERROR) << StringPrintf("server receive invalid PDU size:%d pdu size:%d",
- len + 1, payload_size);
+ log::error("server receive invalid PDU size:{} pdu size:{}", len + 1,
+ payload_size);
/* for invalid request expecting response, send it now */
if (op_code != GATT_CMD_WRITE && op_code != GATT_SIGN_CMD_WRITE &&
op_code != GATT_HANDLE_VALUE_CONF) {
diff --git a/system/stack/gatt/gatt_sr_hash.cc b/system/stack/gatt/gatt_sr_hash.cc
index 660ffe1..1400379 100644
--- a/system/stack/gatt/gatt_sr_hash.cc
+++ b/system/stack/gatt/gatt_sr_hash.cc
@@ -18,6 +18,7 @@
#include <base/logging.h>
#include <base/strings/string_number_conversions.h>
+#include <bluetooth/log.h>
#include <list>
@@ -27,6 +28,7 @@
#include "types/bluetooth/uuid.h"
using bluetooth::Uuid;
+using namespace bluetooth;
static size_t calculate_database_info_size(std::list<tGATT_SRV_LIST_ELEM>* lst_ptr) {
size_t len = 0;
@@ -125,8 +127,7 @@
std::reverse(serialized.begin(), serialized.end());
Octet16 db_hash = crypto_toolbox::aes_cmac(Octet16{0}, serialized.data(),
serialized.size());
- LOG(INFO) << __func__ << ": hash="
- << base::HexEncode(db_hash.data(), db_hash.size());
+ log::info("hash={}", base::HexEncode(db_hash.data(), db_hash.size()));
return db_hash;
}
diff --git a/system/stack/gatt/gatt_utils.cc b/system/stack/gatt/gatt_utils.cc
index 0e8bf7e..575d24f 100644
--- a/system/stack/gatt/gatt_utils.cc
+++ b/system/stack/gatt/gatt_utils.cc
@@ -25,6 +25,7 @@
#include <base/logging.h>
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <cstdint>
#include <deque>
@@ -50,8 +51,8 @@
uint8_t btm_ble_read_sec_key_size(const RawAddress& bd_addr);
using namespace bluetooth::legacy::stack::sdp;
+using namespace bluetooth;
-using base::StringPrintf;
using bluetooth::Uuid;
using bluetooth::eatt::EattExtension;
using bluetooth::eatt::EattChannel;
@@ -114,7 +115,7 @@
*
******************************************************************************/
void gatt_free_pending_ind(tGATT_TCB* p_tcb) {
- VLOG(1) << __func__;
+ log::verbose("");
if (p_tcb->pending_ind_q == NULL) return;
@@ -135,7 +136,7 @@
*
******************************************************************************/
void gatt_delete_dev_from_srv_chg_clt_list(const RawAddress& bd_addr) {
- VLOG(1) << __func__;
+ log::verbose("");
tGATTS_SRV_CHG* p_buf = gatt_is_bda_in_the_srv_chg_clt_list(bd_addr);
if (p_buf != NULL) {
@@ -160,18 +161,18 @@
*
******************************************************************************/
void gatt_set_srv_chg(void) {
- VLOG(1) << __func__;
+ log::verbose("");
if (fixed_queue_is_empty(gatt_cb.srv_chg_clt_q)) return;
list_t* list = fixed_queue_get_list(gatt_cb.srv_chg_clt_q);
for (const list_node_t* node = list_begin(list); node != list_end(list);
node = list_next(node)) {
- VLOG(1) << "found a srv_chg clt";
+ log::verbose("found a srv_chg clt");
tGATTS_SRV_CHG* p_buf = (tGATTS_SRV_CHG*)list_node(node);
if (!p_buf->srv_changed) {
- VLOG(1) << "set srv_changed to true";
+ log::verbose("set srv_changed to true");
p_buf->srv_changed = true;
tGATTS_SRV_CHG_REQ req;
memcpy(&req.srv_chg, p_buf, sizeof(tGATTS_SRV_CHG));
@@ -184,7 +185,7 @@
/** Add a pending indication */
void gatt_add_pending_ind(tGATT_TCB* p_tcb, tGATT_VALUE* p_ind) {
- VLOG(1) << __func__ << "enqueue a pending indication";
+ log::verbose("enqueue a pending indication");
tGATT_VALUE* p_buf = (tGATT_VALUE*)osi_malloc(sizeof(tGATT_VALUE));
memcpy(p_buf, p_ind, sizeof(tGATT_VALUE));
@@ -203,7 +204,7 @@
******************************************************************************/
tGATTS_SRV_CHG* gatt_add_srv_chg_clt(tGATTS_SRV_CHG* p_srv_chg) {
tGATTS_SRV_CHG* p_buf = (tGATTS_SRV_CHG*)osi_malloc(sizeof(tGATTS_SRV_CHG));
- VLOG(1) << __func__ << "enqueue a srv chg client";
+ log::verbose("enqueue a srv chg client");
memcpy(p_buf, p_srv_chg, sizeof(tGATTS_SRV_CHG));
fixed_queue_enqueue(gatt_cb.srv_chg_clt_q, p_buf);
@@ -276,7 +277,7 @@
tBT_TRANSPORT* p_transport) {
uint8_t i;
bool found = false;
- LOG_DEBUG("start_idx=%d", +start_idx);
+ log::debug("start_idx={}", start_idx);
for (i = start_idx; i < GATT_MAX_PHY_CHANNEL; i++) {
if (gatt_cb.tcb[i].in_use && gatt_cb.tcb[i].ch_state == GATT_CH_OPEN) {
@@ -284,11 +285,11 @@
*p_found_idx = i;
*p_transport = gatt_cb.tcb[i].transport;
found = true;
- LOG_DEBUG("bda: %s", ADDRESS_TO_LOGGABLE_CSTR(bda));
+ log::debug("bda: {}", ADDRESS_TO_LOGGABLE_CSTR(bda));
break;
}
}
- LOG_DEBUG("found=%d found_idx=%d", found, +i);
+ log::debug("found={} found_idx={}", found, i);
return found;
}
@@ -303,8 +304,7 @@
*
******************************************************************************/
bool gatt_is_srv_chg_ind_pending(tGATT_TCB* p_tcb) {
- VLOG(1) << __func__
- << " is_queue_empty=" << fixed_queue_is_empty(p_tcb->pending_ind_q);
+ log::verbose("is_queue_empty={}", fixed_queue_is_empty(p_tcb->pending_ind_q));
if (p_tcb->indicate_handle == gatt_cb.handle_of_h_r) return true;
@@ -337,8 +337,7 @@
*
******************************************************************************/
tGATTS_SRV_CHG* gatt_is_bda_in_the_srv_chg_clt_list(const RawAddress& bda) {
-
- VLOG(1) << __func__ << ": " << bda;
+ log::verbose("{}", ADDRESS_TO_LOGGABLE_STR(bda));
if (fixed_queue_is_empty(gatt_cb.srv_chg_clt_q)) return NULL;
@@ -347,7 +346,7 @@
node = list_next(node)) {
tGATTS_SRV_CHG* p_buf = (tGATTS_SRV_CHG*)list_node(node);
if (bda == p_buf->bda) {
- VLOG(1) << "bda is in the srv chg clt list";
+ log::verbose("bda is in the srv chg clt list");
return p_buf;
}
}
@@ -496,9 +495,9 @@
p_tcb->conn_ids_waiting_for_mtu_exchange.end(), conn_id);
if (it == p_tcb->conn_ids_waiting_for_mtu_exchange.end()) {
p_tcb->conn_ids_waiting_for_mtu_exchange.push_back(conn_id);
- LOG_INFO("Put conn_id=0x%04x on wait list", conn_id);
+ log::info("Put conn_id=0x{:04x} on wait list", conn_id);
} else {
- LOG_INFO("Conn_id=0x%04x already on wait list", conn_id);
+ log::info("Conn_id=0x{:04x} already on wait list", conn_id);
}
}
@@ -555,12 +554,12 @@
/* do not allow 32 bits UUID in ATT PDU now */
case Uuid::kNumBytes32:
- LOG(ERROR) << "DO NOT ALLOW 32 BITS UUID IN ATT PDU";
+ log::error("DO NOT ALLOW 32 BITS UUID IN ATT PDU");
return false;
case 0:
default:
if (uuid_size != 0) ret = false;
- LOG(WARNING) << __func__ << ": invalid uuid size";
+ log::warn("invalid uuid size");
break;
}
@@ -690,16 +689,16 @@
tGATT_CLCB* p_clcb = (tGATT_CLCB*)data;
if (p_clcb == NULL || p_clcb->p_tcb == NULL) {
- LOG(WARNING) << __func__ << " clcb is already deleted";
+ log::warn("clcb is already deleted");
return;
}
if (p_clcb->operation == GATTC_OPTYPE_DISCOVERY &&
p_clcb->op_subtype == GATT_DISC_SRVC_ALL &&
p_clcb->retry_count < GATT_REQ_RETRY_LIMIT) {
uint8_t rsp_code;
- LOG(WARNING) << __func__ << " retry discovery primary service";
+ log::warn("retry discovery primary service");
if (p_clcb != gatt_cmd_dequeue(*p_clcb->p_tcb, p_clcb->cid, &rsp_code)) {
- LOG(ERROR) << __func__ << " command queue out of sync, disconnect";
+ log::error("command queue out of sync, disconnect");
} else {
p_clcb->retry_count++;
gatt_act_discovery(p_clcb);
@@ -710,11 +709,11 @@
auto eatt_channel = EattExtension::GetInstance()->FindEattChannelByCid(
p_clcb->p_tcb->peer_bda, p_clcb->cid);
if (eatt_channel) {
- LOG_WARN("disconnecting EATT cid: %d", p_clcb->cid);
+ log::warn("disconnecting EATT cid: {}", p_clcb->cid);
EattExtension::GetInstance()->Disconnect(p_clcb->p_tcb->peer_bda,
p_clcb->cid);
} else {
- LOG_WARN("disconnecting GATT...");
+ log::warn("disconnecting GATT...");
gatt_disconnect(p_clcb->p_tcb);
}
}
@@ -747,13 +746,14 @@
* TODO: In future, we should properly expose CCC, and send indication only
* to devices that register for it.
*/
- LOG(WARNING) << " Service Changed notification timed out in 30 "
- "seconds, assuming server-only remote, not disconnecting";
+ log::warn(
+ "Service Changed notification timed out in 30 seconds, assuming "
+ "server-only remote, not disconnecting");
gatts_proc_srv_chg_ind_ack(*p_tcb);
return;
}
- LOG(WARNING) << __func__ << " disconnecting...";
+ log::warn("disconnecting...");
gatt_disconnect(p_tcb);
}
@@ -770,7 +770,7 @@
tGATT_TCB* p_tcb = (tGATT_TCB*)data;
CHECK(p_tcb);
- LOG(WARNING) << __func__ << ": send ack now";
+ log::warn("send ack now");
p_tcb->ind_count = 0;
/*TODO: For now ATT used only, but we need to have timeout per CID
* and use it here corretly.
@@ -836,14 +836,14 @@
tGATT_REG* p_reg = gatt_get_regcb(gatt_if);
if (!p_reg) {
- LOG(ERROR) << "p_reg not found discard request";
+ log::error("p_reg not found discard request");
return;
}
if (p_reg->in_use && p_reg->app_cb.p_req_cb) {
(*p_reg->app_cb.p_req_cb)(conn_id, trans_id, type, p_data);
} else {
- LOG(WARNING) << "Call back not found for application conn_id=" << conn_id;
+ log::warn("Call back not found for application conn_id={}", conn_id);
}
}
@@ -893,8 +893,7 @@
uint8_t buff[60];
uint8_t* p = buff;
- VLOG(1) << __func__
- << StringPrintf(" s_hdl=0x%x s_hdl=0x%x", start_hdl, end_hdl);
+ log::verbose("s_hdl=0x{:x} s_hdl=0x{:x}", start_hdl, end_hdl);
uint32_t sdp_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord();
if (sdp_handle == 0) return 0;
@@ -958,9 +957,8 @@
*
******************************************************************************/
void gatt_set_err_rsp(bool enable, uint8_t req_op_code, uint8_t err_status) {
- VLOG(1) << __func__
- << StringPrintf(" enable=%d op_code=%d, err_status=%d", enable,
- req_op_code, err_status);
+ log::verbose("enable={} op_code={}, err_status={}", enable, req_op_code,
+ err_status);
gatt_cb.enable_err_rsp = enable;
gatt_cb.req_op_code = req_op_code;
gatt_cb.err_status = err_status;
@@ -981,7 +979,7 @@
tGATT_REG* p_reg = NULL;
if (ii < 1 || ii > GATT_MAX_APPS) {
- LOG(WARNING) << "gatt_if out of range = " << +ii;
+ log::warn("gatt_if out of range = {}", ii);
return NULL;
}
@@ -989,7 +987,7 @@
p_reg = &gatt_cb.cl_rcb[ii - 1];
if (!p_reg->in_use) {
- LOG(WARNING) << "gatt_if found but not in use.";
+ log::warn("gatt_if found but not in use.");
return NULL;
}
@@ -1012,8 +1010,8 @@
EattChannel* channel =
EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid);
if (channel == nullptr) {
- LOG_WARN("%s, cid 0x%02x already disconnected",
- ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
+ log::warn("{}, cid 0x{:02x} already disconnected",
+ ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
return false;
}
@@ -1051,8 +1049,8 @@
* bigger than that and also if it is bigger, we believe it should not
* cause the problem. This WARN is just to monitor number of CLCB and will
* help in debugging in case we are wrong */
- LOG_WARN("Number of CLCB: %zu > %d", gatt_cb.clcb_queue.size(),
- GATT_CL_MAX_LCB);
+ log::warn("Number of CLCB: {} > {}", gatt_cb.clcb_queue.size(),
+ GATT_CL_MAX_LCB);
}
return p_clcb;
}
@@ -1156,8 +1154,8 @@
EattChannel* channel =
EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid);
if (channel == nullptr) {
- LOG_WARN("%s, cid 0x%02x already disconnected",
- ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
+ log::warn("{}, cid 0x{:02x} already disconnected",
+ ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
return 0;
}
@@ -1205,8 +1203,9 @@
if (!p_tcb->pending_enc_clcb.empty()) {
for (size_t i = 0; i < p_tcb->pending_enc_clcb.size(); i++) {
if (p_tcb->pending_enc_clcb.at(i) == p_clcb) {
- LOG_WARN("Removing clcb (%p) for conn id=0x%04x from pending_enc_clcb",
- p_clcb, p_clcb->conn_id);
+ log::warn(
+ "Removing clcb ({}) for conn id=0x{:04x} from pending_enc_clcb",
+ fmt::ptr(p_clcb), p_clcb->conn_id);
p_tcb->pending_enc_clcb.at(i) = NULL;
break;
}
@@ -1219,8 +1218,8 @@
EattChannel* channel = EattExtension::GetInstance()->FindEattChannelByCid(
p_tcb->peer_bda, cid);
if (channel == nullptr) {
- LOG_WARN("%s, cid 0x%02x already disconnected",
- ADDRESS_TO_LOGGABLE_CSTR(p_tcb->peer_bda), cid);
+ log::warn("{}, cid 0x{:02x} already disconnected",
+ ADDRESS_TO_LOGGABLE_CSTR(p_tcb->peer_bda), cid);
return;
}
cl_cmd_q_p = &channel->cl_cmd_q_;
@@ -1240,15 +1239,15 @@
if (iter->to_send) {
/* If command was not send, just remove the entire element */
cl_cmd_q_p->erase(iter);
- LOG_WARN("Removing scheduled clcb (%p) for conn_id=0x%04x", p_clcb,
- p_clcb->conn_id);
+ log::warn("Removing scheduled clcb ({}) for conn_id=0x{:04x}",
+ fmt::ptr(p_clcb), p_clcb->conn_id);
} else {
/* If command has been sent, just invalidate p_clcb pointer for proper
* response handling */
iter->p_clcb = NULL;
- LOG_WARN(
- "Invalidating clcb (%p) for already sent request on conn_id=0x%04x",
- p_clcb, p_clcb->conn_id);
+ log::warn(
+ "Invalidating clcb ({}) for already sent request on conn_id=0x{:04x}",
+ fmt::ptr(p_clcb), p_clcb->conn_id);
}
}
/*******************************************************************************
@@ -1368,8 +1367,8 @@
EattChannel* channel =
EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid);
if (channel == nullptr) {
- LOG_WARN("%s, cid 0x%02x already disconnected",
- ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
+ log::warn("{}, cid 0x{:02x} already disconnected",
+ ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
return;
}
channel->server_outstanding_cmd_.cback_cnt[i] = 0;
@@ -1396,15 +1395,15 @@
tGATT_SR_CMD* gatt_sr_get_cmd_by_cid(tGATT_TCB& tcb, uint16_t cid) {
tGATT_SR_CMD* sr_cmd_p;
- LOG(INFO) << __func__ << " cid: " << int(cid) << " tcb cid " << tcb.att_lcid;
+ log::info("cid: {} tcb cid {}", int(cid), tcb.att_lcid);
if (cid == tcb.att_lcid) {
sr_cmd_p = &tcb.sr_cmd;
} else {
EattChannel* channel =
EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid);
if (channel == nullptr) {
- LOG_WARN("%s, cid 0x%02x already disconnected",
- ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
+ log::warn("{}, cid 0x{:02x} already disconnected",
+ ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
return nullptr;
}
@@ -1418,15 +1417,15 @@
tGATT_READ_MULTI* gatt_sr_get_read_multi(tGATT_TCB& tcb, uint16_t cid) {
tGATT_READ_MULTI* read_multi_p;
- LOG(INFO) << __func__ << " cid: " << int(cid) << " tcb cid " << tcb.att_lcid;
+ log::info("cid: {} tcb cid {}", int(cid), tcb.att_lcid);
if (cid == tcb.att_lcid) {
read_multi_p = &tcb.sr_cmd.multi_req;
} else {
EattChannel* channel =
EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid);
if (channel == nullptr) {
- LOG_WARN("%s, cid 0x%02x already disconnected",
- ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
+ log::warn("{}, cid 0x{:02x} already disconnected",
+ ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
return nullptr;
}
read_multi_p = &channel->server_outstanding_cmd_.multi_req;
@@ -1455,8 +1454,8 @@
EattChannel* channel =
EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid);
if (channel == nullptr) {
- LOG_WARN("%s, cid 0x%02x already disconnected",
- ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
+ log::warn("{}, cid 0x{:02x} already disconnected",
+ ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
return;
}
sr_cmd_p = &channel->server_outstanding_cmd_;
@@ -1487,9 +1486,8 @@
bool is_reset_first) {
uint8_t idx = ((uint8_t)gatt_if) - 1;
- VLOG(1) << StringPrintf(
- "%s tcb idx=%d gatt_if=%d is_inc=%d is_reset_first=%d", __func__,
- tcb.tcb_idx, gatt_if, is_inc, is_reset_first);
+ log::verbose("tcb idx={} gatt_if={} is_inc={} is_reset_first={}", tcb.tcb_idx,
+ gatt_if, is_inc, is_reset_first);
if (is_reset_first) {
gatt_sr_reset_prep_cnt(tcb);
@@ -1507,23 +1505,22 @@
bool gatt_cancel_open(tGATT_IF gatt_if, const RawAddress& bda) {
tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bda, BT_TRANSPORT_LE);
if (!p_tcb) {
- LOG_WARN(
- "Unable to cancel open for unknown connection gatt_if:%hhu peer:%s",
- gatt_if, ADDRESS_TO_LOGGABLE_CSTR(bda));
+ log::warn("Unable to cancel open for unknown connection gatt_if:{} peer:{}",
+ gatt_if, ADDRESS_TO_LOGGABLE_CSTR(bda));
return true;
}
if (gatt_get_ch_state(p_tcb) == GATT_CH_OPEN) {
- LOG(ERROR) << __func__ << ": link connected Too late to cancel";
+ log::error("link connected Too late to cancel");
return false;
}
gatt_update_app_use_link_flag(gatt_if, p_tcb, false, false);
if (p_tcb->app_hold_link.empty()) {
- LOG_DEBUG(
- "Client reference count is zero disconnecting device gatt_if:%hhu "
- "peer:%s",
+ log::debug(
+ "Client reference count is zero disconnecting device gatt_if:{} "
+ "peer:{}",
gatt_if, ADDRESS_TO_LOGGABLE_CSTR(bda));
gatt_disconnect(p_tcb);
}
@@ -1536,14 +1533,14 @@
if (!connection_manager::direct_connect_remove(gatt_if, bda)) {
if (!connection_manager::is_background_connection(bda)) {
BTM_AcceptlistRemove(bda);
- LOG_INFO(
- "Gatt connection manager has no background record but "
- " removed filter acceptlist gatt_if:%hhu peer:%s",
+ log::info(
+ "Gatt connection manager has no background record but removed "
+ "filter acceptlist gatt_if:{} peer:{}",
gatt_if, ADDRESS_TO_LOGGABLE_CSTR(bda));
} else {
- LOG_INFO(
- "Gatt connection manager maintains a background record"
- " preserving filter acceptlist gatt_if:%hhu peer:%s",
+ log::info(
+ "Gatt connection manager maintains a background record preserving "
+ "filter acceptlist gatt_if:{} peer:{}",
gatt_if, ADDRESS_TO_LOGGABLE_CSTR(bda));
}
}
@@ -1568,8 +1565,8 @@
EattChannel* channel =
EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cmd.cid);
if (channel == nullptr) {
- LOG_WARN("%s, cid 0x%02x already disconnected",
- ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cmd.cid);
+ log::warn("{}, cid 0x{:02x} already disconnected",
+ ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cmd.cid);
return false;
}
channel->cl_cmd_q_.push_back(cmd);
@@ -1588,8 +1585,8 @@
EattChannel* channel =
EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cid);
if (channel == nullptr) {
- LOG_WARN("%s, cid 0x%02x already disconnected",
- ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
+ log::warn("{}, cid 0x{:02x} already disconnected",
+ ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cid);
return nullptr;
}
@@ -1606,8 +1603,8 @@
* peer, device p_clcb will be null.
*/
if (p_clcb && p_clcb->cid != cid) {
- LOG_WARN(" CID does not match (%d!=%d), conn_id=0x%04x", p_clcb->cid, cid,
- p_clcb->conn_id);
+ log::warn("CID does not match ({}!={}), conn_id=0x{:04x}", p_clcb->cid, cid,
+ p_clcb->conn_id);
}
cl_cmd_q_p->pop_front();
@@ -1662,9 +1659,8 @@
uint16_t conn_id;
uint8_t operation;
- VLOG(1) << __func__
- << StringPrintf(" status=%d op=%d subtype=%d", status,
- p_clcb->operation, p_clcb->op_subtype);
+ log::verbose("status={} op={} subtype={}", status, p_clcb->operation,
+ p_clcb->op_subtype);
memset(&cb_data.att_value, 0, sizeof(tGATT_VALUE));
if (p_cmpl_cb != NULL && p_clcb->operation != 0) {
@@ -1673,9 +1669,7 @@
cb_data.att_value.len = p_clcb->counter;
if (cb_data.att_value.len > GATT_MAX_ATTR_LEN) {
- LOG(WARNING) << __func__
- << StringPrintf(" Large cb_data.att_value, size=%d",
- cb_data.att_value.len);
+ log::warn("Large cb_data.att_value, size={}", cb_data.att_value.len);
cb_data.att_value.len = GATT_MAX_ATTR_LEN;
}
@@ -1690,7 +1684,7 @@
if (p_data) {
cb_data.att_value = *((tGATT_VALUE*)p_data);
} else {
- VLOG(1) << "Rcv Prepare write rsp but no data";
+ log::verbose("Rcv Prepare write rsp but no data");
}
}
}
@@ -1716,23 +1710,21 @@
else if (p_cmpl_cb && op)
(*p_cmpl_cb)(conn_id, op, status, &cb_data);
else
- LOG(WARNING) << __func__
- << StringPrintf(
- ": not sent out op=%d p_disc_cmpl_cb:%p p_cmpl_cb:%p",
- operation, p_disc_cmpl_cb, p_cmpl_cb);
+ log::warn("not sent out op={} p_disc_cmpl_cb:{} p_cmpl_cb:{}", operation,
+ fmt::ptr(p_disc_cmpl_cb), fmt::ptr(p_cmpl_cb));
}
/** This function cleans up the control blocks when L2CAP channel disconnect */
void gatt_cleanup_upon_disc(const RawAddress& bda, tGATT_DISCONN_REASON reason,
tBT_TRANSPORT transport) {
- VLOG(1) << __func__;
+ log::verbose("");
tGATT_TCB* p_tcb = gatt_find_tcb_by_addr(bda, transport);
if (!p_tcb) {
- LOG_ERROR(
- "Disconnect for unknown connection bd_addr:%s reason:%s transport:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bda), gatt_disconnection_reason_text(reason).c_str(),
- bt_transport_text(transport).c_str());
+ log::error(
+ "Disconnect for unknown connection bd_addr:{} reason:{} transport:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bda), gatt_disconnection_reason_text(reason),
+ bt_transport_text(transport));
return;
}
@@ -1749,7 +1741,7 @@
}
gatt_stop_rsp_timer(&(*clcb_it));
- VLOG(1) << "found p_clcb conn_id=" << +clcb_it->conn_id;
+ log::verbose("found p_clcb conn_id={}", clcb_it->conn_id);
if (clcb_it->operation == GATTC_OPTYPE_NONE) {
clcb_it = gatt_cb.clcb_queue.erase(clcb_it);
continue;
@@ -1781,7 +1773,7 @@
}
*p_tcb = tGATT_TCB();
- VLOG(1) << __func__ << ": exit";
+ log::verbose("exit");
}
/*******************************************************************************
*
@@ -1792,7 +1784,7 @@
* Returns uint8_t *: name of the operation.
*
******************************************************************************/
-uint8_t* gatt_dbg_op_name(uint8_t op_code) {
+char const* gatt_dbg_op_name(uint8_t op_code) {
uint8_t pseduo_op_code_idx = op_code & (~GATT_WRITE_CMD_MASK);
if (op_code == GATT_CMD_WRITE) {
@@ -1805,10 +1797,10 @@
#define ARR_SIZE(a) (sizeof(a)/sizeof(a[0]))
if (pseduo_op_code_idx < ARR_SIZE(op_code_name))
- return (uint8_t*)op_code_name[pseduo_op_code_idx];
+ return op_code_name[pseduo_op_code_idx];
else
- return (uint8_t*)"Op Code Exceed Max";
- #undef ARR_SIZE
+ return "Op Code Exceed Max";
+#undef ARR_SIZE
}
/** Remove the application interface for the specified background device */
diff --git a/system/stack/hcic/hcicmds.cc b/system/stack/hcic/hcicmds.cc
index 74b1c1a..21c819d 100644
--- a/system/stack/hcic/hcicmds.cc
+++ b/system/stack/hcic/hcicmds.cc
@@ -48,10 +48,6 @@
#define HCIC_INQ_INQ_LAP_OFF 0
#define HCIC_INQ_DUR_OFF 3
#define HCIC_INQ_RSP_CNT_OFF 4
-/* Inquiry */
-
-/* Inquiry Cancel */
-#define HCIC_PARAM_SIZE_INQ_CANCEL 0
/* Periodic Inquiry Mode */
#define HCIC_PARAM_SIZE_PER_INQ_MODE 9
@@ -482,18 +478,6 @@
#define HCIC_PARAM_SIZE_BLE_RC_PARAM_REQ_REPLY 14
#define HCIC_PARAM_SIZE_BLE_RC_PARAM_REQ_NEG_REPLY 3
-static void btsnd_hcic_inq_cancel(void) {
- BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE);
- uint8_t* pp = (uint8_t*)(p + 1);
-
- p->len = HCIC_PREAMBLE_SIZE + HCIC_PARAM_SIZE_INQ_CANCEL;
- p->offset = 0;
- UINT16_TO_STREAM(pp, HCI_INQUIRY_CANCEL);
- UINT8_TO_STREAM(pp, HCIC_PARAM_SIZE_INQ_CANCEL);
-
- btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p);
-}
-
static void btsnd_hcic_disconnect(uint16_t handle, uint8_t reason) {
BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE);
uint8_t* pp = (uint8_t*)(p + 1);
@@ -1672,7 +1656,6 @@
namespace bluetooth::legacy::hci {
class InterfaceImpl : public Interface {
- void InquiryCancel() const override { btsnd_hcic_inq_cancel(); }
void Disconnect(uint16_t handle, uint8_t reason) const override {
btsnd_hcic_disconnect(handle, reason);
}
diff --git a/system/stack/hid/hid_conn.h b/system/stack/hid/hid_conn.h
index 22e9b9d..562525e 100644
--- a/system/stack/hid/hid_conn.h
+++ b/system/stack/hid/hid_conn.h
@@ -26,6 +26,7 @@
#define HID_CONN_H
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include "macros.h"
#include "osi/include/alarm.h"
@@ -77,4 +78,9 @@
#define HIDD_SEC_CHN 3
+namespace fmt {
+template <>
+struct formatter<tHID_CONN_STATE> : enum_formatter<tHID_CONN_STATE> {};
+} // namespace fmt
+
#endif
diff --git a/system/stack/hid/hidd_api.cc b/system/stack/hid/hidd_api.cc
index fad8e977..602f9a7 100644
--- a/system/stack/hid/hidd_api.cc
+++ b/system/stack/hid/hidd_api.cc
@@ -27,6 +27,7 @@
#include "hidd_api.h"
+#include <bluetooth/log.h>
#include <frameworks/proto_logging/stats/enums/bluetooth/enums.pb.h>
#include <stdio.h>
#include <stdlib.h>
@@ -44,6 +45,7 @@
#include "stack/include/stack_metrics_logging.h"
#include "types/raw_address.h"
+using namespace bluetooth;
using namespace bluetooth::legacy::stack::sdp;
tHID_DEV_CTB hd_cb;
@@ -58,7 +60,7 @@
*
******************************************************************************/
void HID_DevInit(void) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
memset(&hd_cb, 0, sizeof(tHID_DEV_CTB));
}
@@ -75,7 +77,7 @@
tHID_STATUS HID_DevRegister(tHID_DEV_HOST_CALLBACK* host_cback) {
tHID_STATUS st;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
if (hd_cb.reg_flag) {
log_counter_metrics(
@@ -116,7 +118,7 @@
*
******************************************************************************/
tHID_STATUS HID_DevDeregister(void) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
if (!hd_cb.reg_flag) {
log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::
@@ -146,7 +148,7 @@
uint16_t desc_len, uint8_t* p_desc_data) {
bool result = TRUE;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
// Service Class ID List
if (result) {
@@ -266,8 +268,8 @@
uint8_t seq_len = 4 + desc_len;
if (desc_len > HIDD_APP_DESCRIPTOR_LEN) {
- LOG_ERROR("%s: descriptor length = %d, larger than max %d", __func__,
- desc_len, HIDD_APP_DESCRIPTOR_LEN);
+ log::error("descriptor length = {}, larger than max {}", desc_len,
+ HIDD_APP_DESCRIPTOR_LEN);
log_counter_metrics(
android::bluetooth::CodePathCounterKeyEnum::
HIDD_ERR_NOT_REGISTERED_DUE_TO_DESCRIPTOR_LENGTH,
@@ -278,7 +280,7 @@
p_buf = (uint8_t*)osi_malloc(HIDD_APP_DESCRIPTOR_LEN + 6);
if (p_buf == NULL) {
- LOG_ERROR("%s: Buffer allocation failure for size = 2048 ", __func__);
+ log::error("Buffer allocation failure for size = 2048");
log_counter_metrics(
android::bluetooth::CodePathCounterKeyEnum::
HIDD_ERR_NOT_REGISTERED_DUE_TO_BUFFER_ALLOCATION,
@@ -352,7 +354,7 @@
}
if (!result) {
- LOG_ERROR("%s: failed to complete SDP record", __func__);
+ log::error("failed to complete SDP record");
log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::
HIDD_ERR_NOT_REGISTERED_AT_SDP,
1);
@@ -373,8 +375,7 @@
******************************************************************************/
tHID_STATUS HID_DevSendReport(uint8_t channel, uint8_t type, uint8_t id,
uint16_t len, uint8_t* p_data) {
- LOG_VERBOSE("%s: channel=%d type=%d id=%d len=%d", __func__, channel, type,
- id, len);
+ log::verbose("channel={} type={} id={} len={}", channel, type, id, len);
if (channel == HID_CHANNEL_CTRL) {
return hidd_conn_send_data(HID_CHANNEL_CTRL, HID_TRANS_DATA, type, id, len,
@@ -402,7 +403,7 @@
*
******************************************************************************/
tHID_STATUS HID_DevVirtualCableUnplug(void) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
return hidd_conn_send_data(HID_CHANNEL_CTRL, HID_TRANS_CONTROL,
HID_PAR_CONTROL_VIRTUAL_CABLE_UNPLUG, 0, 0, NULL);
@@ -549,7 +550,7 @@
tHID_STATUS HID_DevReportError(uint8_t error) {
uint8_t handshake_param;
- LOG_VERBOSE("%s: error = %d", __func__, error);
+ log::verbose("error = {}", error);
switch (error) {
case HID_PAR_HANDSHAKE_RSP_SUCCESS:
@@ -580,7 +581,7 @@
*
******************************************************************************/
tHID_STATUS HID_DevGetDevice(RawAddress* addr) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
if (hd_cb.device.in_use) {
*addr = hd_cb.device.addr;
@@ -607,7 +608,7 @@
uint32_t token_bucket_size,
uint32_t peak_bandwidth, uint32_t latency,
uint32_t delay_variation) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
hd_cb.use_in_qos = TRUE;
@@ -634,7 +635,7 @@
uint32_t token_bucket_size,
uint32_t peak_bandwidth, uint32_t latency,
uint32_t delay_variation) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
hd_cb.l2cap_intr_cfg.qos_present = TRUE;
diff --git a/system/stack/hid/hidd_conn.cc b/system/stack/hid/hidd_conn.cc
index 9b9129f..fe417c0 100644
--- a/system/stack/hid/hidd_conn.cc
+++ b/system/stack/hid/hidd_conn.cc
@@ -25,6 +25,7 @@
#include <base/functional/callback.h>
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <frameworks/proto_logging/stats/enums/bluetooth/enums.pb.h>
#include <cstdint>
@@ -40,6 +41,8 @@
#include "stack/include/stack_metrics_logging.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
static void hidd_l2cif_connect_ind(const RawAddress& bd_addr, uint16_t cid,
uint16_t psm, uint8_t id);
static void hidd_l2cif_connect_cfm(uint16_t cid, uint16_t result);
@@ -107,12 +110,12 @@
tHID_DEV_DEV_CTB* p_dev;
bool accept = TRUE; // accept by default
- LOG_VERBOSE("%s: psm=%04x cid=%04x", __func__, psm, cid);
+ log::verbose("psm={:04x} cid={:04x}", psm, cid);
p_dev = &hd_cb.device;
if (!hd_cb.allow_incoming) {
- LOG_WARN("%s: incoming connections not allowed, rejecting", __func__);
+ log::warn("incoming connections not allowed, rejecting");
L2CA_DisconnectReq(cid);
return;
@@ -124,13 +127,13 @@
case HID_PSM_INTERRUPT:
if (p_hcon->ctrl_cid == 0) {
accept = FALSE;
- LOG_WARN("%s: incoming INTR without CTRL, rejecting", __func__);
+ log::warn("incoming INTR without CTRL, rejecting");
}
if (p_hcon->conn_state != HID_CONN_STATE_CONNECTING_INTR) {
accept = FALSE;
- LOG_WARN("%s: incoming INTR in invalid state (%d), rejecting", __func__,
- p_hcon->conn_state);
+ log::warn("incoming INTR in invalid state ({}), rejecting",
+ p_hcon->conn_state);
}
break;
@@ -138,15 +141,15 @@
case HID_PSM_CONTROL:
if (p_hcon->conn_state != HID_CONN_STATE_UNUSED) {
accept = FALSE;
- LOG_WARN("%s: incoming CTRL in invalid state (%d), rejecting", __func__,
- p_hcon->conn_state);
+ log::warn("incoming CTRL in invalid state ({}), rejecting",
+ p_hcon->conn_state);
}
break;
default:
accept = FALSE;
- LOG_ERROR("%s: received invalid PSM, rejecting", __func__);
+ log::error("received invalid PSM, rejecting");
break;
}
@@ -176,7 +179,7 @@
}
static void hidd_on_l2cap_error(uint16_t lcid, uint16_t result) {
- LOG_WARN("%s: connection of config failed, now disconnect", __func__);
+ log::warn("connection of config failed, now disconnect");
hidd_conn_disconnect();
@@ -197,10 +200,10 @@
static void hidd_l2cif_connect_cfm(uint16_t cid, uint16_t result) {
tHID_CONN* p_hcon = &hd_cb.device.conn;
- LOG_VERBOSE("%s: cid=%04x result=%d", __func__, cid, result);
+ log::verbose("cid={:04x} result={}", cid, result);
if (p_hcon->ctrl_cid != cid && p_hcon->intr_cid != cid) {
- LOG_WARN("%s: unknown cid", __func__);
+ log::warn("unknown cid");
return;
}
@@ -209,12 +212,12 @@
(p_hcon->conn_state != HID_CONN_STATE_CONNECTING_CTRL)) ||
((cid == p_hcon->intr_cid) &&
(p_hcon->conn_state != HID_CONN_STATE_CONNECTING_INTR))) {
- LOG_WARN("%s: unexpected", __func__);
+ log::warn("unexpected");
return;
}
if (result != L2CAP_CONN_OK) {
- LOG(ERROR) << __func__ << ": invoked with non OK status";
+ log::error("invoked with non OK status");
return;
}
@@ -239,12 +242,12 @@
*
******************************************************************************/
static void hidd_l2cif_config_ind(uint16_t cid, tL2CAP_CFG_INFO* p_cfg) {
- LOG_VERBOSE("%s: cid=%04x", __func__, cid);
+ log::verbose("cid={:04x}", cid);
tHID_CONN* p_hcon = &hd_cb.device.conn;
if (p_hcon->ctrl_cid != cid && p_hcon->intr_cid != cid) {
- LOG_WARN("%s: unknown cid", __func__);
+ log::warn("unknown cid");
return;
}
@@ -267,12 +270,12 @@
tL2CAP_CFG_INFO* p_cfg) {
hidd_l2cif_config_ind(cid, p_cfg);
- LOG_VERBOSE("%s: cid=%04x", __func__, cid);
+ log::verbose("cid={:04x}", cid);
tHID_CONN* p_hcon = &hd_cb.device.conn;
if (p_hcon->ctrl_cid != cid && p_hcon->intr_cid != cid) {
- LOG_WARN("%s: unknown cid", __func__);
+ log::warn("unknown cid");
return;
}
@@ -286,7 +289,7 @@
hidd_conn_disconnect();
p_hcon->conn_state = HID_CONN_STATE_UNUSED;
- LOG_WARN("%s: could not start L2CAP connection for INTR", __func__);
+ log::warn("could not start L2CAP connection for INTR");
hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_CLOSE,
HID_ERR_L2CAP_FAILED, NULL);
log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::
@@ -312,13 +315,13 @@
*
******************************************************************************/
static void hidd_l2cif_disconnect_ind(uint16_t cid, bool ack_needed) {
- LOG_VERBOSE("%s: cid=%04x ack_needed=%d", __func__, cid, ack_needed);
+ log::verbose("cid={:04x} ack_needed={}", cid, ack_needed);
tHID_CONN* p_hcon = &hd_cb.device.conn;
if (p_hcon->conn_state == HID_CONN_STATE_UNUSED ||
(p_hcon->ctrl_cid != cid && p_hcon->intr_cid != cid)) {
- LOG_WARN("%s: unknown cid", __func__);
+ log::warn("unknown cid");
return;
}
@@ -330,7 +333,7 @@
p_hcon->intr_cid = 0;
if ((p_hcon->ctrl_cid == 0) && (p_hcon->intr_cid == 0)) {
- LOG_VERBOSE("%s: INTR and CTRL disconnected", __func__);
+ log::verbose("INTR and CTRL disconnected");
// clean any outstanding data on intr
if (hd_cb.pending_data) {
@@ -349,13 +352,13 @@
static void hidd_l2cif_disconnect(uint16_t cid) {
L2CA_DisconnectReq(cid);
- LOG_VERBOSE("%s: cid=%04x", __func__, cid);
+ log::verbose("cid={:04x}", cid);
tHID_CONN* p_hcon = &hd_cb.device.conn;
if (p_hcon->conn_state == HID_CONN_STATE_UNUSED ||
(p_hcon->ctrl_cid != cid && p_hcon->intr_cid != cid)) {
- LOG_WARN("%s: unknown cid", __func__);
+ log::warn("unknown cid");
return;
}
@@ -373,7 +376,7 @@
}
if ((p_hcon->ctrl_cid == 0) && (p_hcon->intr_cid == 0)) {
- LOG_VERBOSE("%s: INTR and CTRL disconnected", __func__);
+ log::verbose("INTR and CTRL disconnected");
hd_cb.device.state = HIDD_DEV_NO_CONN;
p_hcon->conn_state = HID_CONN_STATE_UNUSED;
@@ -399,13 +402,13 @@
*
******************************************************************************/
static void hidd_l2cif_cong_ind(uint16_t cid, bool congested) {
- LOG_VERBOSE("%s: cid=%04x congested=%d", __func__, cid, congested);
+ log::verbose("cid={:04x} congested={}", cid, congested);
tHID_CONN* p_hcon = &hd_cb.device.conn;
if (p_hcon->conn_state == HID_CONN_STATE_UNUSED ||
(p_hcon->ctrl_cid != cid && p_hcon->intr_cid != cid)) {
- LOG_WARN("%s: unknown cid", __func__);
+ log::warn("unknown cid");
return;
}
@@ -430,10 +433,10 @@
uint8_t msg_type, param;
bool err = FALSE;
- LOG_VERBOSE("%s: cid=%04x", __func__, cid);
+ log::verbose("cid={:04x}", cid);
if (p_msg->len < 1) {
- LOG_ERROR("Invalid data length, ignore");
+ log::error("Invalid data length, ignore");
osi_free(p_msg);
return;
}
@@ -442,7 +445,7 @@
if (p_hcon->conn_state == HID_CONN_STATE_UNUSED ||
(p_hcon->ctrl_cid != cid && p_hcon->intr_cid != cid)) {
- LOG_WARN("%s: unknown cid", __func__);
+ log::warn("unknown cid");
osi_free(p_msg);
return;
}
@@ -481,15 +484,14 @@
case HID_TRANS_SET_IDLE:
if (p_msg->len != 2) {
- LOG_ERROR("%s: invalid len (%d) set idle request received", __func__,
- p_msg->len);
+ log::error("invalid len ({}) set idle request received", p_msg->len);
err = TRUE;
} else {
hd_cb.device.idle_time = p_data[1];
- LOG_VERBOSE("%s: idle_time = %d", __func__, hd_cb.device.idle_time);
+ log::verbose("idle_time = {}", hd_cb.device.idle_time);
if (hd_cb.device.idle_time) {
- LOG_WARN("%s: idle_time of %d ms not supported by HID Device",
- __func__, (hd_cb.device.idle_time * 4));
+ log::warn("idle_time of {} ms not supported by HID Device",
+ (hd_cb.device.idle_time * 4));
err = TRUE;
}
}
@@ -544,7 +546,7 @@
case HID_TRANS_DATA:
default:
- LOG_WARN("%s: got unsupported msg (%d)", __func__, msg_type);
+ log::warn("got unsupported msg ({})", msg_type);
hidd_conn_send_data(0, HID_TRANS_HANDSHAKE,
HID_PAR_HANDSHAKE_RSP_ERR_UNSUPPORTED_REQ, 0, 0,
NULL);
@@ -563,7 +565,7 @@
*
******************************************************************************/
tHID_STATUS hidd_conn_reg(void) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
memset(&hd_cb.l2cap_cfg, 0, sizeof(tL2CAP_CFG_INFO));
@@ -576,7 +578,7 @@
if (!L2CA_Register2(HID_PSM_CONTROL, dev_reg_info, false /* enable_snoop */,
nullptr, HID_DEV_MTU_SIZE, 0,
BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)) {
- LOG_ERROR("HID Control (device) registration failed");
+ log::error("HID Control (device) registration failed");
log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::
HIDD_ERR_L2CAP_FAILED_CONTROL,
1);
@@ -587,7 +589,7 @@
nullptr, HID_DEV_MTU_SIZE, 0,
BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)) {
L2CA_Deregister(HID_PSM_CONTROL);
- LOG_ERROR("HID Interrupt (device) registration failed");
+ log::error("HID Interrupt (device) registration failed");
log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::
HIDD_ERR_L2CAP_FAILED_INTERRUPT,
1);
@@ -607,7 +609,7 @@
*
******************************************************************************/
void hidd_conn_dereg(void) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
L2CA_Deregister(HID_PSM_CONTROL);
L2CA_Deregister(HID_PSM_INTERRUPT);
@@ -625,10 +627,10 @@
tHID_STATUS hidd_conn_initiate(void) {
tHID_DEV_DEV_CTB* p_dev = &hd_cb.device;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
if (!p_dev->in_use) {
- LOG_WARN("%s: no virtual cable established", __func__);
+ log::warn("no virtual cable established");
log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::
HIDD_ERR_NOT_REGISTERED_AT_INITIATE,
1);
@@ -636,7 +638,7 @@
}
if (p_dev->conn.conn_state != HID_CONN_STATE_UNUSED) {
- LOG_WARN("%s: connection already in progress", __func__);
+ log::warn("connection already in progress");
log_counter_metrics(
android::bluetooth::CodePathCounterKeyEnum::HIDD_ERR_CONN_IN_PROCESS,
1);
@@ -653,7 +655,7 @@
if ((p_dev->conn.ctrl_cid =
L2CA_ConnectReq2(HID_PSM_CONTROL, p_dev->addr,
BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)) == 0) {
- LOG_WARN("%s: could not start L2CAP connection", __func__);
+ log::warn("could not start L2CAP connection");
hd_cb.callback(hd_cb.device.addr, HID_DHOST_EVT_CLOSE, HID_ERR_L2CAP_FAILED,
NULL);
log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::
@@ -676,7 +678,7 @@
*
******************************************************************************/
tHID_STATUS hidd_conn_disconnect(void) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
// clean any outstanding data on intr
if (hd_cb.pending_data) {
@@ -699,7 +701,7 @@
hidd_l2cif_disconnect(p_hcon->ctrl_cid);
}
} else {
- LOG_WARN("%s: already disconnected", __func__);
+ log::warn("already disconnected");
p_hcon->conn_state = HID_CONN_STATE_UNUSED;
}
@@ -723,8 +725,7 @@
uint16_t cid;
uint16_t buf_size;
- LOG_VERBOSE("%s: channel(%d), msg_type(%d), len(%d)", __func__, channel,
- msg_type, len);
+ log::verbose("channel({}), msg_type({}), len({})", channel, msg_type, len);
tHID_CONN* p_hcon = &hd_cb.device.conn;
@@ -808,12 +809,7 @@
return HID_ERR_NO_CONNECTION;
}
-#ifdef REPORT_TRANSFER_TIMESTAMP
- if (report_transfer) {
- LOG_ERROR("%s: report sent", __func__);
- }
-#endif
- LOG_VERBOSE("%s: report sent", __func__);
+ log::verbose("report sent");
if (!L2CA_DataWrite(cid, p_buf)) {
log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::
diff --git a/system/stack/hid/hidh_api.cc b/system/stack/hid/hidh_api.cc
index 0bb7926..24f0f18 100644
--- a/system/stack/hid/hidh_api.cc
+++ b/system/stack/hid/hidh_api.cc
@@ -26,6 +26,7 @@
#include "hidh_api.h"
+#include <bluetooth/log.h>
#include <frameworks/proto_logging/stats/enums/bluetooth/enums.pb.h>
#include <stdio.h>
#include <stdlib.h>
@@ -44,6 +45,7 @@
#include "types/bluetooth/uuid.h"
#include "types/raw_address.h"
+using namespace bluetooth;
using namespace bluetooth::legacy::stack::sdp;
using bluetooth::Uuid;
@@ -107,7 +109,7 @@
}
} else {
str[0] = '\0';
- LOG_ERROR("attr type not str!!");
+ log::error("attr type not str!!");
}
} else
str[0] = '\0';
@@ -496,13 +498,13 @@
tHID_STATUS status = HID_SUCCESS;
if (!hh_cb.reg_flag) {
- LOG_ERROR("HID_ERR_NOT_REGISTERED");
+ log::error("HID_ERR_NOT_REGISTERED");
status = HID_ERR_NOT_REGISTERED;
}
if ((dev_handle >= HID_HOST_MAX_DEVICES) ||
(!hh_cb.devices[dev_handle].in_use)) {
- LOG_ERROR("HID_ERR_INVALID_PARAM");
+ log::error("HID_ERR_INVALID_PARAM");
log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::
HIDH_ERR_INVALID_PARAM_AT_HOST_WRITE_DEV,
1);
@@ -510,7 +512,7 @@
}
else if (hh_cb.devices[dev_handle].state != HID_DEV_CONNECTED) {
- LOG_ERROR("HID_ERR_NO_CONNECTION dev_handle %d", dev_handle);
+ log::error("HID_ERR_NO_CONNECTION dev_handle {}", dev_handle);
log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::
HIDH_ERR_NO_CONNECTION_AT_HOST_WRITE_DEV,
1);
diff --git a/system/stack/hid/hidh_conn.cc b/system/stack/hid/hidh_conn.cc
index b9da24e..261446d 100644
--- a/system/stack/hid/hidh_conn.cc
+++ b/system/stack/hid/hidh_conn.cc
@@ -25,6 +25,7 @@
#include <base/functional/callback.h>
#include <base/logging.h>
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <frameworks/proto_logging/stats/enums/bluetooth/enums.pb.h>
#include <string.h>
@@ -45,6 +46,8 @@
#include "stack/include/stack_metrics_logging.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
namespace {
constexpr char kBtmLogTag[] = "HIDH";
constexpr uint8_t kHID_HOST_MAX_DEVICES = HID_HOST_MAX_DEVICES;
@@ -108,7 +111,7 @@
if (!L2CA_Register2(HID_PSM_CONTROL, hst_reg_info, false /* enable_snoop */,
nullptr, HID_HOST_MTU, 0,
BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)) {
- LOG_ERROR("HID-Host Control Registration failed");
+ log::error("HID-Host Control Registration failed");
log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::
HIDH_ERR_L2CAP_FAILED_AT_REGISTER_CONTROL,
1);
@@ -118,7 +121,7 @@
nullptr, HID_HOST_MTU, 0,
BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT)) {
L2CA_Deregister(HID_PSM_CONTROL);
- LOG_ERROR("HID-Host Interrupt Registration failed");
+ log::error("HID-Host Interrupt Registration failed");
log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::
HIDH_ERR_L2CAP_FAILED_AT_REGISTER_INTERRUPT,
1);
@@ -183,8 +186,8 @@
bool bAccept = true;
uint8_t i = kHID_HOST_MAX_DEVICES;
- LOG_VERBOSE("HID-Host Rcvd L2CAP conn ind, PSM: 0x%04x CID 0x%x", psm,
- l2cap_cid);
+ log::verbose("HID-Host Rcvd L2CAP conn ind, PSM: 0x{:04x} CID 0x{:x}", psm,
+ l2cap_cid);
/* always add incoming connection device into HID database by default */
if (HID_HostAddDev(bd_addr, HID_SEC_REQUIRED, &i) != HID_SUCCESS) {
@@ -203,12 +206,12 @@
/* Check we are in the correct state for this */
if (psm == HID_PSM_INTERRUPT) {
if (p_hcon->ctrl_cid == 0) {
- LOG_WARN("HID-Host Rcvd INTR L2CAP conn ind, but no CTL channel");
+ log::warn("HID-Host Rcvd INTR L2CAP conn ind, but no CTL channel");
bAccept = false;
}
if (p_hcon->conn_state != HID_CONN_STATE_CONNECTING_INTR) {
- LOG_WARN("HID-Host Rcvd INTR L2CAP conn ind, wrong state: %d",
- p_hcon->conn_state);
+ log::warn("HID-Host Rcvd INTR L2CAP conn ind, wrong state: {}",
+ p_hcon->conn_state);
bAccept = false;
}
} else /* CTRL channel */
@@ -218,8 +221,8 @@
p_hcon->conn_state = HID_CONN_STATE_UNUSED;
#else
if (p_hcon->conn_state != HID_CONN_STATE_UNUSED) {
- LOG_WARN("HID-Host - Rcvd CTL L2CAP conn ind, wrong state: %d",
- p_hcon->conn_state);
+ log::warn("HID-Host - Rcvd CTL L2CAP conn ind, wrong state: {}",
+ p_hcon->conn_state);
bAccept = false;
}
#endif
@@ -246,8 +249,9 @@
p_hcon->conn_state = HID_CONN_STATE_CONFIG;
p_hcon->intr_cid = l2cap_cid;
- LOG_VERBOSE(
- "HID-Host Rcvd L2CAP conn ind, sent config req, PSM: 0x%04x CID 0x%x",
+ log::verbose(
+ "HID-Host Rcvd L2CAP conn ind, sent config req, PSM: 0x{:04x} CID "
+ "0x{:x}",
psm, l2cap_cid);
}
@@ -280,9 +284,8 @@
static void hidh_on_l2cap_error(uint16_t l2cap_cid, uint16_t result) {
auto dhandle = find_conn_by_cid(l2cap_cid);
if (dhandle == kHID_HOST_MAX_DEVICES) {
- LOG_WARN("Received error for unknown device cid:0x%04x reason:%s",
- l2cap_cid,
- hci_reason_code_text(to_hci_reason_code(result)).c_str());
+ log::warn("Received error for unknown device cid:0x{:04x} reason:{}",
+ l2cap_cid, hci_reason_code_text(to_hci_reason_code(result)));
return;
}
@@ -336,13 +339,13 @@
((l2cap_cid == p_hcon->intr_cid) &&
(p_hcon->conn_state != HID_CONN_STATE_CONNECTING_INTR) &&
(p_hcon->conn_state != HID_CONN_STATE_DISCONNECTING))) {
- LOG_WARN("HID-Host Rcvd unexpected conn cnf, CID 0x%x ", l2cap_cid);
+ log::warn("HID-Host Rcvd unexpected conn cnf, CID 0x{:x} ", l2cap_cid);
return;
}
if (result != L2CAP_CONN_OK) {
// TODO: We need to provide the real HCI status if we want to retry.
- LOG(ERROR) << __func__ << ": invoked with non OK status";
+ log::error("invoked with non OK status");
return;
}
/* receive Control Channel connect confirmation */
@@ -386,11 +389,11 @@
}
if (p_hcon == NULL) {
- LOG_WARN("HID-Host Rcvd L2CAP cfg ind, unknown CID: 0x%x", l2cap_cid);
+ log::warn("HID-Host Rcvd L2CAP cfg ind, unknown CID: 0x{:x}", l2cap_cid);
return;
}
- LOG_VERBOSE("HID-Host Rcvd cfg ind, sent cfg cfm, CID: 0x%x", l2cap_cid);
+ log::verbose("HID-Host Rcvd cfg ind, sent cfg cfm, CID: 0x{:x}", l2cap_cid);
/* Remember the remote MTU size */
if ((!p_cfg->mtu_present) || (p_cfg->mtu > HID_HOST_MTU))
@@ -417,14 +420,14 @@
tHID_CONN* p_hcon = NULL;
uint32_t reason;
- LOG_VERBOSE("HID-Host Rcvd cfg cfm, CID: 0x%x", l2cap_cid);
+ log::verbose("HID-Host Rcvd cfg cfm, CID: 0x{:x}", l2cap_cid);
/* Find CCB based on CID */
dhandle = find_conn_by_cid(l2cap_cid);
if (dhandle < kHID_HOST_MAX_DEVICES) p_hcon = &hh_cb.devices[dhandle].conn;
if (p_hcon == NULL) {
- LOG_WARN("HID-Host Rcvd L2CAP cfg ind, unknown CID: 0x%x", l2cap_cid);
+ log::warn("HID-Host Rcvd L2CAP cfg ind, unknown CID: 0x{:x}", l2cap_cid);
return;
}
@@ -439,7 +442,7 @@
L2CA_ConnectReq2(HID_PSM_INTERRUPT, hh_cb.devices[dhandle].addr,
BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT);
if (p_hcon->intr_cid == 0) {
- LOG_WARN("HID-Host INTR Originate failed");
+ log::warn("HID-Host INTR Originate failed");
reason = HID_L2CAP_REQ_FAIL;
p_hcon->conn_state = HID_CONN_STATE_UNUSED;
BTM_LogHistory(kBtmLogTag, hh_cb.devices[dhandle].addr, "Failed");
@@ -496,11 +499,11 @@
if (dhandle < kHID_HOST_MAX_DEVICES) p_hcon = &hh_cb.devices[dhandle].conn;
if (p_hcon == NULL) {
- LOG_WARN("HID-Host Rcvd L2CAP disc, unknown CID: 0x%x", l2cap_cid);
+ log::warn("HID-Host Rcvd L2CAP disc, unknown CID: 0x{:x}", l2cap_cid);
return;
}
- LOG_VERBOSE("HID-Host Rcvd L2CAP disc, CID: 0x%x", l2cap_cid);
+ log::verbose("HID-Host Rcvd L2CAP disc, CID: 0x{:x}", l2cap_cid);
p_hcon->conn_state = HID_CONN_STATE_DISCONNECTING;
BTM_LogHistory(
@@ -566,7 +569,7 @@
/* Find CCB based on CID */
const uint8_t dhandle = find_conn_by_cid(l2cap_cid);
if (dhandle == kHID_HOST_MAX_DEVICES) {
- LOG_WARN("HID-Host Rcvd L2CAP disc cfm, unknown CID: 0x%x", l2cap_cid);
+ log::warn("HID-Host Rcvd L2CAP disc cfm, unknown CID: 0x{:x}", l2cap_cid);
return;
}
@@ -576,7 +579,7 @@
} else {
p_hcon->intr_cid = 0;
if (p_hcon->ctrl_cid) {
- LOG_VERBOSE("HID-Host Initiating L2CAP Ctrl disconnection");
+ log::verbose("HID-Host Initiating L2CAP Ctrl disconnection");
L2CA_DisconnectReq(p_hcon->ctrl_cid);
p_hcon->ctrl_cid = 0;
}
@@ -609,13 +612,13 @@
if (dhandle < kHID_HOST_MAX_DEVICES) p_hcon = &hh_cb.devices[dhandle].conn;
if (p_hcon == NULL) {
- LOG_WARN("HID-Host Rcvd L2CAP congestion status, unknown CID: 0x%x",
- l2cap_cid);
+ log::warn("HID-Host Rcvd L2CAP congestion status, unknown CID: 0x{:x}",
+ l2cap_cid);
return;
}
- LOG_VERBOSE("HID-Host Rcvd L2CAP congestion status, CID: 0x%x Cong: %d",
- l2cap_cid, congested);
+ log::verbose("HID-Host Rcvd L2CAP congestion status, CID: 0x{:x} Cong: {}",
+ l2cap_cid, congested);
if (congested)
p_hcon->conn_flags |= HID_CONN_FLAGS_CONGESTED;
@@ -646,20 +649,20 @@
uint8_t dhandle;
tHID_CONN* p_hcon = NULL;
- LOG_VERBOSE("HID-Host hidh_l2cif_data_ind [l2cap_cid=0x%04x]", l2cap_cid);
+ log::verbose("HID-Host hidh_l2cif_data_ind [l2cap_cid=0x{:04x}]", l2cap_cid);
/* Find CCB based on CID */
dhandle = find_conn_by_cid(l2cap_cid);
if (dhandle < kHID_HOST_MAX_DEVICES) p_hcon = &hh_cb.devices[dhandle].conn;
if (p_hcon == NULL) {
- LOG_WARN("HID-Host Rcvd L2CAP data, unknown CID: 0x%x", l2cap_cid);
+ log::warn("HID-Host Rcvd L2CAP data, unknown CID: 0x{:x}", l2cap_cid);
osi_free(p_msg);
return;
}
if (p_msg->len < 1) {
- LOG_WARN("Rcvd L2CAP data, invalid length %d, should be >= 1", p_msg->len);
+ log::warn("Rcvd L2CAP data, invalid length {}, should be >= 1", p_msg->len);
osi_free(p_msg);
return;
}
@@ -884,7 +887,7 @@
p_dev->conn.ctrl_cid = L2CA_ConnectReq2(
HID_PSM_CONTROL, p_dev->addr, BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT);
if (p_dev->conn.ctrl_cid == 0) {
- LOG_WARN("HID-Host Originate failed");
+ log::warn("HID-Host Originate failed");
hh_cb.callback(dhandle, hh_cb.devices[dhandle].addr, HID_HDEV_EVT_CLOSE,
HID_ERR_L2CAP_FAILED, NULL);
log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::
diff --git a/system/stack/include/acl_api.h b/system/stack/include/acl_api.h
index 95d41a8..34d2d50 100644
--- a/system/stack/include/acl_api.h
+++ b/system/stack/include/acl_api.h
@@ -302,8 +302,6 @@
bool acl_peer_supports_ble_connection_subrating_host(
const RawAddress& remote_bda);
-void btm_process_cancel_complete(uint8_t status, uint8_t mode);
-
uint8_t btm_handle_to_acl_index(uint16_t hci_handle);
tHCI_REASON btm_get_acl_disc_reason_code(void);
diff --git a/system/stack/include/ble_hci_link_interface.h b/system/stack/include/ble_hci_link_interface.h
index d00f05d..cedc7cb 100644
--- a/system/stack/include/ble_hci_link_interface.h
+++ b/system/stack/include/ble_hci_link_interface.h
@@ -22,9 +22,6 @@
#include "stack/include/hci_error_code.h"
// This header contains functions for HCI-ble to invoke
-void btm_ble_process_adv_pkt(uint8_t len, const uint8_t* p);
-void btm_ble_process_ext_adv_pkt(uint8_t len, const uint8_t* p);
-void btm_ble_process_phy_update_pkt(uint8_t len, uint8_t* p);
void btm_ble_read_remote_features_complete(uint8_t* p, uint8_t length);
void btm_ble_write_adv_enable_complete(uint8_t* p, uint16_t evt_len);
void btm_ble_ltk_request(uint16_t handle, uint8_t rand[8], uint16_t ediv);
diff --git a/system/stack/include/btm_ble_api_types.h b/system/stack/include/btm_ble_api_types.h
index 07f5bd9..d3519f0 100644
--- a/system/stack/include/btm_ble_api_types.h
+++ b/system/stack/include/btm_ble_api_types.h
@@ -334,6 +334,7 @@
uint8_t quality_report_support;
uint32_t dynamic_audio_buffer_support;
uint16_t adv_filter_extended_features_mask;
+ uint8_t a2dp_offload_v2_support;
} tBTM_BLE_VSC_CB;
/* Stored the default/maximum/minimum buffer time for dynamic audio buffer.
diff --git a/system/stack/include/btm_sec_api_types.h b/system/stack/include/btm_sec_api_types.h
index 4e35d0c..341cadc 100644
--- a/system/stack/include/btm_sec_api_types.h
+++ b/system/stack/include/btm_sec_api_types.h
@@ -19,6 +19,7 @@
#pragma once
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <cstdint>
#include <string>
@@ -524,3 +525,8 @@
return base::StringPrintf("UNKNOWN[%hhu]", bond_type);
}
}
+
+namespace fmt {
+template <>
+struct formatter<tBTM_BLE_SEC_ACT> : enum_formatter<tBTM_BLE_SEC_ACT> {};
+} // namespace fmt
diff --git a/system/stack/include/dev_hci_link_interface.h b/system/stack/include/dev_hci_link_interface.h
index 81cd138..36455f4 100644
--- a/system/stack/include/dev_hci_link_interface.h
+++ b/system/stack/include/dev_hci_link_interface.h
@@ -21,8 +21,6 @@
#include <cstdint>
-#include "types/raw_address.h"
-
void btm_delete_stored_link_key_complete(uint8_t* p, uint16_t evt_len);
void btm_vendor_specific_evt(const uint8_t* p, uint8_t evt_len);
void btm_read_local_name_complete(uint8_t* p, uint16_t evt_len);
diff --git a/system/stack/include/gatt_api.h b/system/stack/include/gatt_api.h
index d5d6189..34e1306 100644
--- a/system/stack/include/gatt_api.h
+++ b/system/stack/include/gatt_api.h
@@ -19,6 +19,7 @@
#define GATT_API_H
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <cstdint>
#include <list>
@@ -1299,4 +1300,15 @@
// Initialize GATTS list of bonded device service change updates.
void gatt_load_bonded(void);
+namespace fmt {
+template <>
+struct formatter<GattStatus> : enum_formatter<GattStatus> {};
+template <>
+struct formatter<tGATTC_OPTYPE> : enum_formatter<tGATTC_OPTYPE> {};
+template <>
+struct formatter<tGATT_OP_CODE> : enum_formatter<tGATT_OP_CODE> {};
+template <>
+struct formatter<tGATT_DISC_TYPE> : enum_formatter<tGATT_DISC_TYPE> {};
+} // namespace fmt
+
#endif /* GATT_API_H */
diff --git a/system/stack/include/hci_error_code.h b/system/stack/include/hci_error_code.h
index 20acb74..af6c352 100644
--- a/system/stack/include/hci_error_code.h
+++ b/system/stack/include/hci_error_code.h
@@ -17,6 +17,7 @@
#pragma once
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <cstdint>
#include <string>
@@ -147,3 +148,8 @@
if (reason_code > _HCI_ERR_MAX_ERR) return HCI_ERR_UNDEFINED;
return static_cast<tHCI_REASON>(reason_code);
}
+
+namespace fmt {
+template <>
+struct formatter<tHCI_ERROR_CODE> : enum_formatter<tHCI_ERROR_CODE> {};
+} // namespace fmt
diff --git a/system/stack/include/hcimsgs.h b/system/stack/include/hcimsgs.h
index cbaabe8..8713ccc 100644
--- a/system/stack/include/hcimsgs.h
+++ b/system/stack/include/hcimsgs.h
@@ -43,7 +43,6 @@
namespace bluetooth::legacy::hci {
class Interface {
public:
- virtual void InquiryCancel() const = 0;
virtual void Disconnect(uint16_t handle, uint8_t reason) const = 0;
virtual void ChangeConnectionPacketType(uint16_t handle,
uint16_t packet_types) const = 0;
diff --git a/system/stack/include/inq_hci_link_interface.h b/system/stack/include/inq_hci_link_interface.h
index 5f712c3..3863889 100644
--- a/system/stack/include/inq_hci_link_interface.h
+++ b/system/stack/include/inq_hci_link_interface.h
@@ -30,7 +30,6 @@
uint8_t inq_res_mode);
void btm_process_inq_complete(tHCI_STATUS status, uint8_t mode);
-void btm_process_cancel_complete(tHCI_STATUS status, uint8_t mode);
void btm_acl_process_sca_cmpl_pkt(uint8_t len, uint8_t* data);
tINQ_DB_ENT* btm_inq_db_new(const RawAddress& p_bda, bool is_ble);
diff --git a/system/stack/include/l2c_api.h b/system/stack/include/l2c_api.h
index 3f257ba..bc1ad23 100644
--- a/system/stack/include/l2c_api.h
+++ b/system/stack/include/l2c_api.h
@@ -24,6 +24,7 @@
#ifndef L2C_API_H
#define L2C_API_H
+#include <bluetooth/log.h>
#include <stdbool.h>
#include <cstdint>
@@ -925,4 +926,11 @@
bool L2CA_isMediaChannel(uint16_t handle, uint16_t channel_id,
bool is_local_cid);
+namespace fmt {
+template <>
+struct formatter<tL2CAP_LATENCY> : enum_formatter<tL2CAP_LATENCY> {};
+template <>
+struct formatter<tL2CAP_PRIORITY> : enum_formatter<tL2CAP_PRIORITY> {};
+} // namespace fmt
+
#endif /* L2C_API_H */
diff --git a/system/stack/include/l2cdefs.h b/system/stack/include/l2cdefs.h
index 2d8be2b..c1c26f7 100644
--- a/system/stack/include/l2cdefs.h
+++ b/system/stack/include/l2cdefs.h
@@ -481,4 +481,9 @@
/* Mask for sequence numbers (range 0 - 63) */
#define L2CAP_FCR_SEQ_MODULO 0x3F
+namespace fmt {
+template <>
+struct formatter<tL2CAP_CONN> : enum_formatter<tL2CAP_CONN> {};
+} // namespace fmt
+
#endif
diff --git a/system/stack/include/sdp_status.h b/system/stack/include/sdp_status.h
index cfb81f8..d71922c 100644
--- a/system/stack/include/sdp_status.h
+++ b/system/stack/include/sdp_status.h
@@ -19,6 +19,7 @@
#pragma once
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <cstdint>
@@ -85,3 +86,8 @@
}
}
const auto sdp_result_text = sdp_status_text;
+
+namespace fmt {
+template <>
+struct formatter<tSDP_STATUS> : enum_formatter<tSDP_STATUS> {};
+} // namespace fmt
diff --git a/system/stack/include/smp_api_types.h b/system/stack/include/smp_api_types.h
index 82748e5..5b8a9a1 100644
--- a/system/stack/include/smp_api_types.h
+++ b/system/stack/include/smp_api_types.h
@@ -20,6 +20,7 @@
#define SMP_API_TYPES_H
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <cstdint>
#include <string>
@@ -229,4 +230,9 @@
* Manager requires verification from CSIP.*/
typedef tBTM_STATUS(tSMP_SIRK_CALLBACK)(const RawAddress& bd_addr);
+namespace fmt {
+template <>
+struct formatter<tSMP_SEC_LEVEL> : enum_formatter<tSMP_SEC_LEVEL> {};
+} // namespace fmt
+
#endif // SMP_API_TYPES_H
diff --git a/system/stack/l2cap/l2c_api.cc b/system/stack/l2cap/l2c_api.cc
index dceb825..d12df9b 100644
--- a/system/stack/l2cap/l2c_api.cc
+++ b/system/stack/l2cap/l2c_api.cc
@@ -29,6 +29,7 @@
#include <base/location.h>
#include <base/logging.h>
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <cstdint>
#include <string>
@@ -53,6 +54,8 @@
#include "stack/l2cap/l2c_int.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
void btsnd_hcic_enhanced_flush(uint16_t handle,
uint8_t packet_type); // TODO Remove
@@ -133,16 +136,16 @@
** or only a server.
*/
if (!config_cfm_cb || !data_ind_cb || !disconnect_ind_cb) {
- LOG_ERROR(
- "L2CAP - no cb registering PSM: 0x%04x cfg_cfm:%u cfg_ind:%u"
- " data_ind:%u discon_int:%u",
+ log::error(
+ "L2CAP - no cb registering PSM: 0x{:04x} cfg_cfm:{} cfg_ind:{} "
+ "data_ind:{} discon_int:{}",
psm, config_cfm_cb, config_ind_cb, data_ind_cb, disconnect_ind_cb);
return (0);
}
/* Verify PSM is valid */
if (L2C_INVALID_PSM(psm)) {
- LOG_ERROR("L2CAP - invalid PSM value, PSM: 0x%04x", psm);
+ log::error("L2CAP - invalid PSM value, PSM: 0x{:04x}", psm);
return (0);
}
@@ -154,7 +157,7 @@
if (p_rcb == NULL) break;
}
- LOG_DEBUG("L2CAP - Real PSM: 0x%04x Virtual PSM: 0x%04x", psm, vpsm);
+ log::debug("L2CAP - Real PSM: 0x{:04x} Virtual PSM: 0x{:04x}", psm, vpsm);
}
/* If registration block already there, just overwrite it */
@@ -162,13 +165,13 @@
if (p_rcb == NULL) {
p_rcb = l2cu_allocate_rcb(vpsm);
if (p_rcb == NULL) {
- LOG_WARN("L2CAP - no RCB available, PSM: 0x%04x vPSM: 0x%04x", psm,
- vpsm);
+ log::warn("L2CAP - no RCB available, PSM: 0x{:04x} vPSM: 0x{:04x}", psm,
+ vpsm);
return (0);
}
}
- LOG_INFO("L2CAP Registered service classic PSM: 0x%04x", psm);
+ log::info("L2CAP Registered service classic PSM: 0x{:04x}", psm);
p_rcb->log_packets = enable_snoop;
p_rcb->api = p_cb_info;
p_rcb->real_psm = psm;
@@ -198,7 +201,7 @@
tL2C_LCB* p_lcb;
int ii;
- LOG_VERBOSE("L2CAP - L2CA_Deregister() called for PSM: 0x%04x", psm);
+ log::verbose("L2CAP - L2CA_Deregister() called for PSM: 0x{:04x}", psm);
p_rcb = l2cu_find_rcb_by_psm(psm);
if (p_rcb != NULL) {
@@ -223,7 +226,7 @@
}
l2cu_release_rcb(p_rcb);
} else {
- LOG_WARN("L2CAP - PSM: 0x%04x not found for deregistration", psm);
+ log::warn("L2CAP - PSM: 0x{:04x} not found for deregistration", psm);
}
}
@@ -241,11 +244,11 @@
uint16_t psm = l2cb.le_dyn_psm;
uint16_t count = 0;
- LOG_VERBOSE("%s: last psm=%d", __func__, psm);
+ log::verbose("last psm={}", psm);
while (!done) {
count++;
if (count > LE_DYNAMIC_PSM_RANGE) {
- LOG_ERROR("%s: Out of free BLE PSM", __func__);
+ log::error("Out of free BLE PSM");
return 0;
}
@@ -257,13 +260,12 @@
if (!l2cb.le_dyn_psm_assigned[psm - LE_DYNAMIC_PSM_START]) {
/* make sure the newly allocated psm is not used right now */
if (l2cu_find_ble_rcb_by_psm(psm)) {
- LOG_WARN("%s: supposedly-free PSM=%d have allocated rcb!", __func__,
- psm);
+ log::warn("supposedly-free PSM={} have allocated rcb!", psm);
continue;
}
l2cb.le_dyn_psm_assigned[psm - LE_DYNAMIC_PSM_START] = true;
- LOG_VERBOSE("%s: assigned PSM=%d", __func__, psm);
+ log::verbose("assigned PSM={}", psm);
done = true;
break;
}
@@ -283,15 +285,15 @@
*
******************************************************************************/
void L2CA_FreeLePSM(uint16_t psm) {
- LOG_VERBOSE("%s: to free psm=%d", __func__, psm);
+ log::verbose("to free psm={}", psm);
if ((psm < LE_DYNAMIC_PSM_START) || (psm > LE_DYNAMIC_PSM_END)) {
- LOG_ERROR("%s: Invalid PSM=%d value!", __func__, psm);
+ log::error("Invalid PSM={} value!", psm);
return;
}
if (!l2cb.le_dyn_psm_assigned[psm - LE_DYNAMIC_PSM_START]) {
- LOG_WARN("%s: PSM=%d was not allocated!", __func__, psm);
+ log::warn("PSM={} was not allocated!", psm);
}
l2cb.le_dyn_psm_assigned[psm - LE_DYNAMIC_PSM_START] = false;
}
@@ -317,18 +319,17 @@
*
******************************************************************************/
uint16_t L2CA_ConnectReq(uint16_t psm, const RawAddress& p_bd_addr) {
- VLOG(1) << __func__ << "BDA " << ADDRESS_TO_LOGGABLE_STR(p_bd_addr)
- << StringPrintf(" PSM: 0x%04x", psm);
+ log::verbose("BDA {} PSM: 0x{:04x}", ADDRESS_TO_LOGGABLE_STR(p_bd_addr), psm);
/* Fail if we have not established communications with the controller */
if (!BTM_IsDeviceUp()) {
- LOG(WARNING) << __func__ << ": BTU not ready";
+ log::warn("BTU not ready");
return 0;
}
/* Fail if the PSM is not registered */
tL2C_RCB* p_rcb = l2cu_find_rcb_by_psm(psm);
if (p_rcb == nullptr) {
- LOG(WARNING) << __func__ << ": no RCB, PSM=" << loghex(psm);
+ log::warn("no RCB, PSM={}", loghex(psm));
return 0;
}
@@ -340,9 +341,8 @@
p_lcb = l2cu_allocate_lcb(p_bd_addr, false, BT_TRANSPORT_BR_EDR);
/* currently use BR/EDR for ERTM mode l2cap connection */
if (p_lcb == nullptr) {
- LOG(WARNING) << __func__
- << ": connection not started for PSM=" << loghex(psm)
- << ", p_lcb=" << p_lcb;
+ log::warn("connection not started for PSM={}, p_lcb={}", loghex(psm),
+ fmt::ptr(p_lcb));
return 0;
}
l2cu_create_conn_br_edr(p_lcb);
@@ -351,7 +351,7 @@
/* Allocate a channel control block */
tL2C_CCB* p_ccb = l2cu_allocate_ccb(p_lcb, 0);
if (p_ccb == nullptr) {
- LOG(WARNING) << __func__ << ": no CCB, PSM=" << loghex(psm);
+ log::warn("no CCB, PSM={}", loghex(psm));
return 0;
}
@@ -370,14 +370,14 @@
* ccb will be automatically retried after link disconnect
* arrives
*/
- LOG_VERBOSE("L2CAP API - link disconnecting: RETRY LATER");
+ log::verbose("L2CAP API - link disconnecting: RETRY LATER");
/* Save ccb so it can be started after disconnect is finished */
p_lcb->p_pending_ccb = p_ccb;
}
- LOG_VERBOSE("L2CAP - L2CA_conn_req(psm: 0x%04x) returned CID: 0x%04x", psm,
- p_ccb->local_cid);
+ log::verbose("L2CAP - L2CA_conn_req(psm: 0x{:04x}) returned CID: 0x{:04x}",
+ psm, p_ccb->local_cid);
/* Return the local CID as our handle */
return p_ccb->local_cid;
@@ -412,13 +412,13 @@
** or only a server.
*/
if ((!p_cb_info.pL2CA_DataInd_Cb) || (!p_cb_info.pL2CA_DisconnectInd_Cb)) {
- LOG_ERROR("No cb registering BLE PSM: 0x%04x", psm);
+ log::error("No cb registering BLE PSM: 0x{:04x}", psm);
return 0;
}
/* Verify PSM is valid */
if (!L2C_IS_VALID_LE_PSM(psm)) {
- LOG_ERROR("Invalid BLE PSM value, PSM: 0x%04x", psm);
+ log::error("Invalid BLE PSM value, PSM: 0x{:04x}", psm);
return 0;
}
@@ -431,25 +431,26 @@
(p_cb_info.pL2CA_ConnectInd_Cb == NULL)) {
vpsm = L2CA_AllocateLePSM();
if (vpsm == 0) {
- LOG_ERROR("Out of free BLE PSM");
+ log::error("Out of free BLE PSM");
return 0;
}
- LOG_DEBUG("Real PSM: 0x%04x Virtual PSM: 0x%04x", psm, vpsm);
+ log::debug("Real PSM: 0x{:04x} Virtual PSM: 0x{:04x}", psm, vpsm);
}
/* If registration block already there, just overwrite it */
p_rcb = l2cu_find_ble_rcb_by_psm(vpsm);
if (p_rcb == NULL) {
- LOG_DEBUG("Allocate rcp for Virtual PSM: 0x%04x", vpsm);
+ log::debug("Allocate rcp for Virtual PSM: 0x{:04x}", vpsm);
p_rcb = l2cu_allocate_ble_rcb(vpsm);
if (p_rcb == NULL) {
- LOG_WARN("No BLE RCB available, PSM: 0x%04x vPSM: 0x%04x", psm, vpsm);
+ log::warn("No BLE RCB available, PSM: 0x{:04x} vPSM: 0x{:04x}", psm,
+ vpsm);
return 0;
}
}
- LOG_INFO("Registered service LE COC PSM: 0x%04x", psm);
+ log::info("Registered service LE COC PSM: 0x{:04x}", psm);
p_rcb->api = p_cb_info;
p_rcb->real_psm = psm;
p_rcb->coc_cfg = cfg;
@@ -468,11 +469,11 @@
*
******************************************************************************/
void L2CA_DeregisterLECoc(uint16_t psm) {
- LOG_VERBOSE("%s called for PSM: 0x%04x", __func__, psm);
+ log::verbose("called for PSM: 0x{:04x}", psm);
tL2C_RCB* p_rcb = l2cu_find_ble_rcb_by_psm(psm);
if (p_rcb == NULL) {
- LOG_WARN("%s PSM: 0x%04x not found for deregistration", __func__, psm);
+ log::warn("PSM: 0x{:04x} not found for deregistration", psm);
return;
}
@@ -516,19 +517,19 @@
get_btm_client_interface().security.BTM_SetSecurityLevel(
true, "", 0, sec_level, psm, 0, 0);
- VLOG(1) << __func__ << " BDA: " << ADDRESS_TO_LOGGABLE_STR(p_bd_addr)
- << StringPrintf(" PSM: 0x%04x", psm);
+ log::verbose("BDA: {} PSM: 0x{:04x}", ADDRESS_TO_LOGGABLE_STR(p_bd_addr),
+ psm);
/* Fail if we have not established communications with the controller */
if (!BTM_IsDeviceUp()) {
- LOG_WARN("%s BTU not ready", __func__);
+ log::warn("BTU not ready");
return 0;
}
/* Fail if the PSM is not registered */
tL2C_RCB* p_rcb = l2cu_find_ble_rcb_by_psm(psm);
if (p_rcb == NULL) {
- LOG_WARN("%s No BLE RCB, PSM: 0x%04x", __func__, psm);
+ log::warn("No BLE RCB, PSM: 0x{:04x}", psm);
return 0;
}
@@ -540,8 +541,8 @@
if ((p_lcb == NULL)
/* currently use BR/EDR for ERTM mode l2cap connection */
|| (!l2cu_create_conn_le(p_lcb))) {
- LOG_WARN("%s conn not started for PSM: 0x%04x p_lcb: 0x%p", __func__,
- psm, p_lcb);
+ log::warn("conn not started for PSM: 0x{:04x} p_lcb: 0x{}", psm,
+ fmt::ptr(p_lcb));
return 0;
}
}
@@ -549,7 +550,7 @@
/* Allocate a channel control block */
tL2C_CCB* p_ccb = l2cu_allocate_ccb(p_lcb, 0);
if (p_ccb == NULL) {
- LOG_WARN("%s no CCB, PSM: 0x%04x", __func__, psm);
+ log::warn("no CCB, PSM: 0x{:04x}", psm);
return 0;
}
@@ -567,7 +568,7 @@
/* If link is up, start the L2CAP connection */
if (p_lcb->link_state == LST_CONNECTED) {
if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) {
- LOG_VERBOSE("%s LE Link is up", __func__);
+ log::verbose("LE Link is up");
// post this asynchronously to avoid out-of-order callback invocation
// should this operation fail
do_in_main_thread(
@@ -583,14 +584,13 @@
* arrives
*/
else if (p_lcb->link_state == LST_DISCONNECTING) {
- LOG_VERBOSE("%s link disconnecting: RETRY LATER", __func__);
+ log::verbose("link disconnecting: RETRY LATER");
/* Save ccb so it can be started after disconnect is finished */
p_lcb->p_pending_ccb = p_ccb;
}
- LOG_VERBOSE("%s(psm: 0x%04x) returned CID: 0x%04x", __func__, psm,
- p_ccb->local_cid);
+ log::verbose("(psm: 0x{:04x}) returned CID: 0x{:04x}", psm, p_ccb->local_cid);
/* Return the local CID as our handle */
return p_ccb->local_cid;
@@ -610,11 +610,11 @@
*
******************************************************************************/
bool L2CA_GetPeerLECocConfig(uint16_t lcid, tL2CAP_LE_CFG_INFO* peer_cfg) {
- LOG_VERBOSE("%s CID: 0x%04x", __func__, lcid);
+ log::verbose("CID: 0x{:04x}", lcid);
tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(NULL, lcid);
if (p_ccb == NULL) {
- LOG_ERROR("%s No CCB for CID:0x%04x", __func__, lcid);
+ log::error("No CCB for CID:0x{:04x}", lcid);
return false;
}
@@ -639,13 +639,13 @@
tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_LE);
if (p_lcb == NULL) {
/* No link. Get an LCB and start link establishment */
- LOG_WARN("%s no LCB", __func__);
+ log::warn("no LCB");
return L2CAP_LE_CREDIT_MAX;
}
tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(p_lcb, lcid);
if (p_ccb == NULL) {
- LOG_ERROR("%s No CCB for CID:0x%04x", __func__, lcid);
+ log::error("No CCB for CID:0x{:04x}", lcid);
return L2CAP_LE_CREDIT_MAX;
}
@@ -671,15 +671,15 @@
bool L2CA_ConnectCreditBasedRsp(const RawAddress& p_bd_addr, uint8_t id,
std::vector<uint16_t>& accepted_lcids,
uint16_t result, tL2CAP_LE_CFG_INFO* p_cfg) {
- VLOG(1) << __func__ << " BDA: " << ADDRESS_TO_LOGGABLE_STR(p_bd_addr)
- << StringPrintf(" num of cids: %d Result: %d",
- int(accepted_lcids.size()), +result);
+ log::verbose("BDA: {} num of cids: {} Result: {}",
+ ADDRESS_TO_LOGGABLE_STR(p_bd_addr), int(accepted_lcids.size()),
+ result);
/* First, find the link control block */
tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(p_bd_addr, BT_TRANSPORT_LE);
if (p_lcb == NULL) {
/* No link. Get an LCB and start link establishment */
- LOG_WARN("%s no LCB", __func__);
+ log::warn("no LCB");
return false;
}
@@ -688,14 +688,14 @@
tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(p_lcb, p_lcb->pending_lead_cid);
if (!p_ccb) {
- LOG_ERROR("%s No CCB for CID:0x%04x", __func__, p_lcb->pending_lead_cid);
+ log::error("No CCB for CID:0x{:04x}", p_lcb->pending_lead_cid);
return false;
}
for (uint16_t cid : accepted_lcids) {
tL2C_CCB* temp_p_ccb = l2cu_find_ccb_by_cid(p_lcb, cid);
if (temp_p_ccb == NULL) {
- LOG_WARN("%s no CCB", __func__);
+ log::warn("no CCB");
return false;
}
@@ -707,8 +707,7 @@
/* The IDs must match */
if (p_ccb->remote_id != id) {
- LOG_WARN("%s bad id. Expected: %d Got: %d", __func__, p_ccb->remote_id,
- id);
+ log::warn("bad id. Expected: {} Got: {}", p_ccb->remote_id, id);
return false;
}
@@ -743,46 +742,46 @@
std::vector<uint16_t> L2CA_ConnectCreditBasedReq(uint16_t psm,
const RawAddress& p_bd_addr,
tL2CAP_LE_CFG_INFO* p_cfg) {
- VLOG(1) << __func__ << " BDA: " << ADDRESS_TO_LOGGABLE_STR(p_bd_addr)
- << StringPrintf(" PSM: 0x%04x", psm);
+ log::verbose("BDA: {} PSM: 0x{:04x}", ADDRESS_TO_LOGGABLE_STR(p_bd_addr),
+ psm);
std::vector<uint16_t> allocated_cids;
/* Fail if we have not established communications with the controller */
if (!BTM_IsDeviceUp()) {
- LOG_WARN("%s BTU not ready", __func__);
+ log::warn("BTU not ready");
return allocated_cids;
}
if (!p_cfg) {
- LOG_WARN("%s p_cfg is NULL", __func__);
+ log::warn("p_cfg is NULL");
return allocated_cids;
}
/* Fail if the PSM is not registered */
tL2C_RCB* p_rcb = l2cu_find_ble_rcb_by_psm(psm);
if (p_rcb == NULL) {
- LOG_WARN("%s No BLE RCB, PSM: 0x%04x", __func__, psm);
+ log::warn("No BLE RCB, PSM: 0x{:04x}", psm);
return allocated_cids;
}
/* First, see if we already have a le link to the remote */
tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(p_bd_addr, BT_TRANSPORT_LE);
if (p_lcb == NULL) {
- LOG_WARN("%s No link available", __func__);
+ log::warn("No link available");
return allocated_cids;
}
if (p_lcb->link_state != LST_CONNECTED) {
- LOG_WARN("%s incorrect link state: %d", __func__, p_lcb->link_state);
+ log::warn("incorrect link state: {}", p_lcb->link_state);
return allocated_cids;
}
- LOG_VERBOSE("%s LE Link is up", __func__);
+ log::verbose("LE Link is up");
/* Check if there is no ongoing connection request */
if (p_lcb->pending_ecoc_conn_cnt > 0) {
- LOG_WARN("There is ongoing connection request, PSM: 0x%04x", psm);
+ log::warn("There is ongoing connection request, PSM: 0x{:04x}", psm);
return allocated_cids;
}
@@ -800,7 +799,7 @@
l2cu_allocate_ccb(p_lcb, 0, psm == BT_PSM_EATT /* is_eatt */);
if (p_ccb == NULL) {
if (i == 0) {
- LOG_WARN("%s no CCB, PSM: 0x%04x", __func__, psm);
+ log::warn("no CCB, PSM: 0x{:04x}", psm);
return allocated_cids;
} else {
break;
@@ -832,8 +831,8 @@
p_lcb->pending_ecoc_conn_cnt = (uint16_t)(allocated_cids.size());
l2c_csm_execute(p_ccb_primary, L2CEVT_L2CA_CREDIT_BASED_CONNECT_REQ, NULL);
- LOG_VERBOSE("%s(psm: 0x%04x) returned CID: 0x%04x", __func__, psm,
- p_ccb_primary->local_cid);
+ log::verbose("(psm: 0x{:04x}) returned CID: 0x{:04x}", psm,
+ p_ccb_primary->local_cid);
return allocated_cids;
}
@@ -856,10 +855,10 @@
tL2CAP_LE_CFG_INFO* p_cfg) {
tL2C_CCB* p_ccb;
- LOG_VERBOSE("L2CA_ReconfigCreditBasedConnsReq() ");
+ log::verbose("L2CA_ReconfigCreditBasedConnsReq() ");
if (lcids.empty()) {
- LOG_WARN("L2CAP - no lcids given to %s", __func__);
+ log::warn("L2CAP - empty lcids");
return (false);
}
@@ -867,28 +866,28 @@
p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
if (!p_ccb) {
- LOG_WARN("L2CAP - no CCB for L2CA_cfg_req, CID: %d", cid);
+ log::warn("L2CAP - no CCB for L2CA_cfg_req, CID: {}", cid);
return (false);
}
if ((p_ccb->local_conn_cfg.mtu > p_cfg->mtu) ||
(p_ccb->local_conn_cfg.mps > p_cfg->mps)) {
- LOG_WARN("L2CAP - MPS or MTU reduction, CID: %d", cid);
+ log::warn("L2CAP - MPS or MTU reduction, CID: {}", cid);
return (false);
}
}
if (p_cfg->mtu > L2CAP_MTU_SIZE) {
- LOG_WARN("L2CAP - adjust MTU: %u too large", p_cfg->mtu);
+ log::warn("L2CAP - adjust MTU: {} too large", p_cfg->mtu);
p_cfg->mtu = L2CAP_MTU_SIZE;
}
/* Mark all the p_ccbs which going to be reconfigured */
for (uint16_t cid : lcids) {
- LOG_VERBOSE(" cid: %d", cid);
+ log::verbose("cid: {}", cid);
p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
if (!p_ccb) {
- LOG(ERROR) << __func__ << "Missing cid? " << int(cid);
+ log::error("Missing cid? {}", int(cid));
return (false);
}
p_ccb->reconfig_started = true;
@@ -927,11 +926,11 @@
/* Find the channel control block. We don't know the link it is on. */
p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
if (p_ccb == NULL) {
- LOG_WARN("L2CAP - no CCB for L2CA_disc_req, CID: %d", cid);
+ log::warn("L2CAP - no CCB for L2CA_disc_req, CID: {}", cid);
return (false);
}
- LOG_DEBUG("L2CAP Local disconnect request CID: 0x%04x", cid);
+ log::debug("L2CAP Local disconnect request CID: 0x{:04x}", cid);
l2c_csm_execute(p_ccb, L2CEVT_L2CA_DISCONNECT_REQ, NULL);
@@ -1009,12 +1008,12 @@
/* Find the link control block for the acl channel */
tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_BR_EDR);
if (p_lcb == nullptr) {
- LOG_WARN("L2CAP - no LCB for L2CA_SetUseLatencyMode, BDA: %s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::warn("L2CAP - no LCB for L2CA_SetUseLatencyMode, BDA: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return false;
}
- LOG_INFO("BDA: %s, use_latency_mode: %s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
- use_latency_mode ? "true" : "false");
+ log::info("BDA: {}, use_latency_mode: {}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ use_latency_mode ? "true" : "false");
p_lcb->use_latency_mode = use_latency_mode;
return true;
}
@@ -1031,8 +1030,8 @@
*
******************************************************************************/
bool L2CA_SetAclPriority(const RawAddress& bd_addr, tL2CAP_PRIORITY priority) {
- VLOG(1) << __func__ << " BDA: " << ADDRESS_TO_LOGGABLE_STR(bd_addr)
- << ", priority: " << std::to_string(priority);
+ log::verbose("BDA: {}, priority: {}", ADDRESS_TO_LOGGABLE_STR(bd_addr),
+ priority);
return (l2cu_set_acl_priority(bd_addr, priority, false));
}
@@ -1046,8 +1045,8 @@
*
******************************************************************************/
bool L2CA_SetAclLatency(const RawAddress& bd_addr, tL2CAP_LATENCY latency) {
- LOG_INFO("BDA: %s, latency: %s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
- std::to_string(latency).c_str());
+ log::info("BDA: {}, latency: {}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ std::to_string(latency));
return l2cu_set_acl_latency(bd_addr, latency);
}
@@ -1063,12 +1062,13 @@
bool L2CA_SetTxPriority(uint16_t cid, tL2CAP_CHNL_PRIORITY priority) {
tL2C_CCB* p_ccb;
- LOG_VERBOSE("L2CA_SetTxPriority() CID: 0x%04x, priority:%d", cid, priority);
+ log::verbose("L2CA_SetTxPriority() CID: 0x{:04x}, priority:{}", cid,
+ priority);
/* Find the channel control block. We don't know the link it is on. */
p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
if (p_ccb == NULL) {
- LOG_WARN("L2CAP - no CCB for L2CA_SetTxPriority, CID: %d", cid);
+ log::warn("L2CAP - no CCB for L2CA_SetTxPriority, CID: {}", cid);
return (false);
}
@@ -1098,13 +1098,13 @@
/* We must already have a link to the remote */
p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_BR_EDR);
if (p_lcb == NULL) {
- LOG(WARNING) << __func__ << " No BDA: " << ADDRESS_TO_LOGGABLE_STR(bd_addr);
+ log::warn("No BDA: {}", ADDRESS_TO_LOGGABLE_STR(bd_addr));
return false;
}
- VLOG(1) << __func__ << " BDA: " << ADDRESS_TO_LOGGABLE_STR(bd_addr)
- << StringPrintf(" ExtFea: 0x%08x Chnl_Mask[0]: 0x%02x",
- p_lcb->peer_ext_fea, p_lcb->peer_chnl_mask[0]);
+ log::verbose("BDA: {} ExtFea: 0x{:08x} Chnl_Mask[0]: 0x{:02x}",
+ ADDRESS_TO_LOGGABLE_STR(bd_addr), p_lcb->peer_ext_fea,
+ p_lcb->peer_chnl_mask[0]);
*p_ext_feat = p_lcb->peer_ext_fea;
@@ -1150,13 +1150,12 @@
tL2CAP_FIXED_CHNL_REG* p_freg) {
if ((fixed_cid < L2CAP_FIRST_FIXED_CHNL) ||
(fixed_cid > L2CAP_LAST_FIXED_CHNL)) {
- LOG_ERROR("Invalid fixed CID: 0x%04x", fixed_cid);
+ log::error("Invalid fixed CID: 0x{:04x}", fixed_cid);
return false;
}
l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL] = *p_freg;
- LOG_DEBUG("Registered fixed channel:%s",
- fixed_channel_text(fixed_cid).c_str());
+ log::debug("Registered fixed channel:{}", fixed_channel_text(fixed_cid));
return true;
}
@@ -1176,20 +1175,20 @@
tL2C_LCB* p_lcb;
tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR;
- LOG_DEBUG(" fixed_cid:0x%04x", fixed_cid);
+ log::debug("fixed_cid:0x{:04x}", fixed_cid);
// Check CID is valid and registered
if ((fixed_cid < L2CAP_FIRST_FIXED_CHNL) ||
(fixed_cid > L2CAP_LAST_FIXED_CHNL) ||
(l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb ==
NULL)) {
- LOG_ERROR("Invalid fixed_cid:0x%04x", fixed_cid);
+ log::error("Invalid fixed_cid:0x{:04x}", fixed_cid);
return (false);
}
// Fail if BT is not yet up
if (!BTM_IsDeviceUp()) {
- LOG_WARN("Bt controller is not ready fixed_cid:0x%04x", fixed_cid);
+ log::warn("Bt controller is not ready fixed_cid:0x{:04x}", fixed_cid);
return (false);
}
@@ -1211,21 +1210,21 @@
// Check for supported channel
if (!(peer_channel_mask & (1 << fixed_cid))) {
- LOG_INFO("Peer device does not support fixed_cid:0x%04x", fixed_cid);
+ log::info("Peer device does not support fixed_cid:0x{:04x}", fixed_cid);
return false;
}
// Get a CCB and link the lcb to it
if (!l2cu_initialize_fixed_ccb(p_lcb, fixed_cid)) {
- LOG_WARN("Unable to allocate fixed channel resource fixed_cid:0x%04x",
- fixed_cid);
+ log::warn("Unable to allocate fixed channel resource fixed_cid:0x{:04x}",
+ fixed_cid);
return false;
}
// racing with disconnecting, queue the connection request
if (p_lcb->link_state == LST_DISCONNECTING) {
- LOG_DEBUG(
- "Link is disconnecting so deferring connection fixed_cid:0x%04x",
+ log::debug(
+ "Link is disconnecting so deferring connection fixed_cid:0x{:04x}",
fixed_cid);
/* Save ccb so it can be started after disconnect is finished */
p_lcb->p_pending_ccb =
@@ -1241,15 +1240,16 @@
// No link. Get an LCB and start link establishment
p_lcb = l2cu_allocate_lcb(rem_bda, false, transport);
if (p_lcb == NULL) {
- LOG_WARN("Unable to allocate link resource for connection fixed_cid:0x%04x",
- fixed_cid);
+ log::warn(
+ "Unable to allocate link resource for connection fixed_cid:0x{:04x}",
+ fixed_cid);
return false;
}
// Get a CCB and link the lcb to it
if (!l2cu_initialize_fixed_ccb(p_lcb, fixed_cid)) {
- LOG_WARN("Unable to allocate fixed channel resource fixed_cid:0x%04x",
- fixed_cid);
+ log::warn("Unable to allocate fixed channel resource fixed_cid:0x{:04x}",
+ fixed_cid);
l2cu_release_lcb(p_lcb);
return false;
}
@@ -1257,8 +1257,9 @@
if (transport == BT_TRANSPORT_LE) {
bool ret = l2cu_create_conn_le(p_lcb);
if (!ret) {
- LOG_WARN("Unable to create fixed channel le connection fixed_cid:0x%04x",
- fixed_cid);
+ log::warn(
+ "Unable to create fixed channel le connection fixed_cid:0x{:04x}",
+ fixed_cid);
l2cu_release_lcb(p_lcb);
return false;
}
@@ -1294,13 +1295,13 @@
(fixed_cid > L2CAP_LAST_FIXED_CHNL) ||
(l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb ==
NULL)) {
- LOG_WARN("No service registered or invalid CID: 0x%04x", fixed_cid);
+ log::warn("No service registered or invalid CID: 0x{:04x}", fixed_cid);
osi_free(p_buf);
return (L2CAP_DW_FAILED);
}
if (!BTM_IsDeviceUp()) {
- LOG_WARN("Controller is not ready CID: 0x%04x", fixed_cid);
+ log::warn("Controller is not ready CID: 0x{:04x}", fixed_cid);
osi_free(p_buf);
return (L2CAP_DW_FAILED);
}
@@ -1308,7 +1309,8 @@
p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, transport);
if (p_lcb == NULL || p_lcb->link_state == LST_DISCONNECTING) {
/* if link is disconnecting, also report data sending failure */
- LOG_WARN("Link is disconnecting or does not exist CID: 0x%04x", fixed_cid);
+ log::warn("Link is disconnecting or does not exist CID: 0x{:04x}",
+ fixed_cid);
osi_free(p_buf);
return (L2CAP_DW_FAILED);
}
@@ -1322,7 +1324,7 @@
peer_channel_mask = p_lcb->peer_chnl_mask[0];
if ((peer_channel_mask & (1 << fixed_cid)) == 0) {
- LOG_WARN("Peer does not support fixed channel CID: 0x%04x", fixed_cid);
+ log::warn("Peer does not support fixed channel CID: 0x{:04x}", fixed_cid);
osi_free(p_buf);
return (L2CAP_DW_FAILED);
}
@@ -1332,16 +1334,16 @@
if (!p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]) {
if (!l2cu_initialize_fixed_ccb(p_lcb, fixed_cid)) {
- LOG_WARN("No channel control block found for CID: 0x%4x", fixed_cid);
+ log::warn("No channel control block found for CID: 0x{:4x}", fixed_cid);
osi_free(p_buf);
return (L2CAP_DW_FAILED);
}
}
if (p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]->cong_sent) {
- LOG_WARN(
- "Unable to send data due to congestion CID: 0x%04x xmit_hold_q.count: "
- "%zu buff_quota: %u",
+ log::warn(
+ "Unable to send data due to congestion CID: 0x{:04x} "
+ "xmit_hold_q.count: {} buff_quota: {}",
fixed_cid,
fixed_queue_length(
p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]
@@ -1351,7 +1353,7 @@
return (L2CAP_DW_FAILED);
}
- LOG_DEBUG("Enqueued data for CID: 0x%04x len:%hu", fixed_cid, p_buf->len);
+ log::debug("Enqueued data for CID: 0x{:04x} len:{}", fixed_cid, p_buf->len);
l2c_enqueue_peer_data(p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL],
p_buf);
@@ -1365,7 +1367,7 @@
}
if (p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]->cong_sent) {
- LOG_DEBUG("Link congested for CID: 0x%04x", fixed_cid);
+ log::debug("Link congested for CID: 0x{:04x}", fixed_cid);
return (L2CAP_DW_CONGESTED);
}
@@ -1395,7 +1397,7 @@
(fixed_cid > L2CAP_LAST_FIXED_CHNL) ||
(l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb ==
NULL)) {
- LOG_ERROR("L2CA_RemoveFixedChnl() Invalid CID: 0x%04x", fixed_cid);
+ log::error("L2CA_RemoveFixedChnl() Invalid CID: 0x{:04x}", fixed_cid);
return (false);
}
@@ -1407,13 +1409,13 @@
if (((p_lcb) == NULL) ||
(!p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL])) {
- LOG(WARNING) << __func__ << " BDA: " << ADDRESS_TO_LOGGABLE_STR(rem_bda)
- << StringPrintf(" CID: 0x%04x not connected", fixed_cid);
+ log::warn("BDA: {} CID: 0x{:04x} not connected",
+ ADDRESS_TO_LOGGABLE_STR(rem_bda), fixed_cid);
return (false);
}
- VLOG(2) << __func__ << " BDA: " << ADDRESS_TO_LOGGABLE_STR(rem_bda)
- << StringPrintf(" CID: 0x%04x", fixed_cid);
+ log::verbose("BDA: {} CID: 0x{:04x}", ADDRESS_TO_LOGGABLE_STR(rem_bda),
+ fixed_cid);
/* Release the CCB, starting an inactivity timeout on the LCB if no other CCBs
* exist */
@@ -1458,8 +1460,8 @@
tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, BT_TRANSPORT_LE);
if (((p_lcb) == NULL) ||
(!p_lcb->p_fixed_ccbs[kAttCid - L2CAP_FIRST_FIXED_CHNL])) {
- LOG(WARNING) << __func__ << " BDA: " << ADDRESS_TO_LOGGABLE_STR(rem_bda)
- << StringPrintf(" CID: 0x%04x not connected", kAttCid);
+ log::warn("BDA: {} CID: 0x{:04x} not connected",
+ ADDRESS_TO_LOGGABLE_STR(rem_bda), kAttCid);
return (false);
}
@@ -1481,8 +1483,7 @@
if (p_lcb == NULL) {
return false;
}
- LOG(INFO) << __func__ << "setting link to "
- << ADDRESS_TO_LOGGABLE_STR(rem_bda) << " as active";
+ log::info("setting link to {} as active", ADDRESS_TO_LOGGABLE_STR(rem_bda));
p_lcb->with_active_local_clients = true;
return true;
}
@@ -1500,7 +1501,7 @@
*
******************************************************************************/
uint8_t L2CA_DataWrite(uint16_t cid, BT_HDR* p_data) {
- LOG_VERBOSE("L2CA_DataWrite() CID: 0x%04x Len: %d", cid, p_data->len);
+ log::verbose("L2CA_DataWrite() CID: 0x{:04x} Len: {}", cid, p_data->len);
return l2c_data_write(cid, p_data, L2CAP_FLUSHABLE_CH_BASED);
}
@@ -1524,14 +1525,14 @@
/* Find the channel control block. We don't know the link it is on. */
p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
if (p_ccb == NULL) {
- LOG_WARN("L2CAP - no CCB for L2CA_SetChnlFlushability, CID: %d", cid);
+ log::warn("L2CAP - no CCB for L2CA_SetChnlFlushability, CID: {}", cid);
return (false);
}
p_ccb->is_flushable = is_flushable;
- LOG_VERBOSE("L2CA_SetChnlFlushability() CID: 0x%04x is_flushable: %d", cid,
- is_flushable);
+ log::verbose("L2CA_SetChnlFlushability() CID: 0x{:04x} is_flushable: {}",
+ cid, is_flushable);
return (true);
}
@@ -1558,19 +1559,20 @@
p_ccb = l2cu_find_ccb_by_cid(NULL, lcid);
if (!p_ccb || (p_ccb->p_lcb == NULL)) {
- LOG_WARN("L2CA_FlushChannel() abnormally returning 0 CID: 0x%04x", lcid);
+ log::warn("L2CA_FlushChannel() abnormally returning 0 CID: 0x{:04x}",
+ lcid);
return (0);
}
p_lcb = p_ccb->p_lcb;
if (num_to_flush != L2CAP_FLUSH_CHANS_GET) {
- LOG_VERBOSE(
- "L2CA_FlushChannel (FLUSH) CID: 0x%04x NumToFlush: %d QC: %zu "
- "pFirst: 0x%p",
+ log::verbose(
+ "L2CA_FlushChannel (FLUSH) CID: 0x{:04x} NumToFlush: {} QC: {} "
+ "pFirst: 0x{}",
lcid, num_to_flush, fixed_queue_length(p_ccb->xmit_hold_q),
- fixed_queue_try_peek_first(p_ccb->xmit_hold_q));
+ fmt::ptr(fixed_queue_try_peek_first(p_ccb->xmit_hold_q)));
} else {
- LOG_VERBOSE("L2CA_FlushChannel (QUERY) CID: 0x%04x", lcid);
+ log::verbose("L2CA_FlushChannel (QUERY) CID: 0x{:04x}", lcid);
}
/* Cannot flush eRTM buffers once they have a sequence number */
@@ -1627,8 +1629,8 @@
num_left += fixed_queue_length(p_ccb->xmit_hold_q);
/* Return the local number of buffers left for the CID */
- LOG_VERBOSE("L2CA_FlushChannel() flushed: %u + %u, num_left: %u",
- num_flushed1, num_flushed2, num_left);
+ log::verbose("L2CA_FlushChannel() flushed: {} + {}, num_left: {}",
+ num_flushed1, num_flushed2, num_left);
/* If we were congested, and now we are not, tell the app */
l2cu_check_channel_congestion(p_ccb);
@@ -1661,7 +1663,7 @@
bluetooth::hal::SnoopLogger* snoop_logger = bluetooth::shim::GetSnoopLogger();
if (snoop_logger == nullptr) {
- LOG_ERROR("bluetooth::shim::GetSnoopLogger() is nullptr");
+ log::error("bluetooth::shim::GetSnoopLogger() is nullptr");
return;
}
@@ -1669,8 +1671,8 @@
return;
}
- LOG_DEBUG("local_media_cid=%d, status=%s", local_media_cid,
- (status ? "add" : "remove"));
+ log::debug("local_media_cid={}, status={}", local_media_cid,
+ (status ? "add" : "remove"));
if (status) {
for (i = 0; i < MAX_ACTIVE_AVDT_CONN; i++) {
@@ -1681,7 +1683,7 @@
}
if (set_channel < 0) {
- LOG_ERROR("%s: No empty slot found to set media channel", __func__);
+ log::error("No empty slot found to set media channel");
return;
}
@@ -1699,10 +1701,9 @@
av_media_channels[set_channel].local_cid,
av_media_channels[set_channel].p_ccb->remote_cid);
- LOG_VERBOSE(
- "%s: Set A2DP media snoop filtering for local_cid: %d, remote_cid: %d",
- __func__, local_media_cid,
- av_media_channels[set_channel].p_ccb->remote_cid);
+ log::verbose(
+ "Set A2DP media snoop filtering for local_cid: {}, remote_cid: {}",
+ local_media_cid, av_media_channels[set_channel].p_ccb->remote_cid);
} else {
for (i = 0; i < MAX_ACTIVE_AVDT_CONN; i++) {
if (av_media_channels[i].is_active &&
@@ -1713,8 +1714,8 @@
}
if (set_channel < 0) {
- LOG_ERROR("%s: The channel %d not found in active media channels",
- __func__, local_media_cid);
+ log::error("The channel {} not found in active media channels",
+ local_media_cid);
return;
}
@@ -1727,8 +1728,8 @@
av_media_channels[set_channel].p_ccb->p_lcb->Handle(),
av_media_channels[set_channel].local_cid);
- LOG_VERBOSE("%s: Reset A2DP media snoop filtering for local_cid: %d",
- __func__, local_media_cid);
+ log::verbose("Reset A2DP media snoop filtering for local_cid: {}",
+ local_media_cid);
}
av_media_channels[set_channel].is_active = status;
diff --git a/system/stack/l2cap/l2c_ble.cc b/system/stack/l2cap/l2c_ble.cc
index e1d7394..d83d253 100644
--- a/system/stack/l2cap/l2c_ble.cc
+++ b/system/stack/l2cap/l2c_ble.cc
@@ -26,6 +26,7 @@
#include <base/logging.h>
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <log/log.h>
#ifdef __ANDROID__
@@ -57,6 +58,8 @@
#include "stack/l2cap/l2c_int.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
namespace {
constexpr char kBtmLogTag[] = "L2CAP";
@@ -75,9 +78,9 @@
return;
}
- LOG_INFO("consolidating l2c_lcb record %s -> %s",
- ADDRESS_TO_LOGGABLE_CSTR(rpa),
- ADDRESS_TO_LOGGABLE_CSTR(identity_addr));
+ log::info("consolidating l2c_lcb record {} -> {}",
+ ADDRESS_TO_LOGGABLE_CSTR(rpa),
+ ADDRESS_TO_LOGGABLE_CSTR(identity_addr));
p_lcb->remote_bd_addr = identity_addr;
}
@@ -101,7 +104,7 @@
void l2cble_notify_le_connection(const RawAddress& bda) {
tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(bda, BT_TRANSPORT_LE);
if (p_lcb == nullptr) {
- LOG_WARN("Received notification for le connection but no lcb found");
+ log::warn("Received notification for le connection but no lcb found");
return;
}
@@ -138,17 +141,17 @@
if (!p_lcb) {
p_lcb = l2cu_allocate_lcb(bda, false, BT_TRANSPORT_LE);
if (!p_lcb) {
- LOG_ERROR("Unable to allocate link resource for le acl connection");
+ log::error("Unable to allocate link resource for le acl connection");
return false;
} else {
if (!l2cu_initialize_fixed_ccb(p_lcb, L2CAP_ATT_CID)) {
- LOG_ERROR("Unable to allocate channel resource for le acl connection");
+ log::error("Unable to allocate channel resource for le acl connection");
return false;
}
}
p_lcb->link_state = LST_CONNECTING;
} else if (role == HCI_ROLE_CENTRAL && p_lcb->link_state != LST_CONNECTING) {
- LOG_ERROR(
+ log::error(
"Received le acl connection as role central but not in connecting "
"state");
return false;
@@ -248,7 +251,7 @@
p_pkt_end = p + pkt_len;
if (p + 4 > p_pkt_end) {
- LOG(ERROR) << "invalid read";
+ log::error("invalid read");
return;
}
@@ -258,8 +261,8 @@
/* Check command length does not exceed packet length */
if ((p + cmd_len) > p_pkt_end) {
- LOG_WARN("L2CAP - LE - format error, pkt_len: %d cmd_len: %d code: %d",
- pkt_len, cmd_len, cmd_code);
+ log::warn("L2CAP - LE - format error, pkt_len: {} cmd_len: {} code: {}",
+ pkt_len, cmd_len, cmd_code);
return;
}
@@ -268,8 +271,9 @@
uint16_t reason;
if (p + 2 > p_pkt_end) {
- LOG(ERROR) << "invalid L2CAP_CMD_REJECT packet,"
- << " not containing enough data for `reason` field";
+ log::error(
+ "invalid L2CAP_CMD_REJECT packet, not containing enough data for "
+ "`reason` field");
return;
}
@@ -291,7 +295,7 @@
case L2CAP_CMD_BLE_UPDATE_REQ:
if (p + 8 > p_pkt_end) {
- LOG(ERROR) << "invalid read";
+ log::error("invalid read");
return;
}
@@ -339,7 +343,7 @@
case L2CAP_CMD_CREDIT_BASED_CONN_REQ: {
if (p + 10 > p_pkt_end) {
- LOG(ERROR) << "invalid L2CAP_CMD_CREDIT_BASED_CONN_REQ len";
+ log::error("invalid L2CAP_CMD_CREDIT_BASED_CONN_REQ len");
return;
}
@@ -351,33 +355,31 @@
/* Check how many channels remote side wants. */
num_of_channels = (p_pkt_end - p) / sizeof(uint16_t);
if (num_of_channels > L2CAP_CREDIT_BASED_MAX_CIDS) {
- LOG_WARN("L2CAP - invalid number of channels requested: %d",
- num_of_channels);
+ log::warn("L2CAP - invalid number of channels requested: {}",
+ num_of_channels);
l2cu_reject_credit_based_conn_req(p_lcb, id,
L2CAP_CREDIT_BASED_MAX_CIDS,
L2CAP_LE_RESULT_INVALID_PARAMETERS);
return;
}
- LOG_DEBUG(
- "Recv L2CAP_CMD_CREDIT_BASED_CONN_REQ with "
- "mtu = %d, "
- "mps = %d, "
- "initial credit = %d"
- "num_of_channels = %d",
+ log::debug(
+ "Recv L2CAP_CMD_CREDIT_BASED_CONN_REQ with mtu = {}, mps = {}, "
+ "initial credit = {}num_of_channels = {}",
mtu, mps, initial_credit, num_of_channels);
/* Check PSM Support */
p_rcb = l2cu_find_ble_rcb_by_psm(con_info.psm);
if (p_rcb == NULL) {
- LOG_WARN("L2CAP - rcvd conn req for unknown PSM: 0x%04x", con_info.psm);
+ log::warn("L2CAP - rcvd conn req for unknown PSM: 0x{:04x}",
+ con_info.psm);
l2cu_reject_credit_based_conn_req(p_lcb, id, num_of_channels,
L2CAP_LE_RESULT_NO_PSM);
return;
}
if (p_lcb->pending_ecoc_conn_cnt > 0) {
- LOG_WARN("L2CAP - L2CAP_CMD_CREDIT_BASED_CONN_REQ collision:");
+ log::warn("L2CAP - L2CAP_CMD_CREDIT_BASED_CONN_REQ collision:");
if (p_rcb->api.pL2CA_CreditBasedCollisionInd_Cb &&
con_info.psm == BT_PSM_EATT) {
(*p_rcb->api.pL2CA_CreditBasedCollisionInd_Cb)(p_lcb->remote_bd_addr);
@@ -390,8 +392,8 @@
p_lcb->pending_ecoc_conn_cnt = num_of_channels;
if (!p_rcb->api.pL2CA_CreditBasedConnectInd_Cb) {
- LOG_WARN("L2CAP - rcvd conn req for outgoing-only connection PSM: %d",
- con_info.psm);
+ log::warn("L2CAP - rcvd conn req for outgoing-only connection PSM: {}",
+ con_info.psm);
l2cu_reject_credit_based_conn_req(p_lcb, id, num_of_channels,
L2CAP_CONN_NO_PSM);
return;
@@ -400,7 +402,7 @@
/* validate the parameters */
if (mtu < L2CAP_CREDIT_BASED_MIN_MTU ||
mps < L2CAP_CREDIT_BASED_MIN_MPS || mps > L2CAP_LE_MAX_MPS) {
- LOG_ERROR("L2CAP don't like the params");
+ log::error("L2CAP don't like the params");
l2cu_reject_credit_based_conn_req(p_lcb, id, num_of_channels,
L2CAP_LE_RESULT_INVALID_PARAMETERS);
return;
@@ -412,7 +414,7 @@
STREAM_TO_UINT16(rcid, p);
temp_p_ccb = l2cu_find_ccb_by_remote_cid(p_lcb, rcid);
if (temp_p_ccb) {
- LOG_WARN("L2CAP - rcvd conn req for duplicated cid: 0x%04x", rcid);
+ log::warn("L2CAP - rcvd conn req for duplicated cid: 0x{:04x}", rcid);
p_lcb->pending_ecoc_connection_cids[i] = 0;
p_lcb->pending_l2cap_result =
L2CAP_LE_RESULT_SOURCE_CID_ALREADY_ALLOCATED;
@@ -421,7 +423,7 @@
temp_p_ccb = l2cu_allocate_ccb(
p_lcb, 0, con_info.psm == BT_PSM_EATT /* is_eatt */);
if (temp_p_ccb == NULL) {
- LOG_ERROR("L2CAP - unable to allocate CCB");
+ log::error("L2CAP - unable to allocate CCB");
p_lcb->pending_ecoc_connection_cids[i] = 0;
p_lcb->pending_l2cap_result = L2CAP_LE_RESULT_NO_RESOURCES;
continue;
@@ -458,23 +460,23 @@
}
if (!lead_cid_set) {
- LOG_ERROR("L2CAP - unable to allocate CCB");
+ log::error("L2CAP - unable to allocate CCB");
l2cu_reject_credit_based_conn_req(p_lcb, id, num_of_channels,
p_lcb->pending_l2cap_result);
return;
}
- LOG_DEBUG("L2CAP - processing peer credit based connect request");
+ log::debug("L2CAP - processing peer credit based connect request");
l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CREDIT_BASED_CONNECT_REQ, NULL);
break;
}
case L2CAP_CMD_CREDIT_BASED_CONN_RES:
if (p + 8 > p_pkt_end) {
- LOG(ERROR) << "invalid L2CAP_CMD_CREDIT_BASED_CONN_RES len";
+ log::error("invalid L2CAP_CMD_CREDIT_BASED_CONN_RES len");
return;
}
- LOG_VERBOSE("Recv L2CAP_CMD_CREDIT_BASED_CONN_RES");
+ log::verbose("Recv L2CAP_CMD_CREDIT_BASED_CONN_RES");
/* For all channels, see whose identifier matches this id */
for (temp_p_ccb = p_lcb->ccb_queue.p_first_ccb; temp_p_ccb;
temp_p_ccb = temp_p_ccb->p_next_ccb) {
@@ -485,7 +487,7 @@
}
if (!p_ccb) {
- LOG_VERBOSE(" Cannot find matching connection req");
+ log::verbose("Cannot find matching connection req");
con_info.l2cap_result = L2CAP_LE_RESULT_INVALID_SOURCE_CID;
l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP_NEG, &con_info);
return;
@@ -506,7 +508,7 @@
con_info.l2cap_result == L2CAP_LE_RESULT_INSUFFICIENT_AUTHORIZATION ||
con_info.l2cap_result == L2CAP_LE_RESULT_UNACCEPTABLE_PARAMETERS ||
con_info.l2cap_result == L2CAP_LE_RESULT_INVALID_PARAMETERS) {
- LOG_ERROR("L2CAP - not accepted. Status %d", con_info.l2cap_result);
+ log::error("L2CAP - not accepted. Status {}", con_info.l2cap_result);
l2cble_handle_connect_rsp_neg(p_lcb, &con_info);
return;
}
@@ -514,7 +516,7 @@
/* validate the parameters */
if (mtu < L2CAP_CREDIT_BASED_MIN_MTU ||
mps < L2CAP_CREDIT_BASED_MIN_MPS || mps > L2CAP_LE_MAX_MPS) {
- LOG_ERROR("L2CAP - invalid params");
+ log::error("L2CAP - invalid params");
con_info.l2cap_result = L2CAP_LE_RESULT_INVALID_PARAMETERS;
l2cble_handle_connect_rsp_neg(p_lcb, &con_info);
return;
@@ -524,20 +526,16 @@
* good*/
num_of_channels = (p_pkt_end - p) / sizeof(uint16_t);
if (num_of_channels != p_lcb->pending_ecoc_conn_cnt) {
- LOG_ERROR(
- "Incorrect response."
- "expected num of channels = %d"
- "received num of channels = %d",
+ log::error(
+ "Incorrect response.expected num of channels = {} received num of "
+ "channels = {}",
num_of_channels, p_lcb->pending_ecoc_conn_cnt);
return;
}
- LOG_VERBOSE(
- "mtu = %d, "
- "mps = %d, "
- "initial_credit = %d, "
- "con_info.l2cap_result = %d"
- "num_of_channels = %d",
+ log::verbose(
+ "mtu = {}, mps = {}, initial_credit = {}, con_info.l2cap_result = "
+ "{} num_of_channels = {}",
mtu, mps, initial_credit, con_info.l2cap_result, num_of_channels);
con_info.peer_mtu = mtu;
@@ -561,10 +559,9 @@
*/
temp_p_ccb = l2cu_find_ccb_by_remote_cid(p_lcb, rcid);
if (temp_p_ccb != nullptr) {
- LOG_ERROR(
- "Already Allocated Destination cid. "
- "rcid = %d "
- "send peer_disc_req",
+ log::error(
+ "Already Allocated Destination cid. rcid = {} send "
+ "peer_disc_req",
rcid);
l2cu_send_peer_disc_req(temp_p_ccb);
@@ -581,10 +578,8 @@
temp_p_ccb = l2cu_find_ccb_by_cid(p_lcb, cid);
temp_p_ccb->remote_cid = rcid;
- LOG_VERBOSE(
- "local cid = %d "
- "remote cid = %d",
- cid, temp_p_ccb->remote_cid);
+ log::verbose("local cid = {} remote cid = {}", cid,
+ temp_p_ccb->remote_cid);
/* Check if peer accepted channel, if not release the one not
* created
@@ -620,7 +615,7 @@
/* validate the parameters */
if (mtu < L2CAP_CREDIT_BASED_MIN_MTU ||
mps < L2CAP_CREDIT_BASED_MIN_MPS || mps > L2CAP_LE_MAX_MPS) {
- LOG_ERROR("L2CAP - invalid params");
+ log::error("L2CAP - invalid params");
l2cu_send_ble_reconfig_rsp(p_lcb, id, L2CAP_RECONFIG_UNACCAPTED_PARAM);
return;
}
@@ -628,11 +623,9 @@
/* Check how many channels remote side wants to reconfigure */
num_of_channels = (p_pkt_end - p) / sizeof(uint16_t);
- LOG_VERBOSE(
- "Recv L2CAP_CMD_CREDIT_BASED_RECONFIG_REQ with "
- "mtu = %d, "
- "mps = %d, "
- "num_of_channels = %d",
+ log::verbose(
+ "Recv L2CAP_CMD_CREDIT_BASED_RECONFIG_REQ with mtu = {}, mps = {}, "
+ "num_of_channels = {}",
mtu, mps, num_of_channels);
uint8_t* p_tmp = p;
@@ -640,15 +633,15 @@
STREAM_TO_UINT16(rcid, p_tmp);
p_ccb = l2cu_find_ccb_by_remote_cid(p_lcb, rcid);
if (!p_ccb) {
- LOG_WARN("L2CAP - rcvd config req for non existing cid: 0x%04x",
- rcid);
+ log::warn("L2CAP - rcvd config req for non existing cid: 0x{:04x}",
+ rcid);
l2cu_send_ble_reconfig_rsp(p_lcb, id, L2CAP_RECONFIG_INVALID_DCID);
return;
}
if (p_ccb->peer_conn_cfg.mtu > mtu) {
- LOG_WARN(
- "L2CAP - rcvd config req mtu reduction new mtu < mtu (%d < %d)",
+ log::warn(
+ "L2CAP - rcvd config req mtu reduction new mtu < mtu ({} < {})",
mtu, p_ccb->peer_conn_cfg.mtu);
l2cu_send_ble_reconfig_rsp(p_lcb, id,
L2CAP_RECONFIG_REDUCTION_MTU_NO_ALLOWED);
@@ -656,8 +649,8 @@
}
if (p_ccb->peer_conn_cfg.mps > mps && num_of_channels > 1) {
- LOG_WARN(
- "L2CAP - rcvd config req mps reduction new mps < mps (%d < %d)",
+ log::warn(
+ "L2CAP - rcvd config req mps reduction new mps < mps ({} < {})",
mtu, p_ccb->peer_conn_cfg.mtu);
l2cu_send_ble_reconfig_rsp(p_lcb, id,
L2CAP_RECONFIG_REDUCTION_MPS_NO_ALLOWED);
@@ -689,14 +682,13 @@
case L2CAP_CMD_CREDIT_BASED_RECONFIG_RES: {
uint16_t result;
if (p + sizeof(uint16_t) > p_pkt_end) {
- LOG(ERROR) << "invalid read";
+ log::error("invalid read");
return;
}
STREAM_TO_UINT16(result, p);
- LOG_VERBOSE(
- "Recv L2CAP_CMD_CREDIT_BASED_RECONFIG_RES for "
- "result = 0x%04x",
+ log::verbose(
+ "Recv L2CAP_CMD_CREDIT_BASED_RECONFIG_RES for result = 0x{:04x}",
result);
p_lcb->pending_ecoc_reconfig_cfg.result = result;
@@ -722,7 +714,7 @@
case L2CAP_CMD_BLE_CREDIT_BASED_CONN_REQ:
if (p + 10 > p_pkt_end) {
- LOG(ERROR) << "invalid read";
+ log::error("invalid read");
return;
}
@@ -732,16 +724,14 @@
STREAM_TO_UINT16(mps, p);
STREAM_TO_UINT16(initial_credit, p);
- LOG_VERBOSE(
- "Recv L2CAP_CMD_BLE_CREDIT_BASED_CONN_REQ with "
- "mtu = %d, "
- "mps = %d, "
- "initial credit = %d",
+ log::verbose(
+ "Recv L2CAP_CMD_BLE_CREDIT_BASED_CONN_REQ with mtu = {}, mps = {}, "
+ "initial credit = {}",
mtu, mps, initial_credit);
p_ccb = l2cu_find_ccb_by_remote_cid(p_lcb, rcid);
if (p_ccb) {
- LOG_WARN("L2CAP - rcvd conn req for duplicated cid: 0x%04x", rcid);
+ log::warn("L2CAP - rcvd conn req for duplicated cid: 0x{:04x}", rcid);
l2cu_reject_ble_coc_connection(
p_lcb, id, L2CAP_LE_RESULT_SOURCE_CID_ALREADY_ALLOCATED);
break;
@@ -749,13 +739,15 @@
p_rcb = l2cu_find_ble_rcb_by_psm(con_info.psm);
if (p_rcb == NULL) {
- LOG_WARN("L2CAP - rcvd conn req for unknown PSM: 0x%04x", con_info.psm);
+ log::warn("L2CAP - rcvd conn req for unknown PSM: 0x{:04x}",
+ con_info.psm);
l2cu_reject_ble_coc_connection(p_lcb, id, L2CAP_LE_RESULT_NO_PSM);
break;
} else {
if (!p_rcb->api.pL2CA_ConnectInd_Cb) {
- LOG_WARN("L2CAP - rcvd conn req for outgoing-only connection PSM: %d",
- con_info.psm);
+ log::warn(
+ "L2CAP - rcvd conn req for outgoing-only connection PSM: {}",
+ con_info.psm);
l2cu_reject_ble_coc_connection(p_lcb, id, L2CAP_CONN_NO_PSM);
break;
}
@@ -765,7 +757,7 @@
p_ccb = l2cu_allocate_ccb(p_lcb, 0,
con_info.psm == BT_PSM_EATT /* is_eatt */);
if (p_ccb == NULL) {
- LOG_ERROR("L2CAP - unable to allocate CCB");
+ log::error("L2CAP - unable to allocate CCB");
l2cu_reject_ble_connection(p_ccb, id, L2CAP_CONN_NO_RESOURCES);
break;
}
@@ -773,7 +765,7 @@
/* validate the parameters */
if (mtu < L2CAP_LE_MIN_MTU || mps < L2CAP_LE_MIN_MPS ||
mps > L2CAP_LE_MAX_MPS) {
- LOG_ERROR("L2CAP do not like the params");
+ log::error("L2CAP do not like the params");
l2cu_reject_ble_connection(p_ccb, id, L2CAP_CONN_NO_RESOURCES);
break;
}
@@ -804,7 +796,7 @@
break;
case L2CAP_CMD_BLE_CREDIT_BASED_CONN_RES:
- LOG_VERBOSE("Recv L2CAP_CMD_BLE_CREDIT_BASED_CONN_RES");
+ log::verbose("Recv L2CAP_CMD_BLE_CREDIT_BASED_CONN_RES");
/* For all channels, see whose identifier matches this id */
for (temp_p_ccb = p_lcb->ccb_queue.p_first_ccb; temp_p_ccb;
temp_p_ccb = temp_p_ccb->p_next_ccb) {
@@ -814,9 +806,9 @@
}
}
if (p_ccb) {
- LOG_VERBOSE("I remember the connection req");
+ log::verbose("I remember the connection req");
if (p + 10 > p_pkt_end) {
- LOG(ERROR) << "invalid read";
+ log::error("invalid read");
return;
}
@@ -827,12 +819,9 @@
STREAM_TO_UINT16(con_info.l2cap_result, p);
con_info.remote_cid = p_ccb->remote_cid;
- LOG_VERBOSE(
- "remote_cid = %d, "
- "mtu = %d, "
- "mps = %d, "
- "initial_credit = %d, "
- "con_info.l2cap_result = %d",
+ log::verbose(
+ "remote_cid = {}, mtu = {}, mps = {}, initial_credit = {}, "
+ "con_info.l2cap_result = {}",
p_ccb->remote_cid, p_ccb->peer_conn_cfg.mtu,
p_ccb->peer_conn_cfg.mps, p_ccb->peer_conn_cfg.credits,
con_info.l2cap_result);
@@ -841,7 +830,7 @@
if (p_ccb->peer_conn_cfg.mtu < L2CAP_LE_MIN_MTU ||
p_ccb->peer_conn_cfg.mps < L2CAP_LE_MIN_MPS ||
p_ccb->peer_conn_cfg.mps > L2CAP_LE_MAX_MPS) {
- LOG_ERROR("L2CAP do not like the params");
+ log::error("L2CAP do not like the params");
con_info.l2cap_result = L2CAP_LE_RESULT_NO_RESOURCES;
l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP_NEG, &con_info);
break;
@@ -858,7 +847,7 @@
else
l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP_NEG, &con_info);
} else {
- LOG_VERBOSE("I DO NOT remember the connection req");
+ log::verbose("I DO NOT remember the connection req");
con_info.l2cap_result = L2CAP_LE_RESULT_INVALID_SOURCE_CID;
l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP_NEG, &con_info);
}
@@ -866,21 +855,20 @@
case L2CAP_CMD_BLE_FLOW_CTRL_CREDIT:
if (p + 4 > p_pkt_end) {
- LOG(ERROR) << "invalid read";
+ log::error("invalid read");
return;
}
STREAM_TO_UINT16(lcid, p);
p_ccb = l2cu_find_ccb_by_remote_cid(p_lcb, lcid);
if (p_ccb == NULL) {
- LOG_VERBOSE("%s Credit received for unknown channel id %d", __func__,
- lcid);
+ log::verbose("Credit received for unknown channel id {}", lcid);
break;
}
STREAM_TO_UINT16(credit, p);
l2c_csm_execute(p_ccb, L2CEVT_L2CAP_RECV_FLOW_CONTROL_CREDIT, &credit);
- LOG_VERBOSE("%s Credit received", __func__);
+ log::verbose("Credit received");
break;
case L2CAP_CMD_DISC_REQ:
@@ -903,7 +891,7 @@
case L2CAP_CMD_DISC_RSP:
if (p + 4 > p_pkt_end) {
- LOG(ERROR) << "invalid read";
+ log::error("invalid read");
return;
}
STREAM_TO_UINT16(rcid, p);
@@ -917,7 +905,7 @@
break;
default:
- LOG_WARN("L2CAP - LE - unknown cmd code: %d", cmd_code);
+ log::warn("L2CAP - LE - unknown cmd code: {}", cmd_code);
l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_NOT_UNDERSTOOD, id, 0, 0);
break;
}
@@ -1032,9 +1020,9 @@
l2cb.ble_round_robin_unacked = 0;
qq = qq_remainder = 0;
}
- LOG_VERBOSE(
- "l2c_ble_link_adjust_allocation num_hipri: %u num_lowpri: %u "
- "low_quota: %u round_robin_quota: %u qq: %u",
+ log::verbose(
+ "l2c_ble_link_adjust_allocation num_hipri: {} num_lowpri: {} "
+ "low_quota: {} round_robin_quota: {} qq: {}",
num_hipri_links, num_lowpri_links, low_quota, l2cb.ble_round_robin_quota,
qq);
@@ -1059,12 +1047,12 @@
}
}
- LOG_VERBOSE(
- "l2c_ble_link_adjust_allocation LCB %d Priority: %d XmitQuota: %d",
+ log::verbose(
+ "l2c_ble_link_adjust_allocation LCB {} Priority: {} XmitQuota: {}",
yy, p_lcb->acl_priority, p_lcb->link_xmit_quota);
- LOG_VERBOSE(" SentNotAcked: %d RRUnacked: %d",
- p_lcb->sent_not_acked, l2cb.round_robin_unacked);
+ log::verbose("SentNotAcked: {} RRUnacked: {}", p_lcb->sent_not_acked,
+ l2cb.round_robin_unacked);
/* There is a special case where we have readjusted the link quotas and */
/* this link may have sent anything but some other link sent packets so */
@@ -1093,7 +1081,7 @@
uint16_t tx_mtu = 0;
uint16_t i = 0;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
/* See if we have a link control block for the connection */
if (p_lcb == NULL) return;
@@ -1131,16 +1119,17 @@
uint16_t rx_data_len) {
tL2C_LCB* p_lcb = l2cu_find_lcb_by_handle(handle);
if (p_lcb == nullptr) {
- LOG_WARN("Received data length change event for unknown ACL handle:0x%04x",
- handle);
+ log::warn(
+ "Received data length change event for unknown ACL handle:0x{:04x}",
+ handle);
return;
}
if (is_legal_tx_data_len(tx_data_len)) {
if (p_lcb->tx_data_len != tx_data_len) {
- LOG_DEBUG(
- "Received data length change event for device:%s tx_data_len:%hu => "
- "%hu",
+ log::debug(
+ "Received data length change event for device:{} tx_data_len:{} => "
+ "{}",
ADDRESS_TO_LOGGABLE_CSTR(p_lcb->remote_bd_addr), p_lcb->tx_data_len,
tx_data_len);
BTM_LogHistory(kBtmLogTag, p_lcb->remote_bd_addr, "LE Data length change",
@@ -1148,15 +1137,15 @@
p_lcb->tx_data_len, tx_data_len));
p_lcb->tx_data_len = tx_data_len;
} else {
- LOG_DEBUG(
- "Received duplicated data length change event for device:%s "
- "tx_data_len:%hu",
+ log::debug(
+ "Received duplicated data length change event for device:{} "
+ "tx_data_len:{}",
ADDRESS_TO_LOGGABLE_CSTR(p_lcb->remote_bd_addr), tx_data_len);
}
} else {
- LOG_WARN(
- "Received illegal data length change event for device:%s "
- "tx_data_len:%hu",
+ log::warn(
+ "Received illegal data length change event for device:{} "
+ "tx_data_len:{}",
ADDRESS_TO_LOGGABLE_CSTR(p_lcb->remote_bd_addr), tx_data_len);
}
/* ignore rx_data len for now */
@@ -1176,7 +1165,7 @@
if (!p_ccb) return;
if (p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE) {
- LOG_WARN("LE link doesn't exist");
+ log::warn("LE link doesn't exist");
return;
}
@@ -1202,7 +1191,7 @@
if (!p_ccb) return;
if (p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE) {
- LOG_WARN("LE link doesn't exist");
+ log::warn("LE link doesn't exist");
return;
}
@@ -1224,7 +1213,7 @@
if (!p_ccb) return;
if (p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE) {
- LOG_WARN("LE link doesn't exist");
+ log::warn("LE link doesn't exist");
return;
}
@@ -1243,11 +1232,11 @@
*
******************************************************************************/
void l2cble_send_peer_disc_req(tL2C_CCB* p_ccb) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
if (!p_ccb) return;
if (p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE) {
- LOG_WARN("LE link doesn't exist");
+ log::warn("LE link doesn't exist");
return;
}
@@ -1273,8 +1262,8 @@
uint8_t sec_act;
if (!p_lcb) {
- LOG_WARN("%s: security complete for unknown device. bda=%s", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(*bda));
+ log::warn("security complete for unknown device. bda={}",
+ ADDRESS_TO_LOGGABLE_CSTR(*bda));
return;
}
@@ -1284,8 +1273,7 @@
if (!fixed_queue_is_empty(p_lcb->le_sec_pending_q)) {
p_buf = (tL2CAP_SEC_DATA*)fixed_queue_dequeue(p_lcb->le_sec_pending_q);
if (!p_buf) {
- LOG_WARN("%s Security complete for request not initiated from L2CAP",
- __func__);
+ log::warn("Security complete for request not initiated from L2CAP");
return;
}
@@ -1298,21 +1286,20 @@
(*(p_buf->p_callback))(bda, BT_TRANSPORT_LE, p_buf->p_ref_data,
status);
else {
- LOG_VERBOSE("%s MITM Protection Not present", __func__);
+ log::verbose("MITM Protection Not present");
(*(p_buf->p_callback))(bda, BT_TRANSPORT_LE, p_buf->p_ref_data,
BTM_FAILED_ON_SECURITY);
}
} else {
- LOG_VERBOSE("%s MITM Protection not required sec_act = %d", __func__,
- p_lcb->sec_act);
+ log::verbose("MITM Protection not required sec_act = {}",
+ p_lcb->sec_act);
(*(p_buf->p_callback))(bda, BT_TRANSPORT_LE, p_buf->p_ref_data, status);
}
osi_free(p_buf);
}
} else {
- LOG_WARN("%s Security complete for request not initiated from L2CAP",
- __func__);
+ log::warn("Security complete for request not initiated from L2CAP");
return;
}
@@ -1350,14 +1337,14 @@
tL2C_LCB* p_lcb = NULL;
if (!p_callback) {
- LOG_ERROR("No callback function");
+ log::error("No callback function");
return L2CAP_LE_RESULT_NO_RESOURCES;
}
p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_LE);
if (!p_lcb) {
- LOG_ERROR("Security check for unknown device");
+ log::error("Security check for unknown device");
p_callback(&bd_addr, BT_TRANSPORT_LE, p_ref_data, BTM_UNKNOWN_ADDR);
return L2CAP_LE_RESULT_NO_RESOURCES;
}
@@ -1365,7 +1352,7 @@
tL2CAP_SEC_DATA* p_buf =
(tL2CAP_SEC_DATA*)osi_malloc((uint16_t)sizeof(tL2CAP_SEC_DATA));
if (!p_buf) {
- LOG_ERROR("No resources for connection");
+ log::error("No resources for connection");
p_callback(&bd_addr, BT_TRANSPORT_LE, p_ref_data, BTM_NO_RESOURCES);
return L2CAP_LE_RESULT_NO_RESOURCES;
}
@@ -1392,7 +1379,7 @@
case BTM_INSUFFICIENT_ENCRYPT_KEY_SIZE:
return L2CAP_LE_RESULT_INSUFFICIENT_ENCRYP_KEY_SIZE;
default:
- LOG_ERROR("unexpected return value: %s", btm_status_text(result).c_str());
+ log::error("unexpected return value: {}", btm_status_text(result));
return L2CAP_LE_RESULT_INVALID_PARAMETERS;
}
}
@@ -1420,13 +1407,13 @@
// When there are bonded Hearing Aid devices, we will constrained this
// minimum interval.
phone_min_interval = BTM_BLE_CONN_INT_MIN_HEARINGAID;
- LOG_VERBOSE("%s: Have Hearing Aids. Min. interval is set to %d", __func__,
- phone_min_interval);
+ log::verbose("Have Hearing Aids. Min. interval is set to {}",
+ phone_min_interval);
}
if (*min_interval < phone_min_interval) {
- LOG_VERBOSE("%s: requested min_interval=%d too small. Set to %d", __func__,
- *min_interval, phone_min_interval);
+ log::verbose("requested min_interval={} too small. Set to {}",
+ *min_interval, phone_min_interval);
*min_interval = phone_min_interval;
}
@@ -1435,8 +1422,8 @@
// to remain established.
// In other words, this is a workaround for certain peripherals.
if (*max_interval < phone_min_interval) {
- LOG_VERBOSE("%s: requested max_interval=%d too small. Set to %d", __func__,
- *max_interval, phone_min_interval);
+ log::verbose("requested max_interval={} too small. Set to {}",
+ *max_interval, phone_min_interval);
*max_interval = phone_min_interval;
}
}
diff --git a/system/stack/l2cap/l2c_ble_conn_params.cc b/system/stack/l2cap/l2c_ble_conn_params.cc
index 47f9832..2db0deb 100644
--- a/system/stack/l2cap/l2c_ble_conn_params.cc
+++ b/system/stack/l2cap/l2c_ble_conn_params.cc
@@ -26,6 +26,7 @@
#define LOG_TAG "l2c_ble_conn_params"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <log/log.h>
#include "internal_include/stack_config.h"
@@ -38,6 +39,8 @@
#include "stack/l2cap/l2c_int.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
void l2cble_start_conn_update(tL2C_LCB* p_lcb);
static void l2cble_start_subrate_change(tL2C_LCB* p_lcb);
@@ -63,18 +66,19 @@
/* If we do not have one, create one and accept the connection. */
if (!p_lcb || !BTM_IsAclConnectionUp(rem_bda, BT_TRANSPORT_LE)) {
- LOG(WARNING) << __func__ << " - unknown BD_ADDR " << rem_bda;
+ log::warn("- unknown BD_ADDR {}", ADDRESS_TO_LOGGABLE_STR(rem_bda));
return (false);
}
if (p_lcb->transport != BT_TRANSPORT_LE) {
- LOG(WARNING) << __func__ << " - BD_ADDR " << rem_bda << " not LE";
+ log::warn("- BD_ADDR {} not LE", ADDRESS_TO_LOGGABLE_STR(rem_bda));
return (false);
}
- VLOG(2) << __func__ << ": BD_ADDR=" << ADDRESS_TO_LOGGABLE_STR(rem_bda)
- << ", min_int=" << min_int << ", max_int=" << max_int
- << ", min_ce_len=" << min_ce_len << ", max_ce_len=" << max_ce_len;
+ log::verbose(
+ "BD_ADDR={}, min_int={}, max_int={}, min_ce_len={}, max_ce_len={}",
+ ADDRESS_TO_LOGGABLE_STR(rem_bda), min_int, max_int, min_ce_len,
+ max_ce_len);
p_lcb->min_interval = min_int;
p_lcb->max_interval = max_int;
@@ -101,32 +105,32 @@
tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, BT_TRANSPORT_LE);
if (!p_lcb) {
- LOG_WARN("unknown address %s", ADDRESS_TO_LOGGABLE_CSTR(rem_bda));
+ log::warn("unknown address {}", ADDRESS_TO_LOGGABLE_CSTR(rem_bda));
return;
}
if (p_lcb->transport != BT_TRANSPORT_LE) {
- LOG_WARN("%s not LE, link role %d", ADDRESS_TO_LOGGABLE_CSTR(rem_bda),
- p_lcb->LinkRole());
+ log::warn("{} not LE, link role {}", ADDRESS_TO_LOGGABLE_CSTR(rem_bda),
+ p_lcb->LinkRole());
return;
}
if (lock == p_lcb->conn_update_blocked_by_service_discovery) {
- LOG_WARN("%s service discovery already locked/unlocked conn params: %d",
- ADDRESS_TO_LOGGABLE_CSTR(rem_bda), +lock);
+ log::warn("{} service discovery already locked/unlocked conn params: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(rem_bda), lock);
return;
}
p_lcb->conn_update_blocked_by_service_discovery = lock;
if (p_lcb->conn_update_blocked_by_profile_connection) {
- LOG_INFO("%s conn params stay locked because of audio setup",
- ADDRESS_TO_LOGGABLE_CSTR(rem_bda));
+ log::info("{} conn params stay locked because of audio setup",
+ ADDRESS_TO_LOGGABLE_CSTR(rem_bda));
return;
}
- LOG_INFO("%s Locking/unlocking conn params for service discovery: %d",
- ADDRESS_TO_LOGGABLE_CSTR(rem_bda), +lock);
+ log::info("{} Locking/unlocking conn params for service discovery: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(rem_bda), lock);
l2c_enable_update_ble_conn_params(p_lcb, !lock);
}
@@ -140,39 +144,39 @@
tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, BT_TRANSPORT_LE);
if (!p_lcb) {
- LOG_WARN("unknown address %s", ADDRESS_TO_LOGGABLE_CSTR(rem_bda));
+ log::warn("unknown address {}", ADDRESS_TO_LOGGABLE_CSTR(rem_bda));
return;
}
if (p_lcb->transport != BT_TRANSPORT_LE) {
- LOG_WARN("%s not LE, link role %d", ADDRESS_TO_LOGGABLE_CSTR(rem_bda),
- p_lcb->LinkRole());
+ log::warn("{} not LE, link role {}", ADDRESS_TO_LOGGABLE_CSTR(rem_bda),
+ p_lcb->LinkRole());
return;
}
if (lock == p_lcb->conn_update_blocked_by_profile_connection) {
- LOG_INFO("%s audio setup already locked/unlocked conn params: %d",
- ADDRESS_TO_LOGGABLE_CSTR(rem_bda), +lock);
+ log::info("{} audio setup already locked/unlocked conn params: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(rem_bda), lock);
return;
}
p_lcb->conn_update_blocked_by_profile_connection = lock;
if (p_lcb->conn_update_blocked_by_service_discovery) {
- LOG_INFO("%s conn params stay locked because of service discovery",
- ADDRESS_TO_LOGGABLE_CSTR(rem_bda));
+ log::info("{} conn params stay locked because of service discovery",
+ ADDRESS_TO_LOGGABLE_CSTR(rem_bda));
return;
}
- LOG_INFO("%s Locking/unlocking conn params for audio setup: %d",
- ADDRESS_TO_LOGGABLE_CSTR(rem_bda), +lock);
+ log::info("{} Locking/unlocking conn params for audio setup: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(rem_bda), lock);
l2c_enable_update_ble_conn_params(p_lcb, !lock);
}
static bool l2c_enable_update_ble_conn_params(tL2C_LCB* p_lcb, bool enable) {
- LOG_DEBUG("%s enable %d current upd state 0x%02x",
- ADDRESS_TO_LOGGABLE_CSTR(p_lcb->remote_bd_addr), enable,
- p_lcb->conn_update_mask);
+ log::debug("{} enable {} current upd state 0x{:02x}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_lcb->remote_bd_addr), enable,
+ p_lcb->conn_update_mask);
if (enable) {
p_lcb->conn_update_mask &= ~L2C_BLE_CONN_UPDATE_DISABLE;
@@ -202,7 +206,8 @@
void l2cble_start_conn_update(tL2C_LCB* p_lcb) {
uint16_t min_conn_int, max_conn_int, peripheral_latency, supervision_tout;
if (!BTM_IsAclConnectionUp(p_lcb->remote_bd_addr, BT_TRANSPORT_LE)) {
- LOG(ERROR) << "No known connection ACL for " << p_lcb->remote_bd_addr;
+ log::error("No known connection ACL for {}",
+ ADDRESS_TO_LOGGABLE_STR(p_lcb->remote_bd_addr));
return;
}
@@ -288,27 +293,27 @@
void l2cble_process_conn_update_evt(uint16_t handle, uint8_t status,
uint16_t interval, uint16_t latency,
uint16_t timeout) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
/* See if we have a link control block for the remote device */
tL2C_LCB* p_lcb = l2cu_find_lcb_by_handle(handle);
if (!p_lcb) {
- LOG_WARN("%s: Invalid handle: %d", __func__, handle);
+ log::warn("Invalid handle: {}", handle);
return;
}
p_lcb->conn_update_mask &= ~L2C_BLE_UPDATE_PENDING;
if (status != HCI_SUCCESS) {
- LOG_WARN("%s: Error status: %d", __func__, status);
+ log::warn("Error status: {}", status);
}
l2cble_start_conn_update(p_lcb);
l2cble_start_subrate_change(p_lcb);
- LOG_VERBOSE("%s: conn_update_mask=%d , subrate_req_mask=%d", __func__,
- p_lcb->conn_update_mask, p_lcb->subrate_req_mask);
+ log::verbose("conn_update_mask={} , subrate_req_mask={}",
+ p_lcb->conn_update_mask, p_lcb->subrate_req_mask);
}
/*******************************************************************************
@@ -336,14 +341,14 @@
btsnd_hcic_ble_rc_param_req_reply(handle, int_min, int_max, latency,
timeout, 0, 0);
} else {
- LOG_VERBOSE("L2CAP - LE - update currently disabled");
+ log::verbose("L2CAP - LE - update currently disabled");
p_lcb->conn_update_mask |= L2C_BLE_NEW_CONN_PARAM;
btsnd_hcic_ble_rc_param_req_neg_reply(handle,
HCI_ERR_UNACCEPT_CONN_INTERVAL);
}
} else {
- LOG_WARN("No link to update connection parameter");
+ log::warn("No link to update connection parameter");
}
}
@@ -365,10 +370,10 @@
(p_lcb->min_interval > p_dev_rec->conn_params.max_conn_int) ||
(p_lcb->latency > p_dev_rec->conn_params.peripheral_latency) ||
(p_lcb->timeout > p_dev_rec->conn_params.supervision_tout))) {
- LOG_VERBOSE(
- "%s: HANDLE=%d min_conn_int=%d max_conn_int=%d peripheral_latency=%d "
- "supervision_tout=%d",
- __func__, p_lcb->Handle(), p_dev_rec->conn_params.min_conn_int,
+ log::verbose(
+ "HANDLE={} min_conn_int={} max_conn_int={} peripheral_latency={} "
+ "supervision_tout={}",
+ p_lcb->Handle(), p_dev_rec->conn_params.min_conn_int,
p_dev_rec->conn_params.max_conn_int,
p_dev_rec->conn_params.peripheral_latency,
p_dev_rec->conn_params.supervision_tout);
@@ -400,23 +405,23 @@
******************************************************************************/
static void l2cble_start_subrate_change(tL2C_LCB* p_lcb) {
if (!BTM_IsAclConnectionUp(p_lcb->remote_bd_addr, BT_TRANSPORT_LE)) {
- LOG(ERROR) << "No known connection ACL for "
- << ADDRESS_TO_LOGGABLE_STR(p_lcb->remote_bd_addr);
+ log::error("No known connection ACL for {}",
+ ADDRESS_TO_LOGGABLE_STR(p_lcb->remote_bd_addr));
return;
}
btm_find_or_alloc_dev(p_lcb->remote_bd_addr);
- LOG_VERBOSE("%s: subrate_req_mask=%d conn_update_mask=%d", __func__,
- p_lcb->subrate_req_mask, p_lcb->conn_update_mask);
+ log::verbose("subrate_req_mask={} conn_update_mask={}",
+ p_lcb->subrate_req_mask, p_lcb->conn_update_mask);
if (p_lcb->subrate_req_mask & L2C_BLE_SUBRATE_REQ_PENDING) {
- LOG_VERBOSE("%s: returning L2C_BLE_SUBRATE_REQ_PENDING ", __func__);
+ log::verbose("returning L2C_BLE_SUBRATE_REQ_PENDING ");
return;
}
if (p_lcb->subrate_req_mask & L2C_BLE_SUBRATE_REQ_DISABLE) {
- LOG_VERBOSE("%s: returning L2C_BLE_SUBRATE_REQ_DISABLE ", __func__);
+ log::verbose("returning L2C_BLE_SUBRATE_REQ_DISABLE ");
return;
}
@@ -424,17 +429,16 @@
if (!(p_lcb->subrate_req_mask & L2C_BLE_NEW_SUBRATE_PARAM) ||
(p_lcb->conn_update_mask & L2C_BLE_UPDATE_PENDING) ||
(p_lcb->conn_update_mask & L2C_BLE_NEW_CONN_PARAM)) {
- LOG_VERBOSE("%s: returning L2C_BLE_NEW_SUBRATE_PARAM", __func__);
+ log::verbose("returning L2C_BLE_NEW_SUBRATE_PARAM");
return;
}
if (!controller_get_interface()->SupportsBleConnectionSubrating() ||
!acl_peer_supports_ble_connection_subrating(p_lcb->remote_bd_addr) ||
!acl_peer_supports_ble_connection_subrating_host(p_lcb->remote_bd_addr)) {
- LOG_VERBOSE(
- "%s: returning L2C_BLE_NEW_SUBRATE_PARAM local_host_sup=%d, "
- "local_conn_subrarte_sup=%d, peer_subrate_sup=%d, peer_host_sup=%d",
- __func__,
+ log::verbose(
+ "returning L2C_BLE_NEW_SUBRATE_PARAM local_host_sup={}, "
+ "local_conn_subrarte_sup={}, peer_subrate_sup={}, peer_host_sup={}",
controller_get_interface()->SupportsBleConnectionSubratingHost(),
controller_get_interface()->SupportsBleConnectionSubrating(),
acl_peer_supports_ble_connection_subrating(p_lcb->remote_bd_addr),
@@ -442,7 +446,7 @@
return;
}
- LOG_VERBOSE("%s: Sending HCI cmd for subrate req", __func__);
+ log::verbose("Sending HCI cmd for subrate req");
bluetooth::shim::ACL_LeSubrateRequest(
p_lcb->Handle(), p_lcb->subrate_min, p_lcb->subrate_max,
p_lcb->max_latency, p_lcb->cont_num, p_lcb->supervision_tout);
@@ -466,9 +470,9 @@
void L2CA_SetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max,
uint16_t max_latency, uint16_t cont_num,
uint16_t timeout) {
- VLOG(1) << __func__ << " subrate_min=" << subrate_min
- << ", subrate_max=" << subrate_max << ", max_latency=" << max_latency
- << ", cont_num=" << cont_num << ", timeout=" << timeout;
+ log::verbose(
+ "subrate_min={}, subrate_max={}, max_latency={}, cont_num={}, timeout={}",
+ subrate_min, subrate_max, max_latency, cont_num, timeout);
bluetooth::shim::ACL_LeSetDefaultSubrate(subrate_min, subrate_max,
max_latency, cont_num, timeout);
@@ -495,21 +499,20 @@
/* If we don't have one, create one and accept the connection. */
if (!p_lcb || !BTM_IsAclConnectionUp(rem_bda, BT_TRANSPORT_LE)) {
- LOG(WARNING) << __func__ << " - unknown BD_ADDR "
- << ADDRESS_TO_LOGGABLE_STR(rem_bda);
+ log::warn("unknown BD_ADDR {}", ADDRESS_TO_LOGGABLE_STR(rem_bda));
return (false);
}
if (p_lcb->transport != BT_TRANSPORT_LE) {
- LOG(WARNING) << __func__ << " - BD_ADDR "
- << ADDRESS_TO_LOGGABLE_STR(rem_bda) << " not LE";
+ log::warn("BD_ADDR {} not LE", ADDRESS_TO_LOGGABLE_STR(rem_bda));
return (false);
}
- VLOG(1) << __func__ << ": BD_ADDR=" << ADDRESS_TO_LOGGABLE_STR(rem_bda)
- << ", subrate_min=" << subrate_min << ", subrate_max=" << subrate_max
- << ", max_latency=" << max_latency << ", cont_num=" << cont_num
- << ", timeout=" << timeout;
+ log::verbose(
+ "BD_ADDR={}, subrate_min={}, subrate_max={}, max_latency={}, "
+ "cont_num={}, timeout={}",
+ ADDRESS_TO_LOGGABLE_STR(rem_bda), subrate_min, subrate_max, max_latency,
+ cont_num, timeout);
p_lcb->subrate_min = subrate_min;
p_lcb->subrate_max = subrate_max;
@@ -545,25 +548,25 @@
uint16_t subrate_factor,
uint16_t peripheral_latency,
uint16_t cont_num, uint16_t timeout) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
/* See if we have a link control block for the remote device */
tL2C_LCB* p_lcb = l2cu_find_lcb_by_handle(handle);
if (!p_lcb) {
- LOG_WARN("%s: Invalid handle: %d", __func__, handle);
+ log::warn("Invalid handle: {}", handle);
return;
}
p_lcb->subrate_req_mask &= ~L2C_BLE_SUBRATE_REQ_PENDING;
if (status != HCI_SUCCESS) {
- LOG_WARN("%s: Error status: %d", __func__, status);
+ log::warn("Error status: {}", status);
}
l2cble_start_conn_update(p_lcb);
l2cble_start_subrate_change(p_lcb);
- LOG_VERBOSE("%s: conn_update_mask=%d , subrate_req_mask=%d", __func__,
- p_lcb->conn_update_mask, p_lcb->subrate_req_mask);
+ log::verbose("conn_update_mask={} , subrate_req_mask={}",
+ p_lcb->conn_update_mask, p_lcb->subrate_req_mask);
}
diff --git a/system/stack/l2cap/l2c_csm.cc b/system/stack/l2cap/l2c_csm.cc
index b64571d..fbab24b 100644
--- a/system/stack/l2cap/l2c_csm.cc
+++ b/system/stack/l2cap/l2c_csm.cc
@@ -25,6 +25,7 @@
#include <base/functional/callback.h>
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <frameworks/proto_logging/stats/enums/bluetooth/enums.pb.h>
#include <string>
@@ -43,6 +44,8 @@
#include "stack/include/l2cdefs.h"
#include "stack/l2cap/l2c_int.h"
+using namespace bluetooth;
+
/******************************************************************************/
/* L O C A L F U N C T I O N P R O T O T Y P E S */
/******************************************************************************/
@@ -106,7 +109,7 @@
p_ccb->p_lcb->remote_bd_addr, p_ccb->local_cid, p_ccb->p_rcb->psm,
p_ccb->remote_id);
} else {
- LOG_WARN("pL2CA_ConnectInd_Cb is null");
+ log::warn("pL2CA_ConnectInd_Cb is null");
}
}
if (p_ccb->chnl_state == CST_OPEN && !p_ccb->p_lcb->is_transport_ble()) {
@@ -129,18 +132,18 @@
******************************************************************************/
void l2c_csm_execute(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data) {
if (p_ccb == nullptr) {
- LOG_WARN("CCB is null for event (%d)", event);
+ log::warn("CCB is null for event ({})", event);
return;
}
if (!l2cu_is_ccb_active(p_ccb)) {
- LOG_WARN("CCB not in use, event (%d) cannot be processed", event);
+ log::warn("CCB not in use, event ({}) cannot be processed", event);
return;
}
- LOG_VERBOSE("Entry chnl_state=%s [%d], event=%s [%d]",
- channel_state_text(p_ccb->chnl_state).c_str(), p_ccb->chnl_state,
- l2c_csm_get_event_name(event), event);
+ log::verbose("Entry chnl_state={} [{}], event={} [{}]",
+ channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state,
+ l2c_csm_get_event_name(event), event);
switch (p_ccb->chnl_state) {
case CST_CLOSED:
@@ -180,7 +183,7 @@
break;
default:
- LOG_ERROR("Unhandled state %d, event %d", p_ccb->chnl_state, event);
+ log::error("Unhandled state {}, event {}", p_ccb->chnl_state, event);
break;
}
}
@@ -202,20 +205,20 @@
tL2CA_DISCONNECT_IND_CB* disconnect_ind;
if (p_ccb->p_rcb == NULL) {
- LOG_ERROR("LCID: 0x%04x st: CLOSED evt: %s p_rcb == NULL",
- p_ccb->local_cid, l2c_csm_get_event_name(event));
+ log::error("LCID: 0x{:04x} st: CLOSED evt: {} p_rcb == NULL",
+ p_ccb->local_cid, l2c_csm_get_event_name(event));
return;
}
disconnect_ind = p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb;
- LOG_DEBUG("LCID: 0x%04x st: CLOSED evt: %s", p_ccb->local_cid,
- l2c_csm_get_event_name(event));
+ log::debug("LCID: 0x{:04x} st: CLOSED evt: {}", p_ccb->local_cid,
+ l2c_csm_get_event_name(event));
switch (event) {
case L2CEVT_LP_DISCONNECT_IND: /* Link was disconnected */
- LOG_DEBUG("Calling Disconnect_Ind_Cb(), CID: 0x%04x No Conf Needed",
- p_ccb->local_cid);
+ log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed",
+ p_ccb->local_cid);
l2cu_release_ccb(p_ccb);
(*disconnect_ind)(local_cid, false);
break;
@@ -255,7 +258,7 @@
true, &l2c_link_sec_comp, p_ccb);
} else {
if (!BTM_SetLinkPolicyActiveMode(p_ccb->p_lcb->remote_bd_addr)) {
- LOG_WARN("Unable to set link policy active");
+ log::warn("Unable to set link policy active");
}
/* If sec access does not result in started SEC_COM or COMP_NEG are
* already processed */
@@ -332,7 +335,7 @@
}
} else {
if (!BTM_SetLinkPolicyActiveMode(p_ccb->p_lcb->remote_bd_addr)) {
- LOG_WARN("Unable to set link policy active");
+ log::warn("Unable to set link policy active");
}
p_ccb->chnl_state = CST_TERM_W4_SEC_COMP;
auto status = btm_sec_l2cap_access_req(p_ccb->p_lcb->remote_bd_addr,
@@ -342,8 +345,8 @@
// started the security process, tell the peer to set a longer timer
l2cu_send_peer_connect_rsp(p_ccb, L2CAP_CONN_PENDING, 0);
} else {
- LOG_INFO("Check security for psm 0x%04x, status %d",
- p_ccb->p_rcb->psm, status);
+ log::info("Check security for psm 0x{:04x}, status {}",
+ p_ccb->p_rcb->psm, status);
}
}
break;
@@ -367,11 +370,11 @@
break;
default:
- LOG_ERROR("Handling unexpected event:%s", l2c_csm_get_event_name(event));
+ log::error("Handling unexpected event:{}", l2c_csm_get_event_name(event));
}
- LOG_VERBOSE("Exit chnl_state=%s [%d], event=%s [%d]",
- channel_state_text(p_ccb->chnl_state).c_str(), p_ccb->chnl_state,
- l2c_csm_get_event_name(event), event);
+ log::verbose("Exit chnl_state={} [{}], event={} [{}]",
+ channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state,
+ l2c_csm_get_event_name(event), event);
}
/*******************************************************************************
@@ -390,16 +393,16 @@
p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb;
uint16_t local_cid = p_ccb->local_cid;
- LOG_DEBUG("%s - LCID: 0x%04x st: ORIG_W4_SEC_COMP evt: %s",
- ((p_ccb->p_lcb) && (p_ccb->p_lcb->transport == BT_TRANSPORT_LE))
- ? "LE "
- : "",
- p_ccb->local_cid, l2c_csm_get_event_name(event));
+ log::debug("{} - LCID: 0x{:04x} st: ORIG_W4_SEC_COMP evt: {}",
+ ((p_ccb->p_lcb) && (p_ccb->p_lcb->transport == BT_TRANSPORT_LE))
+ ? "LE "
+ : "",
+ p_ccb->local_cid, l2c_csm_get_event_name(event));
switch (event) {
case L2CEVT_LP_DISCONNECT_IND: /* Link was disconnected */
- LOG_DEBUG("Calling Disconnect_Ind_Cb(), CID: 0x%04x No Conf Needed",
- p_ccb->local_cid);
+ log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed",
+ p_ccb->local_cid);
l2cu_release_ccb(p_ccb);
(*disconnect_ind)(local_cid, false);
break;
@@ -475,11 +478,11 @@
break;
default:
- LOG_ERROR("Handling unexpected event:%s", l2c_csm_get_event_name(event));
+ log::error("Handling unexpected event:{}", l2c_csm_get_event_name(event));
}
- LOG_VERBOSE("Exit chnl_state=%s [%d], event=%s [%d]",
- channel_state_text(p_ccb->chnl_state).c_str(), p_ccb->chnl_state,
- l2c_csm_get_event_name(event), event);
+ log::verbose("Exit chnl_state={} [{}], event={} [{}]",
+ channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state,
+ l2c_csm_get_event_name(event), event);
}
/*******************************************************************************
@@ -494,8 +497,8 @@
******************************************************************************/
static void l2c_csm_term_w4_sec_comp(tL2C_CCB* p_ccb, tL2CEVT event,
void* p_data) {
- LOG_DEBUG("LCID: 0x%04x st: TERM_W4_SEC_COMP evt: %s", p_ccb->local_cid,
- l2c_csm_get_event_name(event));
+ log::debug("LCID: 0x{:04x} st: TERM_W4_SEC_COMP evt: {}", p_ccb->local_cid,
+ l2c_csm_get_event_name(event));
switch (event) {
case L2CEVT_LP_DISCONNECT_IND: /* Link was disconnected */
@@ -511,20 +514,20 @@
/* Wait for the info resp in next state before sending connect ind (if
* needed) */
if (!p_ccb->p_lcb->w4_info_rsp) {
- LOG_DEBUG("Not waiting for info response, sending connect response");
+ log::debug("Not waiting for info response, sending connect response");
/* Don't need to get info from peer or already retrieved so continue */
alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CONNECT_TIMEOUT_MS,
l2c_ccb_timer_timeout, p_ccb);
if (p_ccb->p_lcb->transport != BT_TRANSPORT_LE) {
- LOG_DEBUG("Not LE connection, sending configure request");
+ log::debug("Not LE connection, sending configure request");
l2c_csm_send_connect_rsp(p_ccb);
l2c_csm_send_config_req(p_ccb);
} else {
if (p_ccb->ecoc) {
/* Handle Credit Based Connection */
- LOG_DEBUG("Calling CreditBasedConnect_Ind_Cb(), num of cids: %d",
- p_ccb->p_lcb->pending_ecoc_conn_cnt);
+ log::debug("Calling CreditBasedConnect_Ind_Cb(), num of cids: {}",
+ p_ccb->p_lcb->pending_ecoc_conn_cnt);
std::vector<uint16_t> pending_cids;
for (int i = 0; i < p_ccb->p_lcb->pending_ecoc_conn_cnt; i++) {
@@ -537,8 +540,8 @@
p_ccb->peer_conn_cfg.mtu, p_ccb->remote_id);
} else {
/* Handle BLE CoC */
- LOG_DEBUG("Calling Connect_Ind_Cb(), CID: 0x%04x",
- p_ccb->local_cid);
+ log::debug("Calling Connect_Ind_Cb(), CID: 0x{:04x}",
+ p_ccb->local_cid);
l2c_csm_send_connect_rsp(p_ccb);
l2c_csm_indicate_connection_open(p_ccb);
}
@@ -560,7 +563,7 @@
alarm_cancel(p_ccb->l2c_ccb_timer);
/* Waiting for the info resp, tell the peer to set a longer timer */
- LOG_DEBUG("Waiting for info response, sending connect pending");
+ log::debug("Waiting for info response, sending connect pending");
l2cu_send_peer_connect_rsp(p_ccb, L2CAP_CONN_PENDING, 0);
}
break;
@@ -615,11 +618,11 @@
break;
default:
- LOG_ERROR("Handling unexpected event:%s", l2c_csm_get_event_name(event));
+ log::error("Handling unexpected event:{}", l2c_csm_get_event_name(event));
}
- LOG_VERBOSE("Exit chnl_state=%s [%d], event=%s [%d]",
- channel_state_text(p_ccb->chnl_state).c_str(), p_ccb->chnl_state,
- l2c_csm_get_event_name(event), event);
+ log::verbose("Exit chnl_state={} [{}], event={} [{}]",
+ channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state,
+ l2c_csm_get_event_name(event), event);
}
/*******************************************************************************
@@ -642,8 +645,8 @@
uint16_t local_cid = p_ccb->local_cid;
tL2C_LCB* p_lcb = p_ccb->p_lcb;
- LOG_DEBUG("LCID: 0x%04x st: W4_L2CAP_CON_RSP evt: %s", p_ccb->local_cid,
- l2c_csm_get_event_name(event));
+ log::debug("LCID: 0x{:04x} st: W4_L2CAP_CON_RSP evt: {}", p_ccb->local_cid,
+ l2c_csm_get_event_name(event));
switch (event) {
case L2CEVT_LP_DISCONNECT_IND: /* Link was disconnected */
@@ -654,8 +657,8 @@
p_ccb->chnl_state = CST_CLOSED;
if ((p_ccb->flags & CCB_FLAG_NO_RETRY) || !p_data ||
(*((uint8_t*)p_data) != HCI_ERR_PEER_USER)) {
- LOG_DEBUG("Calling Disconnect_Ind_Cb(), CID: 0x%04x No Conf Needed",
- p_ccb->local_cid);
+ log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed",
+ p_ccb->local_cid);
l2cu_release_ccb(p_ccb);
(*disconnect_ind)(local_cid, false);
}
@@ -677,8 +680,8 @@
alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS,
l2c_ccb_timer_timeout, p_ccb);
}
- LOG_DEBUG("Calling Connect_Cfm_Cb(), CID: 0x%04x, Success",
- p_ccb->local_cid);
+ log::debug("Calling Connect_Cfm_Cb(), CID: 0x{:04x}, Success",
+ p_ccb->local_cid);
l2c_csm_send_config_req(p_ccb);
break;
@@ -693,20 +696,16 @@
case L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP:
alarm_cancel(p_ccb->l2c_ccb_timer);
p_ccb->chnl_state = CST_OPEN;
- LOG_DEBUG(
- "Calling credit_based_connect_cfm(),"
- "cid %d, result 0x%04x",
- p_ccb->local_cid, L2CAP_CONN_OK);
+ log::debug("Calling credit_based_connect_cfm(),cid {}, result 0x{:04x}",
+ p_ccb->local_cid, L2CAP_CONN_OK);
(*credit_based_connect_cfm)(p_lcb->remote_bd_addr, p_ccb->local_cid,
p_ci->peer_mtu, L2CAP_CONN_OK);
break;
case L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP_NEG:
- LOG_DEBUG(
- "Calling pL2CA_Error_Cb(),"
- "cid %d, result 0x%04x",
- local_cid, p_ci->l2cap_result);
+ log::debug("Calling pL2CA_Error_Cb(),cid {}, result 0x{:04x}", local_cid,
+ p_ci->l2cap_result);
(*p_ccb->p_rcb->api.pL2CA_Error_Cb)(local_cid, p_ci->l2cap_result);
bluetooth::shim::CountCounterMetrics(
android::bluetooth::CodePathCounterKeyEnum::
@@ -717,9 +716,8 @@
break;
case L2CEVT_L2CAP_CONNECT_RSP_NEG: /* Peer rejected connection */
- LOG(WARNING) << __func__ << ": L2CAP connection rejected, lcid="
- << loghex(p_ccb->local_cid)
- << ", reason=" << loghex(p_ci->l2cap_result);
+ log::warn("L2CAP connection rejected, lcid={}, reason={}",
+ loghex(p_ccb->local_cid), loghex(p_ci->l2cap_result));
l2cu_release_ccb(p_ccb);
if (p_lcb->transport == BT_TRANSPORT_LE) {
(*p_ccb->p_rcb->api.pL2CA_Error_Cb)(
@@ -732,13 +730,13 @@
break;
case L2CEVT_TIMEOUT:
- LOG(WARNING) << __func__ << ": L2CAP connection timeout";
+ log::warn("L2CAP connection timeout");
if (p_ccb->ecoc) {
for (int i = 0; i < p_lcb->pending_ecoc_conn_cnt; i++) {
uint16_t cid = p_lcb->pending_ecoc_connection_cids[i];
tL2C_CCB* temp_p_ccb = l2cu_find_ccb_by_cid(p_lcb, cid);
- LOG(WARNING) << __func__ << ": lcid= " << loghex(cid);
+ log::warn("lcid= {}", loghex(cid));
(*p_ccb->p_rcb->api.pL2CA_Error_Cb)(p_ccb->local_cid,
L2CAP_CONN_TIMEOUT);
bluetooth::shim::CountCounterMetrics(
@@ -752,7 +750,7 @@
L2CAP_CREDIT_BASED_MAX_CIDS);
} else {
- LOG(WARNING) << __func__ << ": lcid= " << loghex(p_ccb->local_cid);
+ log::warn("lcid= {}", loghex(p_ccb->local_cid));
l2cu_release_ccb(p_ccb);
(*p_ccb->p_rcb->api.pL2CA_Error_Cb)(local_cid, L2CAP_CONN_OTHER_ERROR);
bluetooth::shim::CountCounterMetrics(
@@ -803,11 +801,11 @@
break;
default:
- LOG_ERROR("Handling unexpected event:%s", l2c_csm_get_event_name(event));
+ log::error("Handling unexpected event:{}", l2c_csm_get_event_name(event));
}
- LOG_VERBOSE("Exit chnl_state=%s [%d], event=%s [%d]",
- channel_state_text(p_ccb->chnl_state).c_str(), p_ccb->chnl_state,
- l2c_csm_get_event_name(event), event);
+ log::verbose("Exit chnl_state={} [{}], event={} [{}]",
+ channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state,
+ l2c_csm_get_event_name(event), event);
}
/*******************************************************************************
@@ -828,13 +826,13 @@
p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb;
uint16_t local_cid = p_ccb->local_cid;
- LOG_DEBUG("LCID: 0x%04x st: W4_L2CA_CON_RSP evt: %s", p_ccb->local_cid,
- l2c_csm_get_event_name(event));
+ log::debug("LCID: 0x{:04x} st: W4_L2CA_CON_RSP evt: {}", p_ccb->local_cid,
+ l2c_csm_get_event_name(event));
switch (event) {
case L2CEVT_LP_DISCONNECT_IND: /* Link was disconnected */
- LOG_DEBUG("Calling Disconnect_Ind_Cb(), CID: 0x%04x No Conf Needed",
- p_ccb->local_cid);
+ log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed",
+ p_ccb->local_cid);
l2cu_release_ccb(p_ccb);
(*disconnect_ind)(local_cid, false);
break;
@@ -842,7 +840,7 @@
case L2CEVT_L2CA_CREDIT_BASED_CONNECT_RSP:
p_ci = (tL2C_CONN_INFO*)p_data;
if ((p_lcb == nullptr) || (p_lcb && p_lcb->transport != BT_TRANSPORT_LE)) {
- LOG_WARN("LE link doesn't exist");
+ log::warn("LE link doesn't exist");
return;
}
l2cu_send_peer_credit_based_conn_res(p_ccb, p_ci->lcids,
@@ -852,8 +850,8 @@
for (int i = 0; i < p_lcb->pending_ecoc_conn_cnt; i++) {
uint16_t cid = p_lcb->pending_ecoc_connection_cids[i];
if (cid == 0) {
- LOG_WARN("pending_ecoc_connection_cids[%d] is %d", i, cid);
- continue;
+ log::warn("pending_ecoc_connection_cids[{}] is {}", i, cid);
+ continue;
}
tL2C_CCB* temp_p_ccb = l2cu_find_ccb_by_cid(p_lcb, cid);
@@ -866,7 +864,9 @@
}
}
else {
- LOG_WARN("temp_p_ccb is NULL, pending_ecoc_connection_cids[%d] is %d", i, cid);
+ log::warn(
+ "temp_p_ccb is NULL, pending_ecoc_connection_cids[{}] is {}", i,
+ cid);
}
}
p_lcb->pending_ecoc_conn_cnt = 0;
@@ -889,15 +889,15 @@
} else {
/* Result should be OK or PENDING */
if ((!p_ci) || (p_ci->l2cap_result == L2CAP_CONN_OK)) {
- LOG_DEBUG("Sending connection ok for BR_EDR");
+ log::debug("Sending connection ok for BR_EDR");
l2cu_send_peer_connect_rsp(p_ccb, L2CAP_CONN_OK, 0);
p_ccb->chnl_state = CST_CONFIG;
alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS,
l2c_ccb_timer_timeout, p_ccb);
} else {
/* If pending, stay in same state and start extended timer */
- LOG_DEBUG("Sending connection result %d and status %d",
- p_ci->l2cap_result, p_ci->l2cap_status);
+ log::debug("Sending connection result {} and status {}",
+ p_ci->l2cap_result, p_ci->l2cap_status);
l2cu_send_peer_connect_rsp(p_ccb, p_ci->l2cap_result,
p_ci->l2cap_status);
alarm_set_on_mloop(p_ccb->l2c_ccb_timer,
@@ -938,8 +938,8 @@
case L2CEVT_TIMEOUT:
l2cu_send_peer_connect_rsp(p_ccb, L2CAP_CONN_NO_PSM, 0);
- LOG_DEBUG("Calling Disconnect_Ind_Cb(), CID: 0x%04x No Conf Needed",
- p_ccb->local_cid);
+ log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed",
+ p_ccb->local_cid);
l2cu_release_ccb(p_ccb);
(*disconnect_ind)(local_cid, false);
break;
@@ -960,17 +960,17 @@
/* We have feature info, so now give the upper layer connect IND */
alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CONNECT_TIMEOUT_MS,
l2c_ccb_timer_timeout, p_ccb);
- LOG_DEBUG("Calling Connect_Ind_Cb(), CID: 0x%04x", p_ccb->local_cid);
+ log::debug("Calling Connect_Ind_Cb(), CID: 0x{:04x}", p_ccb->local_cid);
l2c_csm_send_connect_rsp(p_ccb);
l2c_csm_send_config_req(p_ccb);
break;
default:
- LOG_ERROR("Handling unexpected event:%s", l2c_csm_get_event_name(event));
+ log::error("Handling unexpected event:{}", l2c_csm_get_event_name(event));
}
- LOG_VERBOSE("Exit chnl_state=%s [%d], event=%s [%d]",
- channel_state_text(p_ccb->chnl_state).c_str(), p_ccb->chnl_state,
- l2c_csm_get_event_name(event), event);
+ log::verbose("Exit chnl_state={} [{}], event={} [{}]",
+ channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state,
+ l2c_csm_get_event_name(event), event);
}
/*******************************************************************************
@@ -993,13 +993,13 @@
tL2C_CCB* temp_p_ccb;
tL2CAP_LE_CFG_INFO* p_le_cfg = (tL2CAP_LE_CFG_INFO*)p_data;
- LOG_DEBUG("LCID: 0x%04x st: CONFIG evt: %s", p_ccb->local_cid,
- l2c_csm_get_event_name(event));
+ log::debug("LCID: 0x{:04x} st: CONFIG evt: {}", p_ccb->local_cid,
+ l2c_csm_get_event_name(event));
switch (event) {
case L2CEVT_LP_DISCONNECT_IND: /* Link was disconnected */
- LOG_DEBUG("Calling Disconnect_Ind_Cb(), CID: 0x%04x No Conf Needed",
- p_ccb->local_cid);
+ log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed",
+ p_ccb->local_cid);
l2cu_release_ccb(p_ccb);
(*disconnect_ind)(local_cid, false);
break;
@@ -1008,8 +1008,8 @@
/* For ecoc reconfig is handled below in l2c_ble. In case of success
* let us notify upper layer about the reconfig
*/
- LOG_DEBUG("Calling LeReconfigCompleted_Cb(), CID: 0x%04x",
- p_ccb->local_cid);
+ log::debug("Calling LeReconfigCompleted_Cb(), CID: 0x{:04x}",
+ p_ccb->local_cid);
(*p_ccb->p_rcb->api.pL2CA_CreditBasedReconfigCompleted_Cb)(
p_lcb->remote_bd_addr, p_ccb->local_cid, false, p_le_cfg);
@@ -1017,8 +1017,9 @@
case L2CEVT_L2CAP_CONFIG_REQ: /* Peer config request */
cfg_result = l2cu_process_peer_cfg_req(p_ccb, p_cfg);
if (cfg_result == L2CAP_PEER_CFG_OK) {
- LOG_DEBUG("Calling Config_Req_Cb(), CID: 0x%04x, C-bit %d",
- p_ccb->local_cid, (p_cfg->flags & L2CAP_CFG_FLAGS_MASK_CONT));
+ log::debug("Calling Config_Req_Cb(), CID: 0x{:04x}, C-bit {}",
+ p_ccb->local_cid,
+ (p_cfg->flags & L2CAP_CFG_FLAGS_MASK_CONT));
l2c_csm_send_config_rsp_ok(p_ccb,
p_cfg->flags & L2CAP_CFG_FLAGS_MASK_CONT);
if (p_ccb->config_done & OB_CFG_DONE) {
@@ -1037,11 +1038,11 @@
}
} else if (cfg_result == L2CAP_PEER_CFG_DISCONNECT) {
/* Disconnect if channels are incompatible */
- LOG_DEBUG("incompatible configurations disconnect");
+ log::debug("incompatible configurations disconnect");
l2cu_disconnect_chnl(p_ccb);
} else /* Return error to peer so it can renegotiate if possible */
{
- LOG_DEBUG("incompatible configurations trying reconfig");
+ log::debug("incompatible configurations trying reconfig");
l2cu_send_peer_config_rsp(p_ccb, p_cfg);
}
break;
@@ -1052,7 +1053,7 @@
p_ccb->chnl_state = CST_OPEN;
alarm_cancel(p_ccb->l2c_ccb_timer);
- LOG_DEBUG("Calling Config_Rsp_Cb(), CID: 0x%04x", p_ccb->local_cid);
+ log::debug("Calling Config_Rsp_Cb(), CID: 0x{:04x}", p_ccb->local_cid);
p_ccb->p_rcb->api.pL2CA_CreditBasedReconfigCompleted_Cb(
p_lcb->remote_bd_addr, p_ccb->local_cid, true, p_le_cfg);
@@ -1073,9 +1074,9 @@
/* Verify two sides are in compatible modes before continuing */
if (p_ccb->our_cfg.fcr.mode != p_ccb->peer_cfg.fcr.mode) {
l2cu_send_peer_disc_req(p_ccb);
- LOG_WARN(
- "Calling Disconnect_Ind_Cb(Incompatible CFG), CID: "
- "0x%04x No Conf Needed",
+ log::warn(
+ "Calling Disconnect_Ind_Cb(Incompatible CFG), CID: 0x{:04x} No "
+ "Conf Needed",
p_ccb->local_cid);
l2cu_release_ccb(p_ccb);
(*disconnect_ind)(local_cid, false);
@@ -1116,7 +1117,7 @@
p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE);
}
- LOG_DEBUG("Calling Config_Rsp_Cb(), CID: 0x%04x", p_ccb->local_cid);
+ log::debug("Calling Config_Rsp_Cb(), CID: 0x{:04x}", p_ccb->local_cid);
p_ccb->remote_config_rsp_result = p_cfg->result;
if (p_ccb->config_done & IB_CFG_DONE) {
l2c_csm_indicate_connection_open(p_ccb);
@@ -1129,8 +1130,8 @@
/* If failure was channel mode try to renegotiate */
if (!l2c_fcr_renegotiate_chan(p_ccb, p_cfg)) {
- LOG_DEBUG("Calling Config_Rsp_Cb(), CID: 0x%04x, Failure: %d",
- p_ccb->local_cid, p_cfg->result);
+ log::debug("Calling Config_Rsp_Cb(), CID: 0x{:04x}, Failure: {}",
+ p_ccb->local_cid, p_cfg->result);
if (p_ccb->connection_initiator == L2CAP_INITIATOR_LOCAL) {
(*p_ccb->p_rcb->api.pL2CA_Error_Cb)(p_ccb->local_cid,
L2CAP_CFG_FAILED_NO_REASON);
@@ -1145,8 +1146,8 @@
alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_DISCONNECT_TIMEOUT_MS,
l2c_ccb_timer_timeout, p_ccb);
p_ccb->chnl_state = CST_W4_L2CA_DISCONNECT_RSP;
- LOG_DEBUG("Calling Disconnect_Ind_Cb(), CID: 0x%04x Conf Needed",
- p_ccb->local_cid);
+ log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} Conf Needed",
+ p_ccb->local_cid);
(*p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb)(p_ccb->local_cid, true);
l2c_csm_send_disconnect_rsp(p_ccb);
break;
@@ -1172,9 +1173,9 @@
/* Verify two sides are in compatible modes before continuing */
if (p_ccb->our_cfg.fcr.mode != p_ccb->peer_cfg.fcr.mode) {
l2cu_send_peer_disc_req(p_ccb);
- LOG_WARN(
- "Calling Disconnect_Ind_Cb(Incompatible CFG), CID: "
- "0x%04x No Conf Needed",
+ log::warn(
+ "Calling Disconnect_Ind_Cb(Incompatible CFG), CID: 0x{:04x} No "
+ "Conf Needed",
p_ccb->local_cid);
l2cu_release_ccb(p_ccb);
(*disconnect_ind)(local_cid, false);
@@ -1215,7 +1216,7 @@
break;
case L2CEVT_L2CAP_DATA: /* Peer data packet rcvd */
- LOG_DEBUG("Calling DataInd_Cb(), CID: 0x%04x", p_ccb->local_cid);
+ log::debug("Calling DataInd_Cb(), CID: 0x{:04x}", p_ccb->local_cid);
if (p_ccb->local_cid >= L2CAP_FIRST_FIXED_CHNL &&
p_ccb->local_cid <= L2CAP_LAST_FIXED_CHNL) {
if (p_ccb->local_cid < L2CAP_BASE_APPL_CID) {
@@ -1261,17 +1262,17 @@
}
l2cu_send_peer_disc_req(p_ccb);
- LOG_DEBUG("Calling Disconnect_Ind_Cb(), CID: 0x%04x No Conf Needed",
- p_ccb->local_cid);
+ log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed",
+ p_ccb->local_cid);
l2cu_release_ccb(p_ccb);
(*disconnect_ind)(local_cid, false);
break;
default:
- LOG_ERROR("Handling unexpected event:%s", l2c_csm_get_event_name(event));
+ log::error("Handling unexpected event:{}", l2c_csm_get_event_name(event));
}
- LOG_VERBOSE("Exit chnl_state=%s [%d], event=%s [%d]",
- channel_state_text(p_ccb->chnl_state).c_str(), p_ccb->chnl_state,
- l2c_csm_get_event_name(event), event);
+ log::verbose("Exit chnl_state={} [{}], event={} [{}]",
+ channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state,
+ l2c_csm_get_event_name(event), event);
}
/*******************************************************************************
@@ -1293,13 +1294,13 @@
uint16_t credit = 0;
tL2CAP_LE_CFG_INFO* p_le_cfg = (tL2CAP_LE_CFG_INFO*)p_data;
- LOG_VERBOSE("LCID: 0x%04x st: OPEN evt: %s", p_ccb->local_cid,
- l2c_csm_get_event_name(event));
+ log::verbose("LCID: 0x{:04x} st: OPEN evt: {}", p_ccb->local_cid,
+ l2c_csm_get_event_name(event));
switch (event) {
case L2CEVT_LP_DISCONNECT_IND: /* Link was disconnected */
- LOG_DEBUG("Calling Disconnect_Ind_Cb(), CID: 0x%04x No Conf Needed",
- p_ccb->local_cid);
+ log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed",
+ p_ccb->local_cid);
power_telemetry::GetInstance().LogChannelDisconnected(
p_ccb->p_rcb->psm, p_ccb->local_cid, p_ccb->remote_id,
p_ccb->p_lcb->remote_bd_addr);
@@ -1313,8 +1314,8 @@
* let us notify upper layer about the reconfig
*/
if (p_le_cfg) {
- LOG_DEBUG("Calling LeReconfigCompleted_Cb(), CID: 0x%04x",
- p_ccb->local_cid);
+ log::debug("Calling LeReconfigCompleted_Cb(), CID: 0x{:04x}",
+ p_ccb->local_cid);
(*p_ccb->p_rcb->api.pL2CA_CreditBasedReconfigCompleted_Cb)(
p_ccb->p_lcb->remote_bd_addr, p_ccb->local_cid, false, p_le_cfg);
}
@@ -1362,15 +1363,15 @@
case L2CEVT_L2CAP_DISCONNECT_REQ: /* Peer disconnected request */
if (p_ccb->p_lcb->transport != BT_TRANSPORT_LE) {
if (!BTM_SetLinkPolicyActiveMode(p_ccb->p_lcb->remote_bd_addr)) {
- LOG_WARN("Unable to set link policy active");
+ log::warn("Unable to set link policy active");
}
}
p_ccb->chnl_state = CST_W4_L2CA_DISCONNECT_RSP;
alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_DISCONNECT_TIMEOUT_MS,
l2c_ccb_timer_timeout, p_ccb);
- LOG_DEBUG("Calling Disconnect_Ind_Cb(), CID: 0x%04x Conf Needed",
- p_ccb->local_cid);
+ log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} Conf Needed",
+ p_ccb->local_cid);
power_telemetry::GetInstance().LogChannelDisconnected(
p_ccb->p_rcb->psm, p_ccb->local_cid, p_ccb->remote_id,
p_ccb->p_lcb->remote_bd_addr);
@@ -1397,7 +1398,7 @@
if (p_ccb->p_lcb->transport != BT_TRANSPORT_LE) {
/* Make sure we are not in sniff mode */
if (!BTM_SetLinkPolicyActiveMode(p_ccb->p_lcb->remote_bd_addr)) {
- LOG_WARN("Unable to set link policy active");
+ log::warn("Unable to set link policy active");
}
}
power_telemetry::GetInstance().LogChannelDisconnected(
@@ -1437,7 +1438,7 @@
break;
case L2CEVT_L2CA_CONFIG_REQ: /* Upper layer config req */
- LOG_ERROR(
+ log::error(
"Dropping L2CAP re-config request because there is no usage and "
"should not be invoked");
break;
@@ -1455,7 +1456,7 @@
case L2CEVT_L2CA_SEND_FLOW_CONTROL_CREDIT:
if (p_data) {
- LOG_DEBUG("Sending credit");
+ log::debug("Sending credit");
credit = *(uint16_t*)p_data;
l2cble_send_flow_control_credit(p_ccb, credit);
}
@@ -1464,7 +1465,7 @@
case L2CEVT_L2CAP_RECV_FLOW_CONTROL_CREDIT:
if (p_data) {
credit = *(uint16_t*)p_data;
- LOG_DEBUG("Credits received %d", credit);
+ log::debug("Credits received {}", credit);
if ((p_ccb->peer_conn_cfg.credits + credit) > L2CAP_LE_CREDIT_MAX) {
/* we have received credits more than max coc credits,
* so disconnecting the Le Coc Channel
@@ -1477,11 +1478,11 @@
}
break;
default:
- LOG_ERROR("Handling unexpected event:%s", l2c_csm_get_event_name(event));
+ log::error("Handling unexpected event:{}", l2c_csm_get_event_name(event));
}
- LOG_VERBOSE("Exit chnl_state=%s [%d], event=%s [%d]",
- channel_state_text(p_ccb->chnl_state).c_str(), p_ccb->chnl_state,
- l2c_csm_get_event_name(event), event);
+ log::verbose("Exit chnl_state={} [{}], event={} [{}]",
+ channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state,
+ l2c_csm_get_event_name(event), event);
}
/*******************************************************************************
@@ -1500,8 +1501,8 @@
p_ccb->p_rcb->api.pL2CA_DisconnectCfm_Cb;
uint16_t local_cid = p_ccb->local_cid;
- LOG_DEBUG("LCID: 0x%04x st: W4_L2CAP_DISC_RSP evt: %s", p_ccb->local_cid,
- l2c_csm_get_event_name(event));
+ log::debug("LCID: 0x{:04x} st: W4_L2CAP_DISC_RSP evt: {}", p_ccb->local_cid,
+ l2c_csm_get_event_name(event));
switch (event) {
case L2CEVT_L2CAP_DISCONNECT_RSP: /* Peer disconnect response */
@@ -1534,11 +1535,11 @@
osi_free(p_data);
break;
default:
- LOG_ERROR("Handling unexpected event:%s", l2c_csm_get_event_name(event));
+ log::error("Handling unexpected event:{}", l2c_csm_get_event_name(event));
}
- LOG_VERBOSE("Exit chnl_state=%s [%d], event=%s [%d]",
- channel_state_text(p_ccb->chnl_state).c_str(), p_ccb->chnl_state,
- l2c_csm_get_event_name(event), event);
+ log::verbose("Exit chnl_state={} [{}], event={} [{}]",
+ channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state,
+ l2c_csm_get_event_name(event), event);
}
/*******************************************************************************
@@ -1557,13 +1558,13 @@
p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb;
uint16_t local_cid = p_ccb->local_cid;
- LOG_DEBUG("LCID: 0x%04x st: W4_L2CA_DISC_RSP evt: %s", p_ccb->local_cid,
- l2c_csm_get_event_name(event));
+ log::debug("LCID: 0x{:04x} st: W4_L2CA_DISC_RSP evt: {}", p_ccb->local_cid,
+ l2c_csm_get_event_name(event));
switch (event) {
case L2CEVT_LP_DISCONNECT_IND: /* Link was disconnected */
- LOG_DEBUG("Calling Disconnect_Ind_Cb(), CID: 0x%04x No Conf Needed",
- p_ccb->local_cid);
+ log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed",
+ p_ccb->local_cid);
l2cu_release_ccb(p_ccb);
(*disconnect_ind)(local_cid, false);
break;
@@ -1571,8 +1572,8 @@
case L2CEVT_TIMEOUT:
l2cu_send_peer_disc_rsp(p_ccb->p_lcb, p_ccb->remote_id, p_ccb->local_cid,
p_ccb->remote_cid);
- LOG_DEBUG("Calling Disconnect_Ind_Cb(), CID: 0x%04x No Conf Needed",
- p_ccb->local_cid);
+ log::debug("Calling Disconnect_Ind_Cb(), CID: 0x{:04x} No Conf Needed",
+ p_ccb->local_cid);
l2cu_release_ccb(p_ccb);
(*disconnect_ind)(local_cid, false);
break;
@@ -1589,11 +1590,11 @@
osi_free(p_data);
break;
default:
- LOG_ERROR("Handling unexpected event:%s", l2c_csm_get_event_name(event));
+ log::error("Handling unexpected event:{}", l2c_csm_get_event_name(event));
}
- LOG_VERBOSE("Exit chnl_state=%s [%d], event=%s [%d]",
- channel_state_text(p_ccb->chnl_state).c_str(), p_ccb->chnl_state,
- l2c_csm_get_event_name(event), event);
+ log::verbose("Exit chnl_state={} [{}], event={} [{}]",
+ channel_state_text(p_ccb->chnl_state), p_ccb->chnl_state,
+ l2c_csm_get_event_name(event), event);
}
/*******************************************************************************
@@ -1744,10 +1745,10 @@
}
if (p_ccb->xmit_hold_q == NULL) {
- LOG_ERROR(
- "empty queue: p_ccb = %p p_ccb->in_use = %d p_ccb->chnl_state = %d "
- "p_ccb->local_cid = %u p_ccb->remote_cid = %u",
- p_ccb, p_ccb->in_use, p_ccb->chnl_state, p_ccb->local_cid,
+ log::error(
+ "empty queue: p_ccb = {} p_ccb->in_use = {} p_ccb->chnl_state = {} "
+ "p_ccb->local_cid = {} p_ccb->remote_cid = {}",
+ fmt::ptr(p_ccb), p_ccb->in_use, p_ccb->chnl_state, p_ccb->local_cid,
p_ccb->remote_cid);
} else {
fixed_queue_enqueue(p_ccb->xmit_hold_q, p_buf);
diff --git a/system/stack/l2cap/l2c_fcr.cc b/system/stack/l2cap/l2c_fcr.cc
index 6d8e95d..be66785 100644
--- a/system/stack/l2cap/l2c_fcr.cc
+++ b/system/stack/l2cap/l2c_fcr.cc
@@ -24,6 +24,7 @@
******************************************************************************/
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -42,6 +43,8 @@
*/
#define L2C_FCR_RETX_ALL_PKTS 0xFF
+using namespace bluetooth;
+
/* this is the minimal offset required by OBX to process incoming packets */
static const uint16_t OBX_BUF_MIN_OFFSET = 4;
@@ -349,18 +352,18 @@
p_buf->len += L2CAP_FCS_LEN;
if (is_retransmission) {
- LOG_VERBOSE(
- "L2CAP eRTM ReTx I-frame CID: 0x%04x Len: %u SAR: %s TxSeq: %u "
- "ReqSeq: %u F: %u",
+ log::verbose(
+ "L2CAP eRTM ReTx I-frame CID: 0x{:04x} Len: {} SAR: {} TxSeq: {} "
+ "ReqSeq: {} F: {}",
p_ccb->local_cid, p_buf->len,
SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
(ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
(ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
(ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
} else {
- LOG_VERBOSE(
- "L2CAP eRTM Tx I-frame CID: 0x%04x Len: %u SAR: %-12s TxSeq: %u "
- "ReqSeq: %u F: %u",
+ log::verbose(
+ "L2CAP eRTM Tx I-frame CID: 0x{:04x} Len: {} SAR: {:<12s} TxSeq: {} "
+ " ReqSeq: {} F: {}",
p_ccb->local_cid, p_buf->len,
SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
(ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
@@ -427,25 +430,25 @@
if ((((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 1) ||
(((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 3)) {
- LOG_WARN(
- "L2CAP eRTM Tx S-frame CID: 0x%04x ctrlword: 0x%04x Type: %s "
- "ReqSeq: %u P: %u F: %u",
+ log::warn(
+ "L2CAP eRTM Tx S-frame CID: 0x{:04x} ctrlword: 0x{:04x} Type: {} "
+ "ReqSeq: {} P: {} F: {}",
p_ccb->local_cid, ctrl_word,
SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
(ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
(ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
(ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
- LOG_WARN(" Buf Len: %u", p_buf->len);
+ log::warn("Buf Len: {}", p_buf->len);
} else {
- LOG_VERBOSE(
- "L2CAP eRTM Tx S-frame CID: 0x%04x ctrlword: 0x%04x Type: %s "
- "ReqSeq: %u P: %u F: %u",
+ log::verbose(
+ "L2CAP eRTM Tx S-frame CID: 0x{:04x} ctrlword: 0x{:04x} Type: {} "
+ "ReqSeq: {} P: {} F: {}",
p_ccb->local_cid, ctrl_word,
SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
(ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
(ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
(ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
- LOG_VERBOSE(" Buf Len: %u", p_buf->len);
+ log::verbose("Buf Len: {}", p_buf->len);
}
l2c_link_check_send_pkts(p_ccb->p_lcb, 0, p_buf);
@@ -478,8 +481,8 @@
min_pdu_len = (uint16_t)(L2CAP_FCS_LEN + L2CAP_FCR_OVERHEAD);
if (p_buf->len < min_pdu_len) {
- LOG_WARN("Rx L2CAP PDU: CID: 0x%04x Len too short: %u", p_ccb->local_cid,
- p_buf->len);
+ log::warn("Rx L2CAP PDU: CID: 0x{:04x} Len too short: {}",
+ p_ccb->local_cid, p_buf->len);
osi_free(p_buf);
return;
}
@@ -492,18 +495,18 @@
if ((((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 1) ||
(((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 3)) {
/* REJ or SREJ */
- LOG_WARN(
- "L2CAP eRTM Rx S-frame: cid: 0x%04x Len: %u Type: %s ReqSeq: %u "
- "P: %u F: %u",
+ log::warn(
+ "L2CAP eRTM Rx S-frame: cid: 0x{:04x} Len: {} Type: {} ReqSeq: {} "
+ " P: {} F: {}",
p_ccb->local_cid, p_buf->len,
SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
(ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
(ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
(ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
} else {
- LOG_VERBOSE(
- "L2CAP eRTM Rx S-frame: cid: 0x%04x Len: %u Type: %s ReqSeq: %u "
- "P: %u F: %u",
+ log::verbose(
+ "L2CAP eRTM Rx S-frame: cid: 0x{:04x} Len: {} Type: {} ReqSeq: {} "
+ " P: {} F: {}",
p_ccb->local_cid, p_buf->len,
SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
(ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
@@ -511,9 +514,9 @@
(ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
}
} else {
- LOG_VERBOSE(
- "L2CAP eRTM Rx I-frame: cid: 0x%04x Len: %u SAR: %-12s TxSeq: %u "
- "ReqSeq: %u F: %u",
+ log::verbose(
+ "L2CAP eRTM Rx I-frame: cid: 0x{:04x} Len: {} SAR: {:<12s} TxSeq: "
+ "{} ReqSeq: {} F: {}",
p_ccb->local_cid, p_buf->len,
SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
(ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
@@ -521,9 +524,9 @@
(ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
}
- LOG_VERBOSE(
- " eRTM Rx Nxt_tx_seq %u, Lst_rx_ack %u, Nxt_seq_exp %u, Lst_ack_snt "
- "%u, wt_q.cnt %zu, tries %u",
+ log::verbose(
+ "eRTM Rx Nxt_tx_seq {}, Lst_rx_ack {}, Nxt_seq_exp {}, Lst_ack_snt {}, "
+ "wt_q.cnt {}, tries {}",
p_ccb->fcrb.next_tx_seq, p_ccb->fcrb.last_rx_ack,
p_ccb->fcrb.next_seq_expected, p_ccb->fcrb.last_ack_sent,
fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q), p_ccb->fcrb.num_tries);
@@ -536,7 +539,7 @@
p_buf->len -= L2CAP_FCS_LEN;
if (l2c_fcr_rx_get_fcs(p_buf) != fcs) {
- LOG_WARN("Rx L2CAP PDU: CID: 0x%04x BAD FCS", p_ccb->local_cid);
+ log::warn("Rx L2CAP PDU: CID: 0x{:04x} BAD FCS", p_ccb->local_cid);
osi_free(p_buf);
return;
}
@@ -619,9 +622,9 @@
STREAM_TO_UINT16(ctrl_word, p);
- LOG_VERBOSE(
- "l2c_fcr_proc_pdu() CID: 0x%04x Process Buffer from SREJ_Hold_Q "
- "TxSeq: %u Expected_Seq: %u",
+ log::verbose(
+ "l2c_fcr_proc_pdu() CID: 0x{:04x} Process Buffer from SREJ_Hold_Q "
+ " TxSeq: {} Expected_Seq: {}",
p_ccb->local_cid,
(ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
p_ccb->fcrb.next_seq_expected);
@@ -647,9 +650,9 @@
(p_ccb->fcrb.next_seq_expected != p_ccb->fcrb.last_ack_sent))
l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, 0);
else {
- LOG_VERBOSE(
- "l2c_fcr_proc_pdu() not sending RR CID: 0x%04x local_busy:%d "
- "rej_sent:%d srej_sent:%d Expected_Seq:%u Last_Ack:%u",
+ log::verbose(
+ "l2c_fcr_proc_pdu() not sending RR CID: 0x{:04x} local_busy:{} "
+ "rej_sent:{} srej_sent:{} Expected_Seq:{} Last_Ack:{}",
p_ccb->local_cid, 0, p_ccb->fcrb.rej_sent, p_ccb->fcrb.srej_sent,
p_ccb->fcrb.next_seq_expected, p_ccb->fcrb.last_ack_sent);
}
@@ -682,8 +685,8 @@
/* Buffer length should not exceed local mps */
if (p_buf->len > p_ccb->local_conn_cfg.mps) {
- LOG_ERROR("buffer length=%d exceeds local mps=%d. Drop and disconnect.",
- p_buf->len, p_ccb->local_conn_cfg.mps);
+ log::error("buffer length={} exceeds local mps={}. Drop and disconnect.",
+ p_buf->len, p_ccb->local_conn_cfg.mps);
/* Discard the buffer and disconnect*/
osi_free(p_buf);
@@ -693,8 +696,7 @@
if (p_ccb->is_first_seg) {
if (p_buf->len < sizeof(sdu_length)) {
- LOG_ERROR("%s: buffer length=%d too small. Need at least 2.", __func__,
- p_buf->len);
+ log::error("buffer length={} too small. Need at least 2.", p_buf->len);
/* Discard the buffer */
osi_free(p_buf);
return;
@@ -703,8 +705,8 @@
/* Check the SDU Length with local MTU size */
if (sdu_length > p_ccb->local_conn_cfg.mtu) {
- LOG_ERROR("sdu length=%d exceeds local mtu=%d. Drop and disconnect.",
- sdu_length, p_ccb->local_conn_cfg.mtu);
+ log::error("sdu length={} exceeds local mtu={}. Drop and disconnect.",
+ sdu_length, p_ccb->local_conn_cfg.mtu);
/* Discard the buffer and disconnect*/
osi_free(p_buf);
l2cu_disconnect_chnl(p_ccb);
@@ -715,7 +717,7 @@
p_buf->offset += sizeof(sdu_length);
if (sdu_length < p_buf->len) {
- LOG_ERROR("%s: Invalid sdu_length: %d", __func__, sdu_length);
+ log::error("Invalid sdu_length: {}", sdu_length);
/* Discard the buffer */
osi_free(p_buf);
return;
@@ -730,7 +732,7 @@
p_ccb->ble_sdu = p_data;
p_data->len = 0;
p_ccb->ble_sdu_length = sdu_length;
- LOG_VERBOSE("%s SDU Length = %d", __func__, sdu_length);
+ log::verbose("SDU Length = {}", sdu_length);
p_data->offset = 0;
} else {
@@ -740,8 +742,8 @@
return;
}
if (p_buf->len > (p_ccb->ble_sdu_length - p_data->len)) {
- LOG_ERROR("%s: buffer length=%d too big. max=%d. Dropped", __func__,
- p_data->len, (p_ccb->ble_sdu_length - p_data->len));
+ log::error("buffer length={} too big. max={}. Dropped", p_data->len,
+ (p_ccb->ble_sdu_length - p_data->len));
osi_free(p_buf);
/* Throw away all pending fragments and disconnects */
@@ -782,9 +784,9 @@
******************************************************************************/
void l2c_fcr_proc_tout(tL2C_CCB* p_ccb) {
CHECK(p_ccb != NULL);
- LOG_VERBOSE(
- "l2c_fcr_proc_tout: CID: 0x%04x num_tries: %u (max: %u) wait_ack: %u "
- "ack_q_count: %zu",
+ log::verbose(
+ "l2c_fcr_proc_tout: CID: 0x{:04x} num_tries: {} (max: {}) wait_ack: "
+ "{} ack_q_count: {}",
p_ccb->local_cid, p_ccb->fcrb.num_tries, p_ccb->peer_cfg.fcr.max_transmit,
p_ccb->fcrb.wait_ack, fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q));
@@ -809,8 +811,9 @@
******************************************************************************/
void l2c_fcr_proc_ack_tout(tL2C_CCB* p_ccb) {
CHECK(p_ccb != NULL);
- LOG_VERBOSE(
- "l2c_fcr_proc_ack_tout: CID: 0x%04x State: %u Wack:%u Rq:%d Acked:%d",
+ log::verbose(
+ "l2c_fcr_proc_ack_tout: CID: 0x{:04x} State: {} Wack:{} Rq:{} "
+ "Acked:{}",
p_ccb->local_cid, p_ccb->chnl_state, p_ccb->fcrb.wait_ack,
p_ccb->fcrb.next_seq_expected, p_ccb->fcrb.last_ack_sent);
@@ -858,9 +861,9 @@
/* Verify the request sequence is in range before proceeding */
if (num_bufs_acked > fixed_queue_length(p_fcrb->waiting_for_ack_q)) {
/* The channel is closed if ReqSeq is not in range */
- LOG_WARN(
- "L2CAP eRTM Frame BAD Req_Seq - ctrl_word: 0x%04x req_seq 0x%02x "
- "last_rx_ack: 0x%02x QCount: %zu",
+ log::warn(
+ "L2CAP eRTM Frame BAD Req_Seq - ctrl_word: 0x{:04x} req_seq 0x{:02x} "
+ "last_rx_ack: 0x{:02x} QCount: {}",
ctrl_word, req_seq, p_fcrb->last_rx_ack,
fixed_queue_length(p_fcrb->waiting_for_ack_q));
@@ -931,11 +934,11 @@
bool all_ok = true;
if (p_buf->len != 0) {
- LOG_WARN("Incorrect S-frame Length (%d)", p_buf->len);
+ log::warn("Incorrect S-frame Length ({})", p_buf->len);
}
- LOG_VERBOSE("process_s_frame ctrl_word 0x%04x fcrb_remote_busy:%d", ctrl_word,
- p_fcrb->remote_busy);
+ log::verbose("process_s_frame ctrl_word 0x{:04x} fcrb_remote_busy:{}",
+ ctrl_word, p_fcrb->remote_busy);
if (ctrl_word & L2CAP_FCR_P_BIT) {
p_fcrb->rej_sent = false; /* After checkpoint, we can send anoher REJ */
@@ -981,7 +984,7 @@
p_fcrb->send_f_rsp = false;
}
} else {
- LOG_VERBOSE("process_s_frame hit_max_retries");
+ log::verbose("process_s_frame hit_max_retries");
}
osi_free(p_buf);
@@ -1023,15 +1026,15 @@
/* Is the frame a duplicate ? If so, just drop it */
if (num_lost >= p_ccb->our_cfg.fcr.tx_win_sz) {
/* Duplicate - simply drop it */
- LOG_WARN(
- "process_i_frame() Dropping Duplicate Frame tx_seq:%u ExpectedTxSeq "
- "%u",
+ log::warn(
+ "process_i_frame() Dropping Duplicate Frame tx_seq:{} ExpectedTxSeq "
+ "{}",
tx_seq, p_fcrb->next_seq_expected);
osi_free(p_buf);
} else {
- LOG_WARN(
- "process_i_frame() CID: 0x%04x Lost: %u tx_seq:%u ExpTxSeq %u "
- "Rej: %u SRej: %u",
+ log::warn(
+ "process_i_frame() CID: 0x{:04x} Lost: {} tx_seq:{} ExpTxSeq {} "
+ "Rej: {} SRej: {}",
p_ccb->local_cid, num_lost, tx_seq, p_fcrb->next_seq_expected,
p_fcrb->rej_sent, p_fcrb->srej_sent);
@@ -1047,17 +1050,17 @@
if ((tx_seq == next_srej) &&
(fixed_queue_length(p_fcrb->srej_rcv_hold_q) <
p_ccb->our_cfg.fcr.tx_win_sz)) {
- LOG_VERBOSE(
- "process_i_frame() Lost: %u tx_seq:%u ExpTxSeq %u Rej: %u "
+ log::verbose(
+ "process_i_frame() Lost: {} tx_seq:{} ExpTxSeq {} Rej: {} "
"SRej1",
num_lost, tx_seq, p_fcrb->next_seq_expected, p_fcrb->rej_sent);
p_buf->layer_specific = tx_seq;
fixed_queue_enqueue(p_fcrb->srej_rcv_hold_q, p_buf);
} else {
- LOG_WARN(
- "process_i_frame() CID: 0x%04x frame dropped in Srej Sent "
- "next_srej:%u hold_q.count:%zu win_sz:%u",
+ log::warn(
+ "process_i_frame() CID: 0x{:04x} frame dropped in Srej Sent "
+ "next_srej:{} hold_q.count:{} win_sz:{}",
p_ccb->local_cid, next_srej,
fixed_queue_length(p_fcrb->srej_rcv_hold_q),
p_ccb->our_cfg.fcr.tx_win_sz);
@@ -1066,17 +1069,17 @@
osi_free(p_buf);
}
} else if (p_fcrb->rej_sent) {
- LOG_WARN(
- "process_i_frame() CID: 0x%04x Lost: %u tx_seq:%u ExpTxSeq %u "
- "Rej: 1 SRej: %u",
+ log::warn(
+ "process_i_frame() CID: 0x{:04x} Lost: {} tx_seq:{} ExpTxSeq {} "
+ " Rej: 1 SRej: {}",
p_ccb->local_cid, num_lost, tx_seq, p_fcrb->next_seq_expected,
p_fcrb->srej_sent);
/* If REJ sent, just drop the frame */
osi_free(p_buf);
} else {
- LOG_VERBOSE(
- "process_i_frame() CID: 0x%04x tx_seq:%u ExpTxSeq %u Rej: %u",
+ log::verbose(
+ "process_i_frame() CID: 0x{:04x} tx_seq:{} ExpTxSeq {} Rej: {}",
p_ccb->local_cid, tx_seq, p_fcrb->next_seq_expected,
p_fcrb->rej_sent);
@@ -1087,9 +1090,9 @@
l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_REJ, 0);
} else {
if (!fixed_queue_is_empty(p_fcrb->srej_rcv_hold_q)) {
- LOG_ERROR(
- "process_i_frame() CID: 0x%04x sending SREJ tx_seq:%d "
- "hold_q.count:%zu",
+ log::error(
+ "process_i_frame() CID: 0x{:04x} sending SREJ tx_seq:{} "
+ "hold_q.count:{}",
p_ccb->local_cid, tx_seq,
fixed_queue_length(p_fcrb->srej_rcv_hold_q));
}
@@ -1115,8 +1118,8 @@
/* If any SAR problem in eRTM mode, spec says disconnect. */
if (!do_sar_reassembly(p_ccb, p_buf, ctrl_word)) {
- LOG_WARN("process_i_frame() CID: 0x%04x reassembly failed",
- p_ccb->local_cid);
+ log::warn("process_i_frame() CID: 0x{:04x} reassembly failed",
+ p_ccb->local_cid);
l2cu_disconnect_chnl(p_ccb);
return;
}
@@ -1168,9 +1171,9 @@
/* Check if the SAR state is correct */
if ((sar_type == L2CAP_FCR_UNSEG_SDU) || (sar_type == L2CAP_FCR_START_SDU)) {
if (p_fcrb->p_rx_sdu != NULL) {
- LOG_WARN(
- "SAR - got unexpected unsegmented or start SDU Expected len: %u "
- "Got so far: %u",
+ log::warn(
+ "SAR - got unexpected unsegmented or start SDU Expected len: {} "
+ "Got so far: {}",
p_fcrb->rx_sdu_len, p_fcrb->p_rx_sdu->len);
packet_ok = false;
@@ -1178,12 +1181,12 @@
/* Check the length of the packet */
if ((sar_type == L2CAP_FCR_START_SDU) &&
(p_buf->len < L2CAP_SDU_LEN_OVERHEAD)) {
- LOG_WARN("SAR start packet too short: %u", p_buf->len);
+ log::warn("SAR start packet too short: {}", p_buf->len);
packet_ok = false;
}
} else {
if (p_fcrb->p_rx_sdu == NULL) {
- LOG_WARN("SAR - got unexpected cont or end SDU");
+ log::warn("SAR - got unexpected cont or end SDU");
packet_ok = false;
}
}
@@ -1199,8 +1202,8 @@
p_buf->len -= 2;
if (p_fcrb->rx_sdu_len > p_ccb->max_rx_mtu) {
- LOG_WARN("SAR - SDU len: %u larger than MTU: %u", p_fcrb->rx_sdu_len,
- p_ccb->max_rx_mtu);
+ log::warn("SAR - SDU len: {} larger than MTU: {}", p_fcrb->rx_sdu_len,
+ p_ccb->max_rx_mtu);
packet_ok = false;
} else {
p_fcrb->p_rx_sdu = (BT_HDR*)osi_malloc(
@@ -1212,14 +1215,14 @@
if (packet_ok) {
if ((p_fcrb->p_rx_sdu->len + p_buf->len) > p_fcrb->rx_sdu_len) {
- LOG_ERROR("SAR - SDU len exceeded Type: %u Lengths: %u %u %u",
- sar_type, p_fcrb->p_rx_sdu->len, p_buf->len,
- p_fcrb->rx_sdu_len);
+ log::error("SAR - SDU len exceeded Type: {} Lengths: {} {} {}",
+ sar_type, p_fcrb->p_rx_sdu->len, p_buf->len,
+ p_fcrb->rx_sdu_len);
packet_ok = false;
} else if ((sar_type == L2CAP_FCR_END_SDU) &&
((p_fcrb->p_rx_sdu->len + p_buf->len) != p_fcrb->rx_sdu_len)) {
- LOG_WARN("SAR - SDU end rcvd but SDU incomplete: %u %u %u",
- p_fcrb->p_rx_sdu->len, p_buf->len, p_fcrb->rx_sdu_len);
+ log::warn("SAR - SDU end rcvd but SDU incomplete: {} {} {}",
+ p_fcrb->p_rx_sdu->len, p_buf->len, p_fcrb->rx_sdu_len);
packet_ok = false;
} else {
memcpy(((uint8_t*)(p_fcrb->p_rx_sdu + 1)) + p_fcrb->p_rx_sdu->offset +
@@ -1277,9 +1280,9 @@
if ((!fixed_queue_is_empty(p_ccb->fcrb.waiting_for_ack_q)) &&
(p_ccb->peer_cfg.fcr.max_transmit != 0) &&
(p_ccb->fcrb.num_tries >= p_ccb->peer_cfg.fcr.max_transmit)) {
- LOG_VERBOSE(
- "Max Tries Exceeded: (last_acq: %d CID: 0x%04x num_tries: %u (max: "
- "%u) ack_q_count: %zu",
+ log::verbose(
+ "Max Tries Exceeded: (last_acq: {} CID: 0x{:04x} num_tries: {} "
+ "(max: {}) ack_q_count: {}",
p_ccb->fcrb.last_rx_ack, p_ccb->local_cid, p_ccb->fcrb.num_tries,
p_ccb->peer_cfg.fcr.max_transmit,
fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q));
@@ -1310,16 +1313,16 @@
buf_seq =
(ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT;
- LOG_VERBOSE("retransmit_i_frames() cur seq: %u looking for: %u",
- buf_seq, tx_seq);
+ log::verbose("retransmit_i_frames() cur seq: {} looking for: {}",
+ buf_seq, tx_seq);
if (tx_seq == buf_seq) break;
}
}
if (!p_buf) {
- LOG_ERROR("retransmit_i_frames() UNKNOWN seq: %u q_count: %zu", tx_seq,
- fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q));
+ log::error("retransmit_i_frames() UNKNOWN seq: {} q_count: {}", tx_seq,
+ fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q));
return (true);
}
} else {
@@ -1439,8 +1442,8 @@
} else /* Should never happen if the application has configured buffers
correctly */
{
- LOG_ERROR("L2CAP - cannot get buffer for segmentation, max_pdu: %u",
- max_pdu);
+ log::error("L2CAP - cannot get buffer for segmentation, max_pdu: {}",
+ max_pdu);
return (NULL);
}
} else /* Use the original buffer if no segmentation, or the last segment */
@@ -1495,8 +1498,9 @@
l2c_fcr_clone_buf(p_xmit, HCI_DATA_PREAMBLE_SIZE, p_xmit->len);
if (!p_wack) {
- LOG_ERROR("L2CAP - no buffer for xmit cloning, CID: 0x%04x Length: %u",
- p_ccb->local_cid, p_xmit->len);
+ log::error(
+ "L2CAP - no buffer for xmit cloning, CID: 0x{:04x} Length: {}",
+ p_ccb->local_cid, p_xmit->len);
/* We will not save the FCS in case we reconfigure and change options */
p_xmit->len -= L2CAP_FCS_LEN;
@@ -1600,7 +1604,7 @@
/* Remove nonbasic options that the peer does not support */
if (!(p_ccb->p_lcb->peer_ext_fea & L2CAP_EXTFEA_ENH_RETRANS) &&
p_ccb->p_rcb->ertm_info.preferred_mode == L2CAP_FCR_ERTM_MODE) {
- LOG_WARN("L2CAP - Peer does not support our desired channel types");
+ log::warn("L2CAP - Peer does not support our desired channel types");
p_ccb->p_rcb->ertm_info.preferred_mode = 0;
return false;
}
@@ -1636,8 +1640,8 @@
p_ccb->our_cfg.fcr.rtrans_tout = 0;
}
- LOG_VERBOSE(
- "l2c_fcr_adj_monitor_retran_timeout: mon_tout:%d, rtrans_tout:%d",
+ log::verbose(
+ "l2c_fcr_adj_monitor_retran_timeout: mon_tout:{}, rtrans_tout:{}",
p_ccb->our_cfg.fcr.mon_tout, p_ccb->our_cfg.fcr.rtrans_tout);
}
}
@@ -1667,8 +1671,8 @@
* adjust it. For now, respond with our own tx_wnd_sz. */
/* Note: peer is not guaranteed to obey our adjustment */
if (p_ccb->peer_cfg.fcr.tx_win_sz > p_ccb->our_cfg.fcr.tx_win_sz) {
- LOG_VERBOSE("%s: adjusting requested tx_win_sz from %i to %i", __func__,
- p_ccb->peer_cfg.fcr.tx_win_sz, p_ccb->our_cfg.fcr.tx_win_sz);
+ log::verbose("adjusting requested tx_win_sz from {} to {}",
+ p_ccb->peer_cfg.fcr.tx_win_sz, p_ccb->our_cfg.fcr.tx_win_sz);
p_ccb->peer_cfg.fcr.tx_win_sz = p_ccb->our_cfg.fcr.tx_win_sz;
}
@@ -1712,7 +1716,7 @@
if (p_ccb->our_cfg.fcr.mode != peer_mode) {
if ((--p_ccb->fcr_cfg_tries) == 0) {
p_cfg->result = L2CAP_CFG_FAILED_NO_REASON;
- LOG_WARN("l2c_fcr_renegotiate_chan (Max retries exceeded)");
+ log::warn("l2c_fcr_renegotiate_chan (Max retries exceeded)");
}
can_renegotiate = false;
@@ -1723,7 +1727,7 @@
case L2CAP_FCR_ERTM_MODE:
/* We can try basic for any other peer mode because it's always
* supported */
- LOG_VERBOSE("%s(Trying Basic)", __func__);
+ log::verbose("(Trying Basic)");
can_renegotiate = true;
p_ccb->our_cfg.fcr.mode = L2CAP_FCR_BASIC_MODE;
break;
@@ -1742,7 +1746,7 @@
/* Basic Mode uses ACL Data Pool, make sure the MTU fits */
if ((p_cfg->mtu_present) && (p_cfg->mtu > L2CAP_MTU_SIZE)) {
- LOG_WARN("L2CAP - adjust MTU: %u too large", p_cfg->mtu);
+ log::warn("L2CAP - adjust MTU: {} too large", p_cfg->mtu);
p_cfg->mtu = L2CAP_MTU_SIZE;
}
}
@@ -1758,8 +1762,8 @@
/* Disconnect if the channels do not match */
if (p_ccb->our_cfg.fcr.mode != peer_mode) {
- LOG_WARN("L2C CFG: Channels incompatible (local %d, peer %d)",
- p_ccb->our_cfg.fcr.mode, peer_mode);
+ log::warn("L2C CFG: Channels incompatible (local {}, peer {})",
+ p_ccb->our_cfg.fcr.mode, peer_mode);
l2cu_disconnect_chnl(p_ccb);
}
@@ -1787,9 +1791,9 @@
p_ccb->p_lcb->w4_info_rsp =
false; /* Handles T61x SonyEricsson Bug in Info Request */
- LOG_VERBOSE(
- "l2c_fcr_process_peer_cfg_req() CFG fcr_present:%d fcr.mode:%d CCB FCR "
- "mode:%d preferred: %u",
+ log::verbose(
+ "l2c_fcr_process_peer_cfg_req() CFG fcr_present:{} fcr.mode:{} CCB FCR "
+ "mode:{} preferred: {}",
p_cfg->fcr_present, p_cfg->fcr.mode, p_ccb->our_cfg.fcr.mode,
p_ccb->p_rcb->ertm_info.preferred_mode);
@@ -1846,8 +1850,8 @@
/* Ensure the MPS is not bigger than our retransmission buffer */
if (p_cfg->fcr.mps > max_retrans_size) {
- LOG_VERBOSE("CFG: Overriding MPS to %d (orig %d)", max_retrans_size,
- p_cfg->fcr.mps);
+ log::verbose("CFG: Overriding MPS to {} (orig {})", max_retrans_size,
+ p_cfg->fcr.mps);
p_cfg->fcr.mps = max_retrans_size;
p_ccb->out_cfg_fcr_present = true;
diff --git a/system/stack/l2cap/l2c_int.h b/system/stack/l2cap/l2c_int.h
index be9b715..6221ff1 100644
--- a/system/stack/l2cap/l2c_int.h
+++ b/system/stack/l2cap/l2c_int.h
@@ -25,6 +25,7 @@
#define L2C_INT_H
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <stdbool.h>
#include <string>
@@ -884,4 +885,13 @@
uint16_t peripheral_latency,
uint16_t cont_num, uint16_t timeout);
+namespace fmt {
+template <>
+struct formatter<tL2C_LINK_STATE> : enum_formatter<tL2C_LINK_STATE> {};
+template <>
+struct formatter<tL2CEVT> : enum_formatter<tL2CEVT> {};
+template <>
+struct formatter<tL2C_CHNL_STATE> : enum_formatter<tL2C_CHNL_STATE> {};
+} // namespace fmt
+
#endif
diff --git a/system/stack/l2cap/l2c_link.cc b/system/stack/l2cap/l2c_link.cc
index 33bc130..a3f17ba 100644
--- a/system/stack/l2cap/l2c_link.cc
+++ b/system/stack/l2cap/l2c_link.cc
@@ -25,6 +25,8 @@
******************************************************************************/
#define LOG_TAG "l2c_link"
+#include <bluetooth/log.h>
+
#include <cstdint>
#include "device/include/device_iot_config.h"
@@ -44,6 +46,8 @@
#include "types/bt_transport.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
extern tBTM_CB btm_cb;
bool BTM_ReadPowerMode(const RawAddress& remote_bda, tBTM_PM_MODE* p_mode);
@@ -78,26 +82,26 @@
if (p_lcb == nullptr) {
p_lcb = l2cu_allocate_lcb(ci.bd_addr, false, BT_TRANSPORT_BR_EDR);
if (p_lcb == nullptr) {
- LOG_WARN("Failed to allocate an LCB");
+ log::warn("Failed to allocate an LCB");
return;
}
- LOG_DEBUG("Allocated l2cap control block for new connection state:%s",
- link_state_text(p_lcb->link_state).c_str());
+ log::debug("Allocated l2cap control block for new connection state:{}",
+ link_state_text(p_lcb->link_state));
p_lcb->link_state = LST_CONNECTING;
}
if ((p_lcb->link_state == LST_CONNECTED) &&
(status == HCI_ERR_CONNECTION_EXISTS)) {
- LOG_WARN("Connection already exists handle:0x%04x", handle);
+ log::warn("Connection already exists handle:0x{:04x}", handle);
return;
} else if (p_lcb->link_state != LST_CONNECTING) {
- LOG_ERROR(
- "Link received unexpected connection complete state:%s status:%s "
- "handle:0x%04x",
- link_state_text(p_lcb->link_state).c_str(),
- hci_error_code_text(status).c_str(), p_lcb->Handle());
+ log::error(
+ "Link received unexpected connection complete state:{} status:{} "
+ "handle:0x{:04x}",
+ link_state_text(p_lcb->link_state), hci_error_code_text(status),
+ p_lcb->Handle());
if (status != HCI_SUCCESS) {
- LOG_ERROR("Disconnecting...");
+ log::error("Disconnecting...");
l2c_link_hci_disc_comp(p_lcb->Handle(), status);
}
return;
@@ -114,7 +118,7 @@
l2cu_send_peer_info_req(p_lcb, L2CAP_EXTENDED_FEATURES_INFO_TYPE);
if (p_lcb->IsBonding()) {
- LOG_DEBUG("Link is dedicated bonding handle:0x%04x", p_lcb->Handle());
+ log::debug("Link is dedicated bonding handle:0x{:04x}", p_lcb->Handle());
if (l2cu_start_post_bond_timer(handle)) return;
}
@@ -136,8 +140,8 @@
/* If there's an lcb disconnecting set this one to holding */
else if ((ci.status == HCI_ERR_MAX_NUM_OF_CONNECTIONS) &&
l2cu_lcb_disconnecting()) {
- LOG_WARN("Delaying connection as reached max number of links:%u",
- HCI_ERR_MAX_NUM_OF_CONNECTIONS);
+ log::warn("Delaying connection as reached max number of links:{}",
+ HCI_ERR_MAX_NUM_OF_CONNECTIONS);
p_lcb->link_state = LST_CONNECT_HOLDING;
p_lcb->InvalidateHandle();
} else {
@@ -154,8 +158,8 @@
p_ccb = pn;
}
- LOG_INFO("Disconnecting link handle:0x%04x status:%s", p_lcb->Handle(),
- hci_error_code_text(status).c_str());
+ log::info("Disconnecting link handle:0x{:04x} status:{}", p_lcb->Handle(),
+ hci_error_code_text(status));
p_lcb->SetDisconnectReason(status);
/* Release the LCB */
if (p_lcb->ccb_queue.p_first_ccb == NULL)
@@ -191,9 +195,8 @@
tL2C_CCB* p_ccb;
tL2C_CCB* p_next_ccb;
- LOG_DEBUG("btm_status=%s, BD_ADDR=%s, transport=%s",
- btm_status_text(status).c_str(), ADDRESS_TO_LOGGABLE_CSTR(*p_bda),
- bt_transport_text(transport).c_str());
+ log::debug("btm_status={}, BD_ADDR={}, transport={}", btm_status_text(status),
+ ADDRESS_TO_LOGGABLE_CSTR(*p_bda), bt_transport_text(transport));
if (status == BTM_SUCCESS_NO_SECURITY) {
status = BTM_SUCCESS;
@@ -207,7 +210,7 @@
/* If we don't have one, this is an error */
if (!p_lcb) {
- LOG_WARN("L2CAP got sec_comp for unknown BD_ADDR");
+ log::warn("L2CAP got sec_comp for unknown BD_ADDR");
return;
}
@@ -324,7 +327,7 @@
disconnecting
*/
if (p_lcb->ccb_queue.p_first_ccb != NULL || p_lcb->p_pending_ccb) {
- LOG_DEBUG("l2c_link_hci_disc_comp: Restarting pending ACL request");
+ log::debug("l2c_link_hci_disc_comp: Restarting pending ACL request");
/* Release any held buffers */
while (!list_is_empty(p_lcb->link_xmit_data_q)) {
BT_HDR* p_buf =
@@ -395,9 +398,8 @@
tL2C_CCB* p_ccb;
tBTM_STATUS rc;
- LOG_DEBUG("L2CAP - l2c_link_timeout() link state:%s is_bonding:%s",
- link_state_text(p_lcb->link_state).c_str(),
- logbool(p_lcb->IsBonding()).c_str());
+ log::debug("L2CAP - l2c_link_timeout() link state:{} is_bonding:{}",
+ link_state_text(p_lcb->link_state), logbool(p_lcb->IsBonding()));
/* If link was connecting or disconnecting, clear all channels and drop the
* LCB */
@@ -428,7 +430,7 @@
uint64_t timeout_ms;
bool start_timeout = true;
- LOG_WARN("TODO: Remove this callback into bcm_sec_disconnect");
+ log::warn("TODO: Remove this callback into bcm_sec_disconnect");
rc = btm_sec_disconnect(
p_lcb->Handle(), HCI_ERR_PEER_USER,
"stack::l2cap::l2c_link::l2c_link_timeout All channels closed");
@@ -596,9 +598,9 @@
qq = qq_remainder = 1;
}
- LOG_DEBUG(
- "l2c_link_adjust_allocation num_hipri: %u num_lowpri: %u low_quota: "
- "%u round_robin_quota: %u qq: %u",
+ log::debug(
+ "l2c_link_adjust_allocation num_hipri: {} num_lowpri: {} low_quota: "
+ "{} round_robin_quota: {} qq: {}",
num_hipri_links, num_lowpri_links, low_quota, l2cb.round_robin_quota, qq);
/* Now, assign the quotas to each link */
@@ -623,12 +625,12 @@
}
}
- LOG_DEBUG(
- "l2c_link_adjust_allocation LCB %d Priority: %d XmitQuota: %d", yy,
+ log::debug(
+ "l2c_link_adjust_allocation LCB {} Priority: {} XmitQuota: {}", yy,
p_lcb->acl_priority, p_lcb->link_xmit_quota);
- LOG_DEBUG(" SentNotAcked: %d RRUnacked: %d",
- p_lcb->sent_not_acked, l2cb.round_robin_unacked);
+ log::debug("SentNotAcked: {} RRUnacked: {}", p_lcb->sent_not_acked,
+ l2cb.round_robin_unacked);
/* There is a special case where we have readjusted the link quotas and */
/* this link may have sent anything but some other link sent packets so */
@@ -667,9 +669,9 @@
tL2CAP_CHNL_DATA_RATE data_rate = p_ccb->tx_data_rate + p_ccb->rx_data_rate;
p_ccb->buff_quota = L2CAP_CBB_DEFAULT_DATA_RATE_BUFF_QUOTA * data_rate;
- LOG_DEBUG(
- "CID:0x%04x FCR Mode:%u Priority:%u TxDataRate:%u RxDataRate:%u "
- "Quota:%u",
+ log::debug(
+ "CID:0x{:04x} FCR Mode:{} Priority:{} TxDataRate:{} RxDataRate:{} "
+ "Quota:{}",
p_ccb->local_cid, p_ccb->peer_cfg.fcr.mode, p_ccb->ccb_priority,
p_ccb->tx_data_rate, p_ccb->rx_data_rate, p_ccb->buff_quota);
@@ -780,7 +782,7 @@
tBTM_PM_MODE mode;
if (BTM_ReadPowerMode(p_lcb->remote_bd_addr, &mode)) {
if (mode == BTM_PM_STS_PENDING) {
- LOG_DEBUG("LCB(0x%x) is in PM pending state", p_lcb->Handle());
+ log::debug("LCB(0x{:x}) is in PM pending state", p_lcb->Handle());
return true;
}
}
@@ -826,7 +828,7 @@
** This LCB will be served when receiving number of completed packet event.
*/
if (l2cb.is_cong_cback_context) {
- LOG_INFO("skipping, is_cong_cback_context=true");
+ log::info("skipping, is_cong_cback_context=true");
return;
}
@@ -834,7 +836,7 @@
** have at least 1, then do a round-robin for all the LCBs
*/
if ((p_lcb == NULL) || (p_lcb->link_xmit_quota == 0)) {
- LOG_DEBUG("Round robin");
+ log::debug("Round robin");
if (p_lcb == NULL) {
p_lcb = l2cb.lcb_pool;
} else if (!single_write) {
@@ -853,34 +855,34 @@
(p_lcb->transport == BT_TRANSPORT_LE &&
(l2cb.ble_round_robin_unacked >= l2cb.ble_round_robin_quota ||
l2cb.controller_le_xmit_window == 0))) {
- LOG_DEBUG("Skipping lcb %d due to controller window full", xx);
+ log::debug("Skipping lcb {} due to controller window full", xx);
continue;
}
if ((!p_lcb->in_use) || (p_lcb->link_state != LST_CONNECTED) ||
(p_lcb->link_xmit_quota != 0) || (l2c_link_check_power_mode(p_lcb))) {
- LOG_DEBUG("Skipping lcb %d due to quota", xx);
+ log::debug("Skipping lcb {} due to quota", xx);
continue;
}
/* See if we can send anything from the Link Queue */
if (!list_is_empty(p_lcb->link_xmit_data_q)) {
- LOG_VERBOSE("Sending to lower layer");
+ log::verbose("Sending to lower layer");
p_buf = (BT_HDR*)list_front(p_lcb->link_xmit_data_q);
list_remove(p_lcb->link_xmit_data_q, p_buf);
l2c_link_send_to_lower(p_lcb, p_buf, NULL);
} else if (single_write) {
/* If only doing one write, break out */
- LOG_DEBUG("single_write is true, skipping");
+ log::debug("single_write is true, skipping");
break;
}
/* If nothing on the link queue, check the channel queue */
else {
tL2C_TX_COMPLETE_CB_INFO cbi = {};
- LOG_DEBUG("Check next buffer");
+ log::debug("Check next buffer");
p_buf = l2cu_get_next_buffer_to_send(p_lcb, &cbi);
if (p_buf != NULL) {
- LOG_DEBUG("Sending next buffer");
+ log::debug("Sending next buffer");
l2c_link_send_to_lower(p_lcb, p_buf, &cbi);
}
}
@@ -901,12 +903,12 @@
/* If a partial segment is being sent, can't send anything else */
if ((p_lcb->link_state != LST_CONNECTED) ||
(l2c_link_check_power_mode(p_lcb))) {
- LOG_INFO("A partial segment is being sent, cannot send anything else");
+ log::info("A partial segment is being sent, cannot send anything else");
return;
}
- LOG_VERBOSE(
- "Direct send, transport=%d, xmit_window=%d, le_xmit_window=%d, "
- "sent_not_acked=%d, link_xmit_quota=%d",
+ log::verbose(
+ "Direct send, transport={}, xmit_window={}, le_xmit_window={}, "
+ "sent_not_acked={}, link_xmit_quota={}",
p_lcb->transport, l2cb.controller_xmit_window,
l2cb.controller_le_xmit_window, p_lcb->sent_not_acked,
p_lcb->link_xmit_quota);
@@ -918,10 +920,10 @@
(p_lcb->transport == BT_TRANSPORT_LE))) &&
(p_lcb->sent_not_acked < p_lcb->link_xmit_quota)) {
if (list_is_empty(p_lcb->link_xmit_data_q)) {
- LOG_VERBOSE("No transmit data, skipping");
+ log::verbose("No transmit data, skipping");
break;
}
- LOG_VERBOSE("Sending to lower layer");
+ log::verbose("Sending to lower layer");
p_buf = (BT_HDR*)list_front(p_lcb->link_xmit_data_q);
list_remove(p_lcb->link_xmit_data_q, p_buf);
l2c_link_send_to_lower(p_lcb, p_buf, NULL);
@@ -929,7 +931,7 @@
if (!single_write) {
/* See if we can send anything for any channel */
- LOG_VERBOSE("Trying to send other data when single_write is false");
+ log::verbose("Trying to send other data when single_write is false");
while (((l2cb.controller_xmit_window != 0 &&
(p_lcb->transport == BT_TRANSPORT_BR_EDR)) ||
(l2cb.controller_le_xmit_window != 0 &&
@@ -938,10 +940,10 @@
tL2C_TX_COMPLETE_CB_INFO cbi = {};
p_buf = l2cu_get_next_buffer_to_send(p_lcb, &cbi);
if (p_buf == NULL) {
- LOG_VERBOSE("No next buffer, skipping");
+ log::verbose("No next buffer, skipping");
break;
}
- LOG_VERBOSE("Sending to lower layer");
+ log::verbose("Sending to lower layer");
l2c_link_send_to_lower(p_lcb, p_buf, &cbi);
}
}
@@ -963,7 +965,7 @@
if (p_lcb != NULL) {
/* There might be any pending packets due to SNIFF or PENDING state */
/* Trigger L2C to start transmission of the pending packets. */
- LOG_VERBOSE(
+ log::verbose(
"btm mode change to active; check l2c_link for outgoing packets");
l2c_link_check_send_pkts(p_lcb, 0, NULL);
}
@@ -987,10 +989,10 @@
l2cb.controller_xmit_window--;
acl_send_data_packet_br_edr(p_lcb->remote_bd_addr, p_buf);
- LOG_VERBOSE("TotalWin=%d,Hndl=0x%x,Quota=%d,Unack=%d,RRQuota=%d,RRUnack=%d",
- l2cb.controller_xmit_window, p_lcb->Handle(),
- p_lcb->link_xmit_quota, p_lcb->sent_not_acked,
- l2cb.round_robin_quota, l2cb.round_robin_unacked);
+ log::verbose(
+ "TotalWin={},Hndl=0x{:x},Quota={},Unack={},RRQuota={},RRUnack={}",
+ l2cb.controller_xmit_window, p_lcb->Handle(), p_lcb->link_xmit_quota,
+ p_lcb->sent_not_acked, l2cb.round_robin_quota, l2cb.round_robin_unacked);
}
static void l2c_link_send_to_lower_ble(tL2C_LCB* p_lcb, BT_HDR* p_buf) {
@@ -1004,10 +1006,10 @@
l2cb.controller_le_xmit_window--;
acl_send_data_packet_ble(p_lcb->remote_bd_addr, p_buf);
- LOG_DEBUG("TotalWin=%d,Hndl=0x%x,Quota=%d,Unack=%d,RRQuota=%d,RRUnack=%d",
- l2cb.controller_le_xmit_window, p_lcb->Handle(),
- p_lcb->link_xmit_quota, p_lcb->sent_not_acked,
- l2cb.ble_round_robin_quota, l2cb.ble_round_robin_unacked);
+ log::debug("TotalWin={},Hndl=0x{:x},Quota={},Unack={},RRQuota={},RRUnack={}",
+ l2cb.controller_le_xmit_window, p_lcb->Handle(),
+ p_lcb->link_xmit_quota, p_lcb->sent_not_acked,
+ l2cb.ble_round_robin_quota, l2cb.ble_round_robin_unacked);
}
static void l2c_link_send_to_lower(tL2C_LCB* p_lcb, BT_HDR* p_buf,
@@ -1039,7 +1041,7 @@
l2cb.update_outstanding_le_packets(num_sent);
break;
default:
- LOG_ERROR("Unknown transport received:%u", p_lcb->transport);
+ log::error("Unknown transport received:{}", p_lcb->transport);
return;
}
@@ -1085,15 +1087,15 @@
/* Find the LCB based on the handle */
tL2C_LCB* p_lcb = l2cu_find_lcb_by_handle(handle);
if (p_lcb == nullptr) {
- LOG_WARN("Received segment complete for unknown connection handle:%d",
- handle);
+ log::warn("Received segment complete for unknown connection handle:{}",
+ handle);
osi_free(p_msg);
return;
}
if (p_lcb->link_state != LST_CONNECTED) {
- LOG_INFO("Received segment complete for unconnected connection handle:%d:",
- handle);
+ log::info("Received segment complete for unconnected connection handle:{}:",
+ handle);
osi_free(p_msg);
return;
}
@@ -1109,14 +1111,14 @@
tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_BR_EDR);
if (p_lcb && (p_lcb->link_state == LST_CONNECTED ||
p_lcb->link_state == LST_CONNECTING)) {
- LOG_WARN("Connection already exists");
+ log::warn("Connection already exists");
return BTM_CMD_STARTED;
}
/* Make sure an L2cap link control block is available */
if (!p_lcb &&
(p_lcb = l2cu_allocate_lcb(bd_addr, true, BT_TRANSPORT_BR_EDR)) == NULL) {
- LOG_WARN("failed allocate LCB for %s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::warn("failed allocate LCB for {}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return BTM_NO_RESOURCES;
}
@@ -1155,13 +1157,13 @@
p_ccb = p_lcb->rr_serv[p_lcb->rr_pri].p_serve_ccb;
if (!p_ccb) {
- LOG_ERROR("p_serve_ccb is NULL, rr_pri=%d", p_lcb->rr_pri);
+ log::error("p_serve_ccb is NULL, rr_pri={}", p_lcb->rr_pri);
return NULL;
}
- LOG_VERBOSE("RR scan pri=%d, lcid=0x%04x, q_cout=%zu",
- p_ccb->ccb_priority, p_ccb->local_cid,
- fixed_queue_length(p_ccb->xmit_hold_q));
+ log::verbose("RR scan pri={}, lcid=0x{:04x}, q_cout={}",
+ p_ccb->ccb_priority, p_ccb->local_cid,
+ fixed_queue_length(p_ccb->xmit_hold_q));
/* store the next serving channel */
/* this channel is the last channel of its priority group */
@@ -1178,7 +1180,7 @@
if (p_ccb->chnl_state != CST_OPEN) continue;
if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) {
- LOG_DEBUG("Connection oriented channel");
+ log::debug("Connection oriented channel");
if (fixed_queue_is_empty(p_ccb->xmit_hold_q)) continue;
} else {
@@ -1217,10 +1219,10 @@
}
if (p_serve_ccb) {
- LOG_VERBOSE("RR service pri=%d, quota=%d, lcid=0x%04x",
- p_serve_ccb->ccb_priority,
- p_lcb->rr_serv[p_serve_ccb->ccb_priority].quota,
- p_serve_ccb->local_cid);
+ log::verbose("RR service pri={}, quota={}, lcid=0x{:04x}",
+ p_serve_ccb->ccb_priority,
+ p_lcb->rr_serv[p_serve_ccb->ccb_priority].quota,
+ p_serve_ccb->local_cid);
}
return p_serve_ccb;
@@ -1274,7 +1276,7 @@
if (!fixed_queue_is_empty(p_ccb->xmit_hold_q)) {
p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q);
if (NULL == p_buf) {
- LOG_ERROR("No data to be sent");
+ log::error("No data to be sent");
return (NULL);
}
@@ -1299,7 +1301,7 @@
if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) {
/* Check credits */
if (p_ccb->peer_conn_cfg.credits == 0) {
- LOG_DEBUG("No credits to send packets");
+ log::debug("No credits to send packets");
return NULL;
}
@@ -1319,7 +1321,7 @@
} else {
p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q);
if (NULL == p_buf) {
- LOG_ERROR("#2: No data to be sent");
+ log::error("#2: No data to be sent");
return (NULL);
}
}
diff --git a/system/stack/l2cap/l2c_main.cc b/system/stack/l2cap/l2c_main.cc
index c1fcd6c..6634b7b 100644
--- a/system/stack/l2cap/l2c_main.cc
+++ b/system/stack/l2cap/l2c_main.cc
@@ -24,6 +24,7 @@
#define LOG_TAG "bt_l2c_main"
+#include <bluetooth/log.h>
#include <string.h>
#include "common/init_flags.h"
@@ -41,6 +42,8 @@
#include "stack/include/l2cdefs.h"
#include "stack/l2cap/l2c_int.h"
+using namespace bluetooth;
+
/******************************************************************************/
/* L O C A L F U N C T I O N P R O T O T Y P E S */
/******************************************************************************/
@@ -73,7 +76,7 @@
/* Since the HCI Transport is putting segmented packets back together, we */
/* should never get a valid packet with the type set to "continuation" */
if (pkt_type == L2CAP_PKT_CONTINUE) {
- LOG_WARN("L2CAP - received packet continuation");
+ log::warn("L2CAP - received packet continuation");
osi_free(p_msg);
return;
}
@@ -82,7 +85,7 @@
STREAM_TO_UINT16(hci_len, p);
if (hci_len < L2CAP_PKT_OVERHEAD || hci_len != p_msg->len - 4) {
/* Remote-declared packet size must match HCI_ACL size - ACL header (4) */
- LOG_WARN("L2CAP - got incorrect hci header");
+ log::warn("L2CAP - got incorrect hci header");
osi_free(p_msg);
return;
}
@@ -94,8 +97,8 @@
/* Find the LCB based on the handle */
tL2C_LCB* p_lcb = l2cu_find_lcb_by_handle(handle);
if (!p_lcb) {
- LOG_ERROR("L2CAP - rcvd ACL for unknown handle:%d ls:%d cid:%d", handle,
- p_msg->layer_specific, rcv_cid);
+ log::error("L2CAP - rcvd ACL for unknown handle:{} ls:{} cid:{}", handle,
+ p_msg->layer_specific, rcv_cid);
osi_free(p_msg);
return;
}
@@ -117,7 +120,7 @@
if (rcv_cid >= L2CAP_BASE_APPL_CID) {
p_ccb = l2cu_find_ccb_by_cid(p_lcb, rcv_cid);
if (!p_ccb) {
- LOG_WARN("L2CAP - unknown CID: 0x%04x", rcv_cid);
+ log::warn("L2CAP - unknown CID: 0x{:04x}", rcv_cid);
osi_free(p_msg);
return;
}
@@ -127,8 +130,8 @@
p_msg->offset += L2CAP_PKT_OVERHEAD;
if (l2cap_len != p_msg->len) {
- LOG_WARN("L2CAP - bad length in pkt. Exp: %d Act: %d", l2cap_len,
- p_msg->len);
+ log::warn("L2CAP - bad length in pkt. Exp: {} Act: {}", l2cap_len,
+ p_msg->len);
osi_free(p_msg);
return;
}
@@ -226,7 +229,7 @@
/* if l2cap command received in CID 1 on top of an LE link, ignore this
* command */
if (p_lcb->transport == BT_TRANSPORT_LE) {
- LOG_INFO("Dropping data on CID 1 for LE link");
+ log::info("Dropping data on CID 1 for LE link");
return;
}
@@ -238,8 +241,8 @@
* will be ignored. Here we simply mark the bad packet and decide which cmd
* ID to reject later */
pkt_size_rej = true;
- LOG_WARN("Signaling pkt_len=%d exceeds MTU size %d", pkt_len,
- L2CAP_DEFAULT_MTU);
+ log::warn("Signaling pkt_len={} exceeds MTU size {}", pkt_len,
+ L2CAP_DEFAULT_MTU);
}
uint8_t* p_next_cmd = p;
@@ -276,8 +279,8 @@
first_cmd = false;
if (cmd_len > BT_SMALL_BUFFER_SIZE) {
- LOG_WARN("Command size %u exceeds limit %d", cmd_len,
- BT_SMALL_BUFFER_SIZE);
+ log::warn("Command size {} exceeds limit {}", cmd_len,
+ BT_SMALL_BUFFER_SIZE);
l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_MTU_EXCEEDED, id, 0, 0);
return;
}
@@ -285,22 +288,22 @@
/* Check command length does not exceed packet length */
p_next_cmd = p + cmd_len;
if (p_next_cmd > p_pkt_end) {
- LOG_WARN("cmd_len > pkt_len, pkt_len=%d, cmd_len=%d, code=%d", pkt_len,
- cmd_len, cmd_code);
+ log::warn("cmd_len > pkt_len, pkt_len={}, cmd_len={}, code={}", pkt_len,
+ cmd_len, cmd_code);
break;
}
- LOG_DEBUG("cmd: %s, id:%d, cmd_len:%d",
- l2cap_command_code_text(cmd_code).c_str(), id, cmd_len);
+ log::debug("cmd: {}, id:{}, cmd_len:{}", l2cap_command_code_text(cmd_code),
+ id, cmd_len);
/* Bad L2CAP packet length, look for cmd to reject */
if (pkt_size_rej) {
/* If command found rejected it and we're done, otherwise keep looking */
if (l2c_is_cmd_rejected(cmd_code, id, p_lcb)) {
- LOG_WARN("Rejected command %d due to bad packet length", cmd_code);
+ log::warn("Rejected command {} due to bad packet length", cmd_code);
return;
} else {
- LOG_WARN("No need to reject command %d for bad packet len", cmd_code);
+ log::warn("No need to reject command {} for bad packet len", cmd_code);
continue; /* Look for next cmd/response in current packet */
}
}
@@ -309,39 +312,40 @@
case L2CAP_CMD_REJECT:
uint16_t rej_reason;
if (p + 2 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CMD_REJECT");
+ log::warn("Not enough data for L2CAP_CMD_REJECT");
return;
}
STREAM_TO_UINT16(rej_reason, p);
if (rej_reason == L2CAP_CMD_REJ_MTU_EXCEEDED) {
uint16_t rej_mtu;
if (p + 2 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CMD_REJ_MTU_EXCEEDED");
+ log::warn("Not enough data for L2CAP_CMD_REJ_MTU_EXCEEDED");
return;
}
STREAM_TO_UINT16(rej_mtu, p);
/* What to do with the MTU reject ? We have negotiated an MTU. For now
* we will ignore it and let a higher protocol timeout take care of it
*/
- LOG_WARN("MTU rej Handle: %d MTU: %d", p_lcb->Handle(), rej_mtu);
+ log::warn("MTU rej Handle: {} MTU: {}", p_lcb->Handle(), rej_mtu);
}
if (rej_reason == L2CAP_CMD_REJ_INVALID_CID) {
uint16_t lcid, rcid;
if (p + 4 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CMD_REJ_INVALID_CID");
+ log::warn("Not enough data for L2CAP_CMD_REJ_INVALID_CID");
return;
}
STREAM_TO_UINT16(rcid, p);
STREAM_TO_UINT16(lcid, p);
- LOG_WARN("Rejected due to invalid CID, LCID: 0x%04x RCID: 0x%04x",
- lcid, rcid);
+ log::warn(
+ "Rejected due to invalid CID, LCID: 0x{:04x} RCID: 0x{:04x}",
+ lcid, rcid);
/* Remote CID invalid. Treat as a disconnect */
tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(p_lcb, lcid);
if ((p_ccb != NULL) && (p_ccb->remote_cid == rcid)) {
/* Fake link disconnect - no reply is generated */
- LOG_WARN("Remote CID is invalid, treat as disconnected");
+ log::warn("Remote CID is invalid, treat as disconnected");
l2c_csm_execute(p_ccb, L2CEVT_LP_DISCONNECT_IND, NULL);
}
}
@@ -367,27 +371,27 @@
case L2CAP_CMD_CONN_REQ: {
uint16_t rcid;
if (p + 4 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CMD_CONN_REQ");
+ log::warn("Not enough data for L2CAP_CMD_CONN_REQ");
return;
}
STREAM_TO_UINT16(con_info.psm, p);
STREAM_TO_UINT16(rcid, p);
p_rcb = l2cu_find_rcb_by_psm(con_info.psm);
if (!p_rcb) {
- LOG_WARN("Rcvd conn req for unknown PSM: %d", con_info.psm);
+ log::warn("Rcvd conn req for unknown PSM: {}", con_info.psm);
l2cu_reject_connection(p_lcb, rcid, id, L2CAP_CONN_NO_PSM);
break;
} else {
if (!p_rcb->api.pL2CA_ConnectInd_Cb) {
- LOG_WARN("Rcvd conn req for outgoing-only connection PSM: %d",
- con_info.psm);
+ log::warn("Rcvd conn req for outgoing-only connection PSM: {}",
+ con_info.psm);
l2cu_reject_connection(p_lcb, rcid, id, L2CAP_CONN_NO_PSM);
break;
}
}
tL2C_CCB* p_ccb = l2cu_allocate_ccb(p_lcb, 0);
if (p_ccb == nullptr) {
- LOG_ERROR("Unable to allocate CCB");
+ log::error("Unable to allocate CCB");
l2cu_reject_connection(p_lcb, rcid, id, L2CAP_CONN_NO_RESOURCES);
break;
}
@@ -411,7 +415,7 @@
case L2CAP_CMD_CONN_RSP: {
uint16_t lcid;
if (p + 8 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CMD_CONN_REQ");
+ log::warn("Not enough data for L2CAP_CMD_CONN_REQ");
return;
}
STREAM_TO_UINT16(con_info.remote_cid, p);
@@ -421,12 +425,12 @@
tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(p_lcb, lcid);
if (!p_ccb) {
- LOG_WARN("no CCB for conn rsp, LCID: %d RCID: %d", lcid,
- con_info.remote_cid);
+ log::warn("no CCB for conn rsp, LCID: {} RCID: {}", lcid,
+ con_info.remote_cid);
break;
}
if (p_ccb->local_id != id) {
- LOG_WARN("con rsp - bad ID. Exp: %d Got: %d", p_ccb->local_id, id);
+ log::warn("con rsp - bad ID. Exp: {} Got: {}", p_ccb->local_id, id);
break;
}
@@ -457,7 +461,7 @@
uint16_t lcid;
if (p + 4 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CMD_CONFIG_REQ");
+ log::warn("Not enough data for L2CAP_CMD_CONFIG_REQ");
return;
}
STREAM_TO_UINT16(lcid, p);
@@ -472,7 +476,7 @@
while (p < p_cfg_end) {
uint8_t cfg_code, cfg_len;
if (p + 2 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CMD_CONFIG_REQ sub_event");
+ log::warn("Not enough data for L2CAP_CMD_CONFIG_REQ sub_event");
return;
}
STREAM_TO_UINT8(cfg_code, p);
@@ -601,7 +605,7 @@
uint8_t* p_cfg_end = p + cmd_len;
uint16_t lcid;
if (p + 6 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CMD_CONFIG_RSP");
+ log::warn("Not enough data for L2CAP_CMD_CONFIG_RSP");
return;
}
STREAM_TO_UINT16(lcid, p);
@@ -615,7 +619,7 @@
while (p < p_cfg_end) {
uint8_t cfg_code, cfg_len;
if (p + 2 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CMD_CONFIG_RSP sub_event");
+ log::warn("Not enough data for L2CAP_CMD_CONFIG_RSP sub_event");
return;
}
STREAM_TO_UINT8(cfg_code, p);
@@ -625,7 +629,7 @@
case L2CAP_CFG_TYPE_MTU:
cfg_info.mtu_present = true;
if (p + 2 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CFG_TYPE_MTU");
+ log::warn("Not enough data for L2CAP_CFG_TYPE_MTU");
return;
}
STREAM_TO_UINT16(cfg_info.mtu, p);
@@ -634,7 +638,7 @@
case L2CAP_CFG_TYPE_FLUSH_TOUT:
cfg_info.flush_to_present = true;
if (p + 2 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CFG_TYPE_FLUSH_TOUT");
+ log::warn("Not enough data for L2CAP_CFG_TYPE_FLUSH_TOUT");
return;
}
STREAM_TO_UINT16(cfg_info.flush_to, p);
@@ -643,7 +647,7 @@
case L2CAP_CFG_TYPE_QOS:
cfg_info.qos_present = true;
if (p + 2 + 5 * 4 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CFG_TYPE_QOS");
+ log::warn("Not enough data for L2CAP_CFG_TYPE_QOS");
return;
}
STREAM_TO_UINT8(cfg_info.qos.qos_flags, p);
@@ -658,7 +662,7 @@
case L2CAP_CFG_TYPE_FCR:
cfg_info.fcr_present = true;
if (p + 3 + 3 * 2 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CFG_TYPE_FCR");
+ log::warn("Not enough data for L2CAP_CFG_TYPE_FCR");
return;
}
STREAM_TO_UINT8(cfg_info.fcr.mode, p);
@@ -672,7 +676,7 @@
case L2CAP_CFG_TYPE_FCS:
cfg_info.fcs_present = true;
if (p + 1 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CFG_TYPE_FCS");
+ log::warn("Not enough data for L2CAP_CFG_TYPE_FCS");
return;
}
STREAM_TO_UINT8(cfg_info.fcs, p);
@@ -681,7 +685,7 @@
case L2CAP_CFG_TYPE_EXT_FLOW:
cfg_info.ext_flow_spec_present = true;
if (p + 2 + 2 + 3 * 4 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CFG_TYPE_EXT_FLOW");
+ log::warn("Not enough data for L2CAP_CFG_TYPE_EXT_FLOW");
return;
}
STREAM_TO_UINT8(cfg_info.ext_flow_spec.id, p);
@@ -697,7 +701,7 @@
tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(p_lcb, lcid);
if (p_ccb) {
if (p_ccb->local_id != id) {
- LOG_WARN("cfg rsp - bad ID. Exp: %d Got: %d", p_ccb->local_id, id);
+ log::warn("cfg rsp - bad ID. Exp: {} Got: {}", p_ccb->local_id, id);
break;
}
if (cfg_info.result == L2CAP_CFG_OK) {
@@ -706,7 +710,7 @@
l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONFIG_RSP_NEG, &cfg_info);
}
} else {
- LOG_WARN("Rcvd cfg rsp for unknown CID: 0x%04x", lcid);
+ log::warn("Rcvd cfg rsp for unknown CID: 0x{:04x}", lcid);
}
break;
}
@@ -714,7 +718,7 @@
case L2CAP_CMD_DISC_REQ: {
uint16_t lcid, rcid;
if (p + 4 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CMD_DISC_REQ");
+ log::warn("Not enough data for L2CAP_CMD_DISC_REQ");
return;
}
STREAM_TO_UINT16(lcid, p);
@@ -735,7 +739,7 @@
case L2CAP_CMD_DISC_RSP: {
uint16_t lcid, rcid;
if (p + 4 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CMD_DISC_RSP");
+ log::warn("Not enough data for L2CAP_CMD_DISC_RSP");
return;
}
STREAM_TO_UINT16(rcid, p);
@@ -757,7 +761,7 @@
case L2CAP_CMD_INFO_REQ: {
uint16_t info_type;
if (p + 2 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CMD_INFO_REQ");
+ log::warn("Not enough data for L2CAP_CMD_INFO_REQ");
return;
}
STREAM_TO_UINT16(info_type, p);
@@ -774,7 +778,7 @@
uint16_t info_type, result;
if (p + 4 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CMD_INFO_RSP");
+ log::warn("Not enough data for L2CAP_CMD_INFO_RSP");
return;
}
STREAM_TO_UINT16(info_type, p);
@@ -783,7 +787,7 @@
if ((info_type == L2CAP_EXTENDED_FEATURES_INFO_TYPE) &&
(result == L2CAP_INFO_RESP_RESULT_SUCCESS)) {
if (p + 4 > p_next_cmd) {
- LOG_WARN("Not enough data for L2CAP_CMD_INFO_RSP sub_event");
+ log::warn("Not enough data for L2CAP_CMD_INFO_RSP sub_event");
return;
}
STREAM_TO_UINT32(p_lcb->peer_ext_fea, p);
@@ -818,7 +822,7 @@
break;
default:
- LOG_WARN("Bad cmd code: %d", cmd_code);
+ log::warn("Bad cmd code: {}", cmd_code);
l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_NOT_UNDERSTOOD, id, 0,
0);
return;
@@ -906,7 +910,7 @@
/* Find the channel control block. We don't know the link it is on. */
tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
if (!p_ccb) {
- LOG_WARN("L2CAP - no CCB for L2CA_DataWrite, CID: %d", cid);
+ log::warn("L2CAP - no CCB for L2CA_DataWrite, CID: {}", cid);
osi_free(p_data);
return (L2CAP_DW_FAILED);
}
@@ -920,9 +924,9 @@
mtu = p_ccb->peer_cfg.mtu;
if (p_data->len > mtu) {
- LOG_WARN(
- "L2CAP - CID: 0x%04x cannot send message bigger than peer's mtu size: "
- "len=%u mtu=%u",
+ log::warn(
+ "L2CAP - CID: 0x{:04x} cannot send message bigger than peer's mtu "
+ "size: len={} mtu={}",
cid, p_data->len, mtu);
osi_free(p_data);
return (L2CAP_DW_FAILED);
@@ -933,9 +937,9 @@
/* If already congested, do not accept any more packets */
if (p_ccb->cong_sent) {
- LOG_ERROR(
- "L2CAP - CID: 0x%04x cannot send, already congested "
- "xmit_hold_q.count: %zu buff_quota: %u",
+ log::error(
+ "L2CAP - CID: 0x{:04x} cannot send, already congested "
+ "xmit_hold_q.count: {} buff_quota: {}",
p_ccb->local_cid, fixed_queue_length(p_ccb->xmit_hold_q),
p_ccb->buff_quota);
diff --git a/system/stack/l2cap/l2c_utils.cc b/system/stack/l2cap/l2c_utils.cc
index bdf4e66..f1e845e 100644
--- a/system/stack/l2cap/l2c_utils.cc
+++ b/system/stack/l2cap/l2c_utils.cc
@@ -24,6 +24,7 @@
#define LOG_TAG "l2c_utils"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <stdio.h>
#include <string.h>
@@ -47,6 +48,8 @@
#include "stack/l2cap/l2c_int.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
tL2C_CCB* l2cu_get_next_channel_in_rr(tL2C_LCB* p_lcb); // TODO Move
/*******************************************************************************
@@ -107,8 +110,8 @@
void l2cu_set_lcb_handle(struct t_l2c_linkcb& p_lcb, uint16_t handle) {
if (p_lcb.Handle() != HCI_INVALID_HANDLE) {
- LOG_WARN("Should not replace active handle:%hu with new handle:%hu",
- p_lcb.Handle(), handle);
+ log::warn("Should not replace active handle:{} with new handle:{}",
+ p_lcb.Handle(), handle);
}
p_lcb.SetHandle(handle);
}
@@ -127,8 +130,8 @@
tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(p_bd_addr, BT_TRANSPORT_BR_EDR);
if (p_lcb) {
- VLOG(1) << __func__ << " BDA: " << ADDRESS_TO_LOGGABLE_STR(p_bd_addr)
- << " is_bonding: " << is_bonding;
+ log::verbose("BDA: {} is_bonding: {}", ADDRESS_TO_LOGGABLE_STR(p_bd_addr),
+ is_bonding);
if (is_bonding) {
p_lcb->SetBonding();
} else {
@@ -277,7 +280,7 @@
case L2CAP_CMD_BLE_UPDATE_REQ:
l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_MTU_EXCEEDED, signal_id,
L2CAP_DEFAULT_MTU, 0);
- LOG_WARN("Dumping first Command (%d)", cmd_code);
+ log::warn("Dumping first Command ({})", cmd_code);
return true;
default: /* Otherwise a response */
@@ -372,7 +375,7 @@
p_buf = l2cu_build_header(p_lcb, (uint16_t)(L2CAP_CMD_REJECT_LEN + param_len),
L2CAP_CMD_REJECT, rem_id);
if (p_buf == NULL) {
- LOG_WARN("L2CAP - no buffer cmd_rej");
+ log::warn("L2CAP - no buffer cmd_rej");
return;
}
@@ -411,7 +414,7 @@
p_buf = l2cu_build_header(p_ccb->p_lcb, L2CAP_CONN_REQ_LEN,
L2CAP_CMD_CONN_REQ, p_ccb->local_id);
if (p_buf == NULL) {
- LOG_WARN("L2CAP - no buffer for conn_req");
+ log::warn("L2CAP - no buffer for conn_req");
return;
}
@@ -439,7 +442,7 @@
if (result == L2CAP_CONN_PENDING) {
/* if we already sent pending response */
if (p_ccb->flags & CCB_FLAG_SENT_PENDING) {
- LOG_DEBUG("Already sent connection pending, not sending again");
+ log::debug("Already sent connection pending, not sending again");
return;
} else {
p_ccb->flags |= CCB_FLAG_SENT_PENDING;
@@ -449,7 +452,7 @@
BT_HDR* p_buf = l2cu_build_header(p_ccb->p_lcb, L2CAP_CONN_RSP_LEN,
L2CAP_CMD_CONN_RSP, p_ccb->remote_id);
if (p_buf == nullptr) {
- LOG_WARN("no buffer for conn_rsp");
+ log::warn("no buffer for conn_rsp");
return;
}
@@ -483,7 +486,7 @@
p_buf =
l2cu_build_header(p_lcb, L2CAP_CONN_RSP_LEN, L2CAP_CMD_CONN_RSP, rem_id);
if (p_buf == NULL) {
- LOG_WARN("L2CAP - no buffer for conn_req");
+ log::warn("L2CAP - no buffer for conn_req");
return;
}
@@ -528,15 +531,15 @@
p_buf = l2cu_build_header(p_lcb, cmd_len, L2CAP_CMD_CREDIT_BASED_RECONFIG_REQ,
p_lcb->signal_id);
if (p_buf == NULL) {
- LOG_WARN("l2cu_send_reconfig_req - no buffer");
+ log::warn("l2cu_send_reconfig_req - no buffer");
return;
}
p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE +
L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD;
- LOG_VERBOSE("l2cu_send_reconfig_req number of cids: %d mtu:%d mps:%d",
- p_lcb->pending_ecoc_reconfig_cnt, p_cfg->mtu, p_cfg->mps);
+ log::verbose("l2cu_send_reconfig_req number of cids: {} mtu:{} mps:{}",
+ p_lcb->pending_ecoc_reconfig_cnt, p_cfg->mtu, p_cfg->mps);
UINT16_TO_STREAM(p, p_cfg->mtu);
UINT16_TO_STREAM(p, p_cfg->mps);
@@ -589,7 +592,7 @@
(uint16_t)(L2CAP_CONFIG_REQ_LEN + cfg_len),
L2CAP_CMD_CONFIG_REQ, p_ccb->local_id);
if (p_buf == NULL) {
- LOG_WARN("L2CAP - no buffer for conn_req");
+ log::warn("L2CAP - no buffer for conn_req");
return;
}
@@ -683,7 +686,7 @@
(uint16_t)(L2CAP_CONFIG_RSP_LEN + cfg_len),
L2CAP_CMD_CONFIG_RSP, p_ccb->remote_id);
if (p_buf == NULL) {
- LOG_WARN("L2CAP - no buffer for conn_req");
+ log::warn("L2CAP - no buffer for conn_req");
return;
}
@@ -758,14 +761,14 @@
uint8_t *p, *p_hci_len, *p_data_end;
uint8_t cfg_code;
- LOG_VERBOSE("l2cu_send_peer_config_rej: data_len=%d, rej_len=%d", data_len,
- rej_len);
+ log::verbose("l2cu_send_peer_config_rej: data_len={}, rej_len={}", data_len,
+ rej_len);
len = BT_HDR_SIZE + HCI_DATA_PREAMBLE_SIZE + L2CAP_PKT_OVERHEAD +
L2CAP_CMD_OVERHEAD + L2CAP_CONFIG_RSP_LEN;
len1 = 0xFFFF - len;
if (rej_len > len1) {
- LOG_ERROR("L2CAP - cfg_rej pkt size exceeds buffer design max limit.");
+ log::error("L2CAP - cfg_rej pkt size exceeds buffer design max limit.");
return;
}
@@ -831,7 +834,7 @@
p += cfg_len + L2CAP_CFG_OPTION_OVERHEAD;
buf_space -= (cfg_len + L2CAP_CFG_OPTION_OVERHEAD);
} else {
- LOG_WARN("L2CAP - cfg_rej exceeds allocated buffer");
+ log::warn("L2CAP - cfg_rej exceeds allocated buffer");
p_data = p_data_end; /* force loop exit */
break;
}
@@ -851,8 +854,8 @@
p_buf->len = len + 4;
- LOG_VERBOSE("L2CAP - cfg_rej pkt hci_len=%d, l2cap_len=%d", len,
- (L2CAP_CMD_OVERHEAD + L2CAP_CONFIG_RSP_LEN + rej_len));
+ log::verbose("L2CAP - cfg_rej pkt hci_len={}, l2cap_len={}", len,
+ (L2CAP_CMD_OVERHEAD + L2CAP_CONFIG_RSP_LEN + rej_len));
l2c_link_check_send_pkts(p_ccb->p_lcb, 0, p_buf);
}
@@ -872,7 +875,7 @@
uint8_t* p;
if ((!p_ccb) || (p_ccb->p_lcb == NULL)) {
- LOG_ERROR("%s L2CAP - ccb or lcb invalid", __func__);
+ log::error("L2CAP - ccb or lcb invalid");
return;
}
@@ -885,7 +888,7 @@
p_buf = l2cu_build_header(p_ccb->p_lcb, L2CAP_DISC_REQ_LEN,
L2CAP_CMD_DISC_REQ, p_ccb->local_id);
if (p_buf == NULL) {
- LOG_WARN("L2CAP - no buffer for disc_req");
+ log::warn("L2CAP - no buffer for disc_req");
return;
}
@@ -931,7 +934,7 @@
p_buf = l2cu_build_header(p_lcb, L2CAP_DISC_RSP_LEN, L2CAP_CMD_DISC_RSP,
remote_id);
if (p_buf == NULL) {
- LOG_WARN("L2CAP - no buffer for disc_rsp");
+ log::warn("L2CAP - no buffer for disc_rsp");
return;
}
@@ -963,7 +966,7 @@
* checking) */
if (!signal_id || signal_id == p_lcb->cur_echo_id) {
/* Dump this request since it is illegal */
- LOG_WARN("L2CAP ignoring duplicate echo request (%d)", signal_id);
+ log::warn("L2CAP ignoring duplicate echo request ({})", signal_id);
return;
} else
p_lcb->cur_echo_id = signal_id;
@@ -985,7 +988,7 @@
p_buf = l2cu_build_header(p_lcb, (uint16_t)(L2CAP_ECHO_RSP_LEN + data_len),
L2CAP_CMD_ECHO_RSP, signal_id);
if (p_buf == NULL) {
- LOG_WARN("L2CAP - no buffer for echo_rsp");
+ log::warn("L2CAP - no buffer for echo_rsp");
return;
}
@@ -1018,11 +1021,11 @@
p_buf = l2cu_build_header(p_lcb, 2, L2CAP_CMD_INFO_REQ, p_lcb->signal_id);
if (p_buf == NULL) {
- LOG_WARN("L2CAP - no buffer for info_req");
+ log::warn("L2CAP - no buffer for info_req");
return;
}
- LOG_VERBOSE("l2cu_send_peer_info_req: type 0x%04x", info_type);
+ log::verbose("l2cu_send_peer_info_req: type 0x{:04x}", info_type);
p = (uint8_t*)(p_buf + 1) + L2CAP_SEND_CMD_OFFSET + HCI_DATA_PREAMBLE_SIZE +
L2CAP_PKT_OVERHEAD + L2CAP_CMD_OVERHEAD;
@@ -1076,7 +1079,7 @@
p_buf = l2cu_build_header(p_lcb, len, L2CAP_CMD_INFO_RSP, remote_id);
if (p_buf == NULL) {
- LOG_WARN("L2CAP - no buffer for info_rsp");
+ log::warn("L2CAP - no buffer for info_rsp");
return;
}
@@ -1162,13 +1165,13 @@
if (p_ccb->p_lcb != NULL) p_q = &p_ccb->p_lcb->ccb_queue;
if ((!p_ccb->in_use) || (p_q == NULL)) {
- LOG_ERROR("%s: CID: 0x%04x ERROR in_use: %u p_lcb: %p", __func__,
- p_ccb->local_cid, p_ccb->in_use, p_ccb->p_lcb);
+ log::error("CID: 0x{:04x} ERROR in_use: {} p_lcb: {}", p_ccb->local_cid,
+ p_ccb->in_use, fmt::ptr(p_ccb->p_lcb));
return;
}
- LOG_VERBOSE("l2cu_enqueue_ccb CID: 0x%04x priority: %d", p_ccb->local_cid,
- p_ccb->ccb_priority);
+ log::verbose("l2cu_enqueue_ccb CID: 0x{:04x} priority: {}", p_ccb->local_cid,
+ p_ccb->ccb_priority);
/* If the queue is empty, we go at the front */
if (!p_q->p_first_ccb) {
@@ -1236,18 +1239,18 @@
void l2cu_dequeue_ccb(tL2C_CCB* p_ccb) {
tL2C_CCB_Q* p_q = NULL;
- LOG_VERBOSE("l2cu_dequeue_ccb CID: 0x%04x", p_ccb->local_cid);
+ log::verbose("l2cu_dequeue_ccb CID: 0x{:04x}", p_ccb->local_cid);
/* Find out which queue the channel is on
*/
if (p_ccb->p_lcb != NULL) p_q = &p_ccb->p_lcb->ccb_queue;
if ((!p_ccb->in_use) || (p_q == NULL) || (p_q->p_first_ccb == NULL)) {
- LOG_ERROR(
- "l2cu_dequeue_ccb CID: 0x%04x ERROR in_use: %u p_lcb: 0x%p p_q: "
- "0x%p p_q->p_first_ccb: 0x%p",
- p_ccb->local_cid, p_ccb->in_use, p_ccb->p_lcb, p_q,
- p_q ? p_q->p_first_ccb : 0);
+ log::error(
+ "l2cu_dequeue_ccb CID: 0x{:04x} ERROR in_use: {} p_lcb: 0x{} p_q: "
+ "0x{} p_q->p_first_ccb: 0x{}",
+ p_ccb->local_cid, p_ccb->in_use, fmt::ptr(p_ccb->p_lcb), fmt::ptr(p_q),
+ fmt::ptr(p_q ? p_q->p_first_ccb : 0));
return;
}
@@ -1309,7 +1312,7 @@
if (p_ccb->ccb_priority != priority) {
/* If CCB is not the only guy on the queue */
if ((p_ccb->p_next_ccb != NULL) || (p_ccb->p_prev_ccb != NULL)) {
- LOG_VERBOSE("Update CCB list in logical link");
+ log::verbose("Update CCB list in logical link");
/* Remove CCB from queue and re-queue it at new priority */
l2cu_dequeue_ccb(p_ccb);
@@ -1347,9 +1350,9 @@
*
******************************************************************************/
tL2C_CCB* l2cu_allocate_ccb(tL2C_LCB* p_lcb, uint16_t cid, bool is_eatt) {
- LOG_DEBUG("is_dynamic = %d, cid 0x%04x", p_lcb != nullptr, cid);
+ log::debug("is_dynamic = {}, cid 0x{:04x}", p_lcb != nullptr, cid);
if (!l2cb.p_free_ccb_first) {
- LOG_ERROR("First free ccb is null for cid 0x%04x", cid);
+ log::error("First free ccb is null for cid 0x{:04x}", cid);
return nullptr;
}
tL2C_CCB* p_ccb;
@@ -1378,7 +1381,7 @@
}
}
if (p_prev == nullptr) {
- LOG_ERROR("Could not find CCB for CID 0x%04x in the free list", cid);
+ log::error("Could not find CCB for CID 0x{:04x} in the free list", cid);
return nullptr;
}
}
@@ -1448,7 +1451,7 @@
if (cid == 0) {
p_ccb->config_done = 0;
} else {
- LOG_DEBUG("cid 0x%04x config_done:0x%x", cid, p_ccb->config_done);
+ log::debug("cid 0x{:04x} config_done:0x{:x}", cid, p_ccb->config_done);
}
p_ccb->chnl_state = CST_CLOSED;
@@ -1493,14 +1496,15 @@
bool l2cu_start_post_bond_timer(uint16_t handle) {
tL2C_LCB* p_lcb = l2cu_find_lcb_by_handle(handle);
if (p_lcb == nullptr) {
- LOG_WARN("Unable to find link control block for handle:0x%04x", handle);
+ log::warn("Unable to find link control block for handle:0x{:04x}", handle);
return true;
}
p_lcb->ResetBonding();
/* Only start timer if no control blocks allocated */
if (p_lcb->ccb_queue.p_first_ccb != nullptr) {
- LOG_DEBUG("Unable to start post bond timer with existing dynamic channels");
+ log::debug(
+ "Unable to start post bond timer with existing dynamic channels");
return false;
}
@@ -1520,13 +1524,13 @@
}
alarm_set_on_mloop(p_lcb->l2c_lcb_timer, timeout_ms,
l2c_lcb_timer_timeout, p_lcb);
- LOG_DEBUG("Started link IDLE timeout_ms:%lu", (unsigned long)timeout_ms);
+ log::debug("Started link IDLE timeout_ms:{}", (unsigned long)timeout_ms);
return true;
} break;
default:
- LOG_DEBUG("Will not start post bond timer with link state:%s",
- link_state_text(p_lcb->link_state).c_str());
+ log::debug("Will not start post bond timer with link state:{}",
+ link_state_text(p_lcb->link_state));
break;
}
return false;
@@ -1547,8 +1551,8 @@
tL2C_LCB* p_lcb = p_ccb->p_lcb;
tL2C_RCB* p_rcb = p_ccb->p_rcb;
- LOG_VERBOSE("l2cu_release_ccb: cid 0x%04x in_use: %u", p_ccb->local_cid,
- p_ccb->in_use);
+ log::verbose("l2cu_release_ccb: cid 0x{:04x} in_use: {}", p_ccb->local_cid,
+ p_ccb->in_use);
/* If already released, could be race condition */
if (!p_ccb->in_use) return;
@@ -1622,7 +1626,7 @@
if (!p_lcb->ccb_queue.p_first_ccb) {
if (p_lcb->transport == BT_TRANSPORT_LE &&
p_ccb->local_cid == L2CAP_ATT_CID) {
- LOG_WARN("%s - disconnecting the LE link", __func__);
+ log::warn("disconnecting the LE link");
l2cu_no_dynamic_ccbs(p_lcb);
}
}
@@ -1752,7 +1756,7 @@
tL2CA_DISCONNECT_IND_CB* p_disc_cb =
p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb;
- LOG_WARN("L2CAP - disconnect_chnl CID: 0x%04x", local_cid);
+ log::warn("L2CAP - disconnect_chnl CID: 0x{:04x}", local_cid);
l2cu_send_peer_disc_req(p_ccb);
@@ -1761,7 +1765,7 @@
(*p_disc_cb)(local_cid, false);
} else {
/* failure on the AMP channel, probably need to disconnect ACL */
- LOG_ERROR("L2CAP - disconnect_chnl CID: 0x%04x Ignored", local_cid);
+ log::error("L2CAP - disconnect_chnl CID: 0x{:04x} Ignored", local_cid);
}
}
@@ -1964,9 +1968,9 @@
else
p_ccb->fcrb.max_held_acks = p_ccb->our_cfg.fcr.tx_win_sz / 3;
- LOG_VERBOSE(
- "l2cu_process_peer_cfg_rsp(): peer tx_win_sz: %d, our tx_win_sz: %d, "
- "max_held_acks: %d",
+ log::verbose(
+ "l2cu_process_peer_cfg_rsp(): peer tx_win_sz: {}, our tx_win_sz: {}, "
+ "max_held_acks: {}",
p_cfg->fcr.tx_win_sz, p_ccb->our_cfg.fcr.tx_win_sz,
p_ccb->fcrb.max_held_acks);
}
@@ -2084,8 +2088,7 @@
if (p_lcb_cur == p_lcb) continue;
if (!p_lcb_cur->in_use) continue;
if (BTM_IsScoActiveByBdaddr(p_lcb_cur->remote_bd_addr)) {
- LOG_VERBOSE("%s Central peripheral switch not allowed when SCO active",
- __func__);
+ log::verbose("Central peripheral switch not allowed when SCO active");
continue;
}
if (p_lcb->IsLinkRoleCentral()) continue;
@@ -2241,16 +2244,16 @@
// priority to high, if using latency mode check preset latency
if (p_lcb->use_latency_mode &&
p_lcb->preset_acl_latency == L2CAP_LATENCY_LOW) {
- LOG_INFO("Set ACL priority: High Priority and Low Latency Mode");
+ log::info("Set ACL priority: High Priority and Low Latency Mode");
vs_param = HCI_BRCM_ACL_HIGH_PRIORITY_LOW_LATENCY;
p_lcb->set_latency(L2CAP_LATENCY_LOW);
} else {
- LOG_INFO("Set ACL priority: High Priority Mode");
+ log::info("Set ACL priority: High Priority Mode");
vs_param = HCI_BRCM_ACL_HIGH_PRIORITY;
}
} else {
// priority to normal
- LOG_INFO("Set ACL priority: Normal Mode");
+ log::info("Set ACL priority: Normal Mode");
vs_param = HCI_BRCM_ACL_NORMAL_PRIORITY;
p_lcb->set_latency(L2CAP_LATENCY_NORMAL);
}
@@ -2282,16 +2285,16 @@
// priority to high, if using latency mode check preset latency
if (p_lcb->use_latency_mode &&
p_lcb->preset_acl_latency == L2CAP_LATENCY_LOW) {
- LOG_INFO("Set ACL priority: High Priority and Low Latency Mode");
+ log::info("Set ACL priority: High Priority and Low Latency Mode");
vs_param = HCI_SYNA_ACL_HIGH_PRIORITY_LOW_LATENCY;
p_lcb->set_latency(L2CAP_LATENCY_LOW);
} else {
- LOG_INFO("Set ACL priority: High Priority Mode");
+ log::info("Set ACL priority: High Priority Mode");
vs_param = HCI_SYNA_ACL_HIGH_PRIORITY;
}
} else {
// priority to normal
- LOG_INFO("Set ACL priority: Normal Mode");
+ log::info("Set ACL priority: Normal Mode");
vs_param = HCI_SYNA_ACL_NORMAL_PRIORITY;
p_lcb->set_latency(L2CAP_LATENCY_NORMAL);
}
@@ -2320,11 +2323,11 @@
uint8_t vs_param;
if (priority == L2CAP_PRIORITY_HIGH) {
// priority to high
- LOG_INFO("Set ACL priority: High Priority Mode");
+ log::info("Set ACL priority: High Priority Mode");
vs_param = HCI_UNISOC_ACL_HIGH_PRIORITY;
} else {
// priority to normal
- LOG_INFO("Set ACL priority: Normal Mode");
+ log::info("Set ACL priority: Normal Mode");
vs_param = HCI_UNISOC_ACL_NORMAL_PRIORITY;
}
@@ -2353,11 +2356,11 @@
uint8_t vs_param;
if (priority == L2CAP_PRIORITY_HIGH) {
// priority to high, if using latency mode check preset latency
- LOG_INFO("Set ACL priority: High Priority Mode");
+ log::info("Set ACL priority: High Priority Mode");
vs_param = HCI_MTK_ACL_HIGH_PRIORITY;
} else {
// priority to normal
- LOG_INFO("Set ACL priority: Normal Mode");
+ log::info("Set ACL priority: Normal Mode");
vs_param = HCI_MTK_ACL_NORMAL_PRIORITY;
}
@@ -2381,12 +2384,12 @@
bool reset_after_rs) {
tL2C_LCB* p_lcb;
- LOG_VERBOSE("SET ACL PRIORITY %d", priority);
+ log::verbose("SET ACL PRIORITY {}", priority);
/* Find the link control block for the acl channel */
p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_BR_EDR);
if (p_lcb == NULL) {
- LOG_WARN("L2CAP - no LCB for L2CA_SetAclPriority");
+ log::warn("L2CAP - no LCB for L2CA_SetAclPriority");
return (false);
}
@@ -2440,8 +2443,8 @@
******************************************************************************/
static void l2cu_set_acl_latency_brcm(tL2C_LCB* p_lcb, tL2CAP_LATENCY latency) {
- LOG_INFO("Set ACL latency: %s",
- latency == L2CAP_LATENCY_LOW ? "Low Latancy" : "Normal Latency");
+ log::info("Set ACL latency: {}",
+ latency == L2CAP_LATENCY_LOW ? "Low Latancy" : "Normal Latency");
uint8_t command[HCI_BRCM_ACL_PRIORITY_PARAM_SIZE];
uint8_t* pp = command;
@@ -2466,8 +2469,8 @@
******************************************************************************/
static void l2cu_set_acl_latency_syna(tL2C_LCB* p_lcb, tL2CAP_LATENCY latency) {
- LOG_INFO("Set ACL latency: %s",
- latency == L2CAP_LATENCY_LOW ? "Low Latancy" : "Normal Latency");
+ log::info("Set ACL latency: {}",
+ latency == L2CAP_LATENCY_LOW ? "Low Latancy" : "Normal Latency");
uint8_t command[HCI_SYNA_ACL_PRIORITY_PARAM_SIZE];
uint8_t* pp = command;
@@ -2492,13 +2495,13 @@
******************************************************************************/
bool l2cu_set_acl_latency(const RawAddress& bd_addr, tL2CAP_LATENCY latency) {
- LOG_INFO("Set ACL low latency: %d", latency);
+ log::info("Set ACL low latency: {}", latency);
/* Find the link control block for the acl channel */
tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_BR_EDR);
if (p_lcb == nullptr) {
- LOG_WARN("Set latency failed: LCB is null");
+ log::warn("Set latency failed: LCB is null");
return false;
}
/* only change controller's latency when stream using latency mode */
@@ -2558,7 +2561,7 @@
tL2C_CCB* p_next_ccb;
int xx;
- LOG_VERBOSE("l2cu_resubmit_pending_sec_req p_bda: 0x%p", p_bda);
+ log::verbose("l2cu_resubmit_pending_sec_req p_bda: 0x{}", fmt::ptr(p_bda));
/* If we are called with a BDA, only resubmit for that BDA */
if (p_bda) {
@@ -2572,7 +2575,7 @@
l2c_csm_execute(p_ccb, L2CEVT_SEC_RE_SEND_CMD, NULL);
}
} else {
- LOG_WARN("l2cu_resubmit_pending_sec_req - unknown BD_ADDR");
+ log::warn("l2cu_resubmit_pending_sec_req - unknown BD_ADDR");
}
} else {
/* No BDA pasesed in, so check all links */
@@ -2621,8 +2624,8 @@
if (packet_size <= (L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD +
L2CAP_SDU_LEN_OVERHEAD + L2CAP_FCS_LEN)) {
/* something is very wrong */
- LOG_ERROR("l2cu_adjust_out_mps bad packet size: %u will use MPS: %u",
- packet_size, p_ccb->peer_cfg.fcr.mps);
+ log::error("l2cu_adjust_out_mps bad packet size: {} will use MPS: {}",
+ packet_size, p_ccb->peer_cfg.fcr.mps);
p_ccb->tx_mps = p_ccb->peer_cfg.fcr.mps;
} else {
packet_size -= (L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD +
@@ -2644,9 +2647,9 @@
else
p_ccb->tx_mps = p_ccb->peer_cfg.fcr.mps;
- LOG_VERBOSE(
- "l2cu_adjust_out_mps use %d Based on peer_cfg.fcr.mps: %u "
- "packet_size: %u",
+ log::verbose(
+ "l2cu_adjust_out_mps use {} Based on peer_cfg.fcr.mps: {} "
+ "packet_size: {}",
p_ccb->tx_mps, p_ccb->peer_cfg.fcr.mps, packet_size);
}
}
@@ -2679,8 +2682,9 @@
if (p_lcb->link_state == LST_DISCONNECTED) {
alarm_cancel(p_lcb->l2c_lcb_timer);
} else {
- LOG_WARN("Unable to cancel link control block for link connection to device %s",
- ADDRESS_TO_LOGGABLE_CSTR(p_lcb->remote_bd_addr));
+ log::warn(
+ "Unable to cancel link control block for link connection to device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_lcb->remote_bd_addr));
}
/* Set CID for the connection */
@@ -2726,8 +2730,8 @@
(p_lcb->p_fixed_ccbs[xx]->fixed_chnl_idle_tout * 1000 > timeout_ms)) {
if (p_lcb->p_fixed_ccbs[xx]->fixed_chnl_idle_tout ==
L2CAP_NO_IDLE_TIMEOUT) {
- LOG_VERBOSE("%s NO IDLE timeout set for fixed cid 0x%04x", __func__,
- p_lcb->p_fixed_ccbs[xx]->local_cid);
+ log::verbose("NO IDLE timeout set for fixed cid 0x{:04x}",
+ p_lcb->p_fixed_ccbs[xx]->local_cid);
start_timeout = false;
}
timeout_ms = p_lcb->p_fixed_ccbs[xx]->fixed_chnl_idle_tout * 1000;
@@ -2737,8 +2741,8 @@
/* If the link is pairing, do not mess with the timeouts */
if (p_lcb->IsBonding()) return;
- LOG_VERBOSE("l2cu_no_dynamic_ccbs() with_active_local_clients=%d",
- p_lcb->with_active_local_clients);
+ log::verbose("l2cu_no_dynamic_ccbs() with_active_local_clients={}",
+ p_lcb->with_active_local_clients);
// Inactive connections should not timeout, since the ATT channel might still
// be in use even without a GATT client. We only timeout if either a dynamic
// channel or a GATT client was used, since then we expect the client to
@@ -2748,7 +2752,7 @@
}
if (timeout_ms == 0) {
- LOG_VERBOSE("l2cu_no_dynamic_ccbs() IDLE timer 0, disconnecting link");
+ log::verbose("l2cu_no_dynamic_ccbs() IDLE timer 0, disconnecting link");
rc = btm_sec_disconnect(
p_lcb->Handle(), HCI_ERR_PEER_USER,
@@ -2779,7 +2783,7 @@
if (start_timeout) {
alarm_set_on_mloop(p_lcb->l2c_lcb_timer, timeout_ms, l2c_lcb_timer_timeout,
p_lcb);
- LOG_DEBUG("Started link IDLE timeout_ms:%lu", (unsigned long)timeout_ms);
+ log::debug("Started link IDLE timeout_ms:{}", (unsigned long)timeout_ms);
} else {
alarm_cancel(p_lcb->l2c_lcb_timer);
}
@@ -2898,7 +2902,7 @@
p_buf = l2cu_build_header(p_lcb, L2CAP_CMD_BLE_UPD_REQ_LEN,
L2CAP_CMD_BLE_UPDATE_REQ, p_lcb->signal_id);
if (p_buf == NULL) {
- LOG_WARN("l2cu_send_peer_ble_par_req - no buffer");
+ log::warn("l2cu_send_peer_ble_par_req - no buffer");
return;
}
@@ -2931,7 +2935,7 @@
p_buf = l2cu_build_header(p_lcb, L2CAP_CMD_BLE_UPD_RSP_LEN,
L2CAP_CMD_BLE_UPDATE_RSP, rem_id);
if (p_buf == NULL) {
- LOG_WARN("l2cu_send_peer_ble_par_rsp - no buffer");
+ log::warn("l2cu_send_peer_ble_par_rsp - no buffer");
return;
}
@@ -2974,7 +2978,7 @@
l2cu_build_header(p_lcb, L2CAP_CMD_BLE_CREDIT_BASED_CONN_REQ_LEN,
L2CAP_CMD_BLE_CREDIT_BASED_CONN_REQ, p_lcb->signal_id);
if (p_buf == NULL) {
- LOG_WARN("l2cu_send_peer_ble_credit_based_conn_req - no buffer");
+ log::warn("l2cu_send_peer_ble_credit_based_conn_req - no buffer");
return;
}
@@ -2985,9 +2989,9 @@
mps = p_ccb->local_conn_cfg.mps;
initial_credit = p_ccb->local_conn_cfg.credits;
- LOG_VERBOSE(
- "l2cu_send_peer_ble_credit_based_conn_req PSM:0x%04x local_cid:%d"
- " mtu:%d mps:%d initial_credit:%d",
+ log::verbose(
+ "l2cu_send_peer_ble_credit_based_conn_req PSM:0x{:04x} local_cid:{} "
+ "mtu:{} mps:{} initial_credit:{}",
p_ccb->p_rcb->real_psm, p_ccb->local_cid, mtu, mps, initial_credit);
UINT16_TO_STREAM(p, p_ccb->p_rcb->real_psm);
@@ -3032,7 +3036,7 @@
2 * p_lcb->pending_ecoc_conn_cnt,
L2CAP_CMD_CREDIT_BASED_CONN_REQ, p_ccb->local_id);
if (p_buf == NULL) {
- LOG_WARN("%s - no buffer", __func__);
+ log::warn("no buffer");
return;
}
@@ -3043,9 +3047,9 @@
mps = p_ccb->local_conn_cfg.mps;
initial_credit = p_ccb->local_conn_cfg.credits;
- LOG_VERBOSE("%s PSM:0x%04x mtu:%d mps:%d initial_credit:%d, cids_cnt %d",
- __func__, p_ccb->p_rcb->real_psm, mtu, mps, initial_credit,
- p_lcb->pending_ecoc_conn_cnt);
+ log::verbose("PSM:0x{:04x} mtu:{} mps:{} initial_credit:{}, cids_cnt {}",
+ p_ccb->p_rcb->real_psm, mtu, mps, initial_credit,
+ p_lcb->pending_ecoc_conn_cnt);
UINT16_TO_STREAM(p, p_ccb->p_rcb->real_psm);
UINT16_TO_STREAM(p, mtu);
@@ -3054,7 +3058,7 @@
for (int i = 0; i < p_lcb->pending_ecoc_conn_cnt; i++) {
uint16_t cid = p_lcb->pending_ecoc_connection_cids[i];
- LOG_VERBOSE("\n\t cid: %d", cid);
+ log::verbose(" cid: {}", cid);
UINT16_TO_STREAM(p, cid);
}
@@ -3080,7 +3084,7 @@
p_buf = l2cu_build_header(p_lcb, L2CAP_CMD_BLE_CREDIT_BASED_CONN_RES_LEN,
L2CAP_CMD_BLE_CREDIT_BASED_CONN_RES, rem_id);
if (p_buf == NULL) {
- LOG_WARN("l2cu_reject_ble_coc_connection - no buffer");
+ log::warn("l2cu_reject_ble_coc_connection - no buffer");
return;
}
@@ -3117,7 +3121,7 @@
p_buf = l2cu_build_header(p_lcb, rsp_len, L2CAP_CMD_CREDIT_BASED_CONN_RES,
rem_id);
if (p_buf == NULL) {
- LOG_WARN("l2cu_reject_credit_based_conn_req - no buffer");
+ log::warn("l2cu_reject_credit_based_conn_req - no buffer");
return;
}
@@ -3150,14 +3154,14 @@
BT_HDR* p_buf;
uint8_t* p;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
uint8_t rsp_len = L2CAP_CMD_CREDIT_BASED_CONN_RES_MIN_LEN +
p_ccb->p_lcb->pending_ecoc_conn_cnt * sizeof(uint16_t);
p_buf = l2cu_build_header(p_ccb->p_lcb, rsp_len,
L2CAP_CMD_CREDIT_BASED_CONN_RES, p_ccb->remote_id);
if (p_buf == NULL) {
- LOG_WARN("%s - no buffer", __func__);
+ log::warn("no buffer");
return;
}
@@ -3239,12 +3243,12 @@
BT_HDR* p_buf;
uint8_t* p;
- LOG_VERBOSE("l2cu_send_ble_reconfig_rsp result 0x04%x", result);
+ log::verbose("l2cu_send_ble_reconfig_rsp result 0x04{:x}", result);
p_buf = l2cu_build_header(p_lcb, L2CAP_CMD_CREDIT_BASED_RECONFIG_RES_LEN,
L2CAP_CMD_CREDIT_BASED_RECONFIG_RES, rem_id);
if (p_buf == NULL) {
- LOG_WARN("l2cu_send_peer_ble_credit_based_conn_res - no buffer");
+ log::warn("l2cu_send_peer_ble_credit_based_conn_res - no buffer");
return;
}
@@ -3273,12 +3277,12 @@
BT_HDR* p_buf;
uint8_t* p;
- LOG_VERBOSE("l2cu_send_peer_ble_credit_based_conn_res");
+ log::verbose("l2cu_send_peer_ble_credit_based_conn_res");
p_buf =
l2cu_build_header(p_ccb->p_lcb, L2CAP_CMD_BLE_CREDIT_BASED_CONN_RES_LEN,
L2CAP_CMD_BLE_CREDIT_BASED_CONN_RES, p_ccb->remote_id);
if (p_buf == NULL) {
- LOG_WARN("l2cu_send_peer_ble_credit_based_conn_res - no buffer");
+ log::warn("l2cu_send_peer_ble_credit_based_conn_res - no buffer");
return;
}
@@ -3322,7 +3326,7 @@
p_buf = l2cu_build_header(p_lcb, L2CAP_CMD_BLE_FLOW_CTRL_CREDIT_LEN,
L2CAP_CMD_BLE_FLOW_CTRL_CREDIT, p_lcb->signal_id);
if (p_buf == NULL) {
- LOG_WARN("l2cu_send_peer_ble_credit_based_conn_req - no buffer");
+ log::warn("l2cu_send_peer_ble_credit_based_conn_req - no buffer");
return;
}
@@ -3349,7 +3353,7 @@
BT_HDR* p_buf;
uint8_t* p;
tL2C_LCB* p_lcb = NULL;
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
if (!p_ccb) return;
p_lcb = p_ccb->p_lcb;
@@ -3362,7 +3366,7 @@
p_buf = l2cu_build_header(p_lcb, L2CAP_DISC_REQ_LEN, L2CAP_CMD_DISC_REQ,
p_lcb->signal_id);
if (p_buf == NULL) {
- LOG_WARN("l2cu_send_peer_ble_credit_based_disconn_req - no buffer");
+ log::warn("l2cu_send_peer_ble_credit_based_disconn_req - no buffer");
return;
}
@@ -3496,9 +3500,9 @@
p_ccb->cong_sent = status;
if (p_ccb->p_rcb && p_ccb->p_rcb->api.pL2CA_CongestionStatus_Cb) {
- LOG_VERBOSE(
- "L2CAP - Calling CongestionStatus_Cb (%d), CID: 0x%04x "
- "xmit_hold_q.count: %zu buff_quota: %u",
+ log::verbose(
+ "L2CAP - Calling CongestionStatus_Cb ({}), CID: 0x{:04x} "
+ "xmit_hold_q.count: {} buff_quota: {}",
status, p_ccb->local_cid, fixed_queue_length(p_ccb->xmit_hold_q),
p_ccb->buff_quota);
diff --git a/system/stack/pan/pan_api.cc b/system/stack/pan/pan_api.cc
index 52db9ad..0e6aaaa 100644
--- a/system/stack/pan/pan_api.cc
+++ b/system/stack/pan/pan_api.cc
@@ -29,6 +29,7 @@
#include <base/logging.h>
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <cstdint>
#include <cstring>
@@ -47,6 +48,7 @@
#include "types/bluetooth/uuid.h"
#include "types/raw_address.h"
+using namespace bluetooth;
using namespace bluetooth::legacy::stack::sdp;
using bluetooth::Uuid;
@@ -153,18 +155,18 @@
/* If the role is not a valid combination reject it */
if ((!(role & (PAN_ROLE_CLIENT | PAN_ROLE_NAP_SERVER))) &&
role != PAN_ROLE_INACTIVE) {
- LOG_ERROR("PAN role %d is invalid", role);
+ log::error("PAN role {} is invalid", role);
return PAN_FAILURE;
}
/* If the current active role is same as the role being set do nothing */
if (pan_cb.role == role) {
- LOG_VERBOSE("PAN role already was set to: %d", role);
+ log::verbose("PAN role already was set to: {}", role);
return PAN_SUCCESS;
}
/* Register all the roles with SDP */
- LOG_VERBOSE("PAN_SetRole() called with role 0x%x", role);
+ log::verbose("PAN_SetRole() called with role 0x{:x}", role);
if (role & PAN_ROLE_NAP_SERVER) {
/* Check the service name */
if (p_nap_name.empty())
@@ -222,7 +224,7 @@
}
pan_cb.role = role;
- LOG_VERBOSE("PAN role set to: %d", role);
+ log::verbose("PAN role set to: {}", role);
BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Role change",
base::StringPrintf("role:0x%x", role));
@@ -264,15 +266,15 @@
/* Check if PAN is active or not */
if (!(pan_cb.role & src_role)) {
- LOG_ERROR("PAN is not active for the role %d", src_role);
+ log::error("PAN is not active for the role {}", src_role);
return PAN_FAILURE;
}
/* Validate the parameters before proceeding */
if ((src_role != PAN_ROLE_CLIENT && src_role != PAN_ROLE_NAP_SERVER) ||
(dst_role != PAN_ROLE_CLIENT && dst_role != PAN_ROLE_NAP_SERVER)) {
- LOG_ERROR("Either source %d or destination role %d is invalid", src_role,
- dst_role);
+ log::error("Either source {} or destination role {} is invalid", src_role,
+ dst_role);
return PAN_FAILURE;
}
@@ -288,7 +290,7 @@
** because if there is already a connection we cannot accept
** another connection in PANU role
*/
- LOG_ERROR(
+ log::error(
"Cannot make PANU connections when there are more than one "
"connection");
return PAN_INVALID_SRC_ROLE;
@@ -305,7 +307,7 @@
/* If destination is PANU role validate source role */
else if (dst_role == PAN_ROLE_CLIENT) {
if (pan_cb.num_conns && pan_cb.active_role == PAN_ROLE_CLIENT && !pcb) {
- LOG_ERROR("Device already have a connection in PANU role");
+ log::error("Device already have a connection in PANU role");
return PAN_INVALID_SRC_ROLE;
}
@@ -315,19 +317,19 @@
}
/* The role combination is not valid */
else {
- LOG_ERROR("Source %d and Destination roles %d are not valid combination",
- src_role, dst_role);
+ log::error("Source {} and Destination roles {} are not valid combination",
+ src_role, dst_role);
return PAN_FAILURE;
}
/* Allocate control block and initiate connection */
if (!pcb) pcb = pan_allocate_pcb(rem_bda, BNEP_INVALID_HANDLE);
if (!pcb) {
- LOG_ERROR("PAN Connection failed because of no resources");
+ log::error("PAN Connection failed because of no resources");
return PAN_NO_RESOURCES;
}
- VLOG(0) << __func__ << " for BD Addr: " << rem_bda;
+ log::verbose("for BD Addr: {}", ADDRESS_TO_LOGGABLE_STR(rem_bda));
if (pcb->con_state == PAN_STATE_IDLE) {
pan_cb.num_conns++;
} else if (pcb->con_state == PAN_STATE_CONNECTED) {
@@ -351,7 +353,7 @@
return (tPAN_RESULT)ret;
}
- LOG_VERBOSE("PAN_Connect() current active role set to %d", src_role);
+ log::verbose("PAN_Connect() current active role set to {}", src_role);
pan_cb.prv_active_role = pan_cb.active_role;
pan_cb.active_role = src_role;
*handle = pcb->handle;
@@ -379,7 +381,7 @@
/* Check if the connection exists */
pcb = pan_get_pcb_by_handle(handle);
if (!pcb) {
- LOG_ERROR("PAN connection not found for the handle %d", handle);
+ log::error("PAN connection not found for the handle {}", handle);
return PAN_FAILURE;
}
@@ -394,11 +396,11 @@
pan_release_pcb(pcb);
if (result != BNEP_SUCCESS) {
- LOG_VERBOSE("Error in closing PAN connection");
+ log::verbose("Error in closing PAN connection");
return PAN_FAILURE;
}
- LOG_VERBOSE("PAN connection closed");
+ log::verbose("PAN connection closed");
return PAN_SUCCESS;
}
@@ -429,7 +431,7 @@
const RawAddress& src, uint16_t protocol, uint8_t* p_data,
uint16_t len, bool ext) {
if (pan_cb.role == PAN_ROLE_INACTIVE || !pan_cb.num_conns) {
- LOG_ERROR("%s PAN is not active, data write failed.", __func__);
+ log::error("PAN is not active, data write failed.");
return PAN_FAILURE;
}
@@ -486,7 +488,7 @@
tBNEP_RESULT result;
if (pan_cb.role == PAN_ROLE_INACTIVE || (!(pan_cb.num_conns))) {
- LOG_ERROR("PAN is not active Data write failed");
+ log::error("PAN is not active Data write failed");
osi_free(p_buf);
return PAN_FAILURE;
}
@@ -513,7 +515,7 @@
}
if (i == MAX_PAN_CONNS) {
- LOG_ERROR("PAN Don't have any user connections");
+ log::error("PAN Don't have any user connections");
osi_free(p_buf);
return PAN_FAILURE;
}
@@ -521,30 +523,30 @@
result =
BNEP_WriteBuf(pan_cb.pcb[i].handle, dst, p_buf, protocol, src, ext);
if (result == BNEP_IGNORE_CMD) {
- LOG_VERBOSE("PAN ignored data write for PANU connection");
+ log::verbose("PAN ignored data write for PANU connection");
return (tPAN_RESULT)result;
} else if (result != BNEP_SUCCESS) {
- LOG_ERROR("PAN failed to write data for the PANU connection");
+ log::error("PAN failed to write data for the PANU connection");
return (tPAN_RESULT)result;
}
pan_cb.pcb[i].write.octets += p_buf->len;
pan_cb.pcb[i].write.packets++;
- LOG_VERBOSE("PAN successfully wrote data for the PANU connection");
+ log::verbose("PAN successfully wrote data for the PANU connection");
return PAN_SUCCESS;
}
/* findout to which connection the data is meant for */
pcb = pan_get_pcb_by_handle(handle);
if (!pcb) {
- LOG_ERROR("PAN Buf write for wrong handle");
+ log::error("PAN Buf write for wrong handle");
osi_free(p_buf);
return PAN_FAILURE;
}
if (pcb->con_state != PAN_STATE_CONNECTED) {
- LOG_ERROR("PAN Buf write when conn is not active");
+ log::error("PAN Buf write when conn is not active");
pcb->write.drops++;
osi_free(p_buf);
return PAN_FAILURE;
@@ -553,11 +555,11 @@
uint16_t len = p_buf->len;
result = BNEP_WriteBuf(pcb->handle, dst, p_buf, protocol, src, ext);
if (result == BNEP_IGNORE_CMD) {
- LOG_VERBOSE("PAN ignored data buf write to PANU");
+ log::verbose("PAN ignored data buf write to PANU");
pcb->write.errors++;
return PAN_IGNORE_CMD;
} else if (result != BNEP_SUCCESS) {
- LOG_ERROR("PAN failed to send data buf to the PANU");
+ log::error("PAN failed to send data buf to the PANU");
pcb->write.errors++;
return (tPAN_RESULT)result;
}
@@ -565,7 +567,7 @@
pcb->write.octets += len;
pcb->write.packets++;
- LOG_VERBOSE("PAN successfully sent data buf to the PANU");
+ log::verbose("PAN successfully sent data buf to the PANU");
return PAN_SUCCESS;
}
@@ -594,18 +596,18 @@
/* Check if the connection exists */
pcb = pan_get_pcb_by_handle(handle);
if (!pcb) {
- LOG_ERROR("PAN connection not found for the handle %d", handle);
+ log::error("PAN connection not found for the handle {}", handle);
return PAN_FAILURE;
}
tBNEP_RESULT result = BNEP_SetProtocolFilters(pcb->handle, num_filters,
p_start_array, p_end_array);
if (result != BNEP_SUCCESS) {
- LOG_ERROR("PAN failed to set protocol filters for handle %d", handle);
+ log::error("PAN failed to set protocol filters for handle {}", handle);
return (tPAN_RESULT)result;
}
- LOG_VERBOSE("PAN successfully sent protocol filters for handle %d", handle);
+ log::verbose("PAN successfully sent protocol filters for handle {}", handle);
return PAN_SUCCESS;
}
@@ -633,18 +635,18 @@
/* Check if the connection exists */
pcb = pan_get_pcb_by_handle(handle);
if (!pcb) {
- LOG_ERROR("PAN connection not found for the handle %d", handle);
+ log::error("PAN connection not found for the handle {}", handle);
return PAN_FAILURE;
}
tBNEP_RESULT result = BNEP_SetMulticastFilters(pcb->handle, num_mcast_filters,
p_start_array, p_end_array);
if (result != BNEP_SUCCESS) {
- LOG_ERROR("PAN failed to set multicast filters for handle %d", handle);
+ log::error("PAN failed to set multicast filters for handle {}", handle);
return (tPAN_RESULT)result;
}
- LOG_VERBOSE("PAN successfully sent multicast filters for handle %d", handle);
+ log::verbose("PAN successfully sent multicast filters for handle {}", handle);
return PAN_SUCCESS;
}
diff --git a/system/stack/pan/pan_int.h b/system/stack/pan/pan_int.h
index bf0060d..b73eae7 100644
--- a/system/stack/pan/pan_int.h
+++ b/system/stack/pan/pan_int.h
@@ -25,6 +25,8 @@
#ifndef PAN_INT_H
#define PAN_INT_H
+#include <bluetooth/log.h>
+
#include <cstdint>
#include "internal_include/bt_target.h"
@@ -134,4 +136,9 @@
/******************************************************************************/
+namespace fmt {
+template <>
+struct formatter<tPAN_STATE> : enum_formatter<tPAN_STATE> {};
+} // namespace fmt
+
#endif
diff --git a/system/stack/pan/pan_main.cc b/system/stack/pan/pan_main.cc
index b06e51b..28d1291 100644
--- a/system/stack/pan/pan_main.cc
+++ b/system/stack/pan/pan_main.cc
@@ -26,12 +26,13 @@
#define LOG_TAG "pan"
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <string.h> // memset
#include <cstdint>
+#include "os/log.h"
#include "osi/include/allocator.h"
-#include "osi/include/log.h"
#include "osi/include/osi.h" // UNUSED_ATTR
#include "stack/include/bnep_api.h"
#include "stack/include/bt_hdr.h"
@@ -40,6 +41,7 @@
#include "types/bluetooth/uuid.h"
#include "types/raw_address.h"
+using namespace bluetooth;
using bluetooth::Uuid;
tPAN_CB pan_cb;
@@ -101,13 +103,13 @@
*/
if (!remote_uuid.Is16Bit()) {
- LOG_ERROR("PAN Connection failed because of wrong remote UUID ");
+ log::error("PAN Connection failed because of wrong remote UUID");
BNEP_ConnectResp(handle, BNEP_CONN_FAILED_SRC_UUID);
return;
}
if (!local_uuid.Is16Bit()) {
- LOG_ERROR("PAN Connection failed because of wrong local UUID ");
+ log::error("PAN Connection failed because of wrong local UUID");
BNEP_ConnectResp(handle, BNEP_CONN_FAILED_DST_UUID);
return;
}
@@ -115,17 +117,17 @@
uint16_t remote_uuid16 = remote_uuid.As16Bit();
uint16_t local_uuid16 = local_uuid.As16Bit();
- LOG_VERBOSE(
- "%s - handle %d, current role %d, dst uuid 0x%x, src uuid 0x%x, role "
- "change %s",
- __func__, handle, pan_cb.role, local_uuid16, remote_uuid16,
+ log::verbose(
+ "handle {}, current role {}, dst uuid 0x{:x}, src uuid 0x{:x}, role "
+ "change {}",
+ handle, pan_cb.role, local_uuid16, remote_uuid16,
is_role_change ? "YES" : "NO");
/* Check if the source UUID is a valid one */
if (remote_uuid16 != UUID_SERVCLASS_PANU &&
remote_uuid16 != UUID_SERVCLASS_NAP &&
remote_uuid16 != UUID_SERVCLASS_GN) {
- LOG_ERROR("Src UUID 0x%x is not valid", remote_uuid16);
+ log::error("Src UUID 0x{:x} is not valid", remote_uuid16);
BNEP_ConnectResp(handle, BNEP_CONN_FAILED_SRC_UUID);
return;
}
@@ -133,7 +135,7 @@
/* Check if the destination UUID is a valid one */
if (local_uuid16 != UUID_SERVCLASS_PANU &&
local_uuid16 != UUID_SERVCLASS_NAP && local_uuid16 != UUID_SERVCLASS_GN) {
- LOG_ERROR("Dst UUID 0x%x is not valid", local_uuid16);
+ log::error("Dst UUID 0x{:x} is not valid", local_uuid16);
BNEP_ConnectResp(handle, BNEP_CONN_FAILED_DST_UUID);
return;
}
@@ -145,8 +147,8 @@
local_uuid16 == UUID_SERVCLASS_GN) ||
((!(pan_cb.role & UUID_SERVCLASS_NAP)) &&
local_uuid16 == UUID_SERVCLASS_NAP)) {
- LOG_ERROR(
- "PAN Connection failed because of unsupported destination UUID 0x%x",
+ log::error(
+ "PAN Connection failed because of unsupported destination UUID 0x{:x}",
local_uuid16);
BNEP_ConnectResp(handle, BNEP_CONN_FAILED_DST_UUID);
return;
@@ -176,9 +178,9 @@
is_valid_interaction = false;
}
if (!is_valid_interaction) {
- LOG_ERROR(
+ log::error(
"PAN Connection failed because of invalid PAN profile roles "
- "interaction: Remote UUID 0x%x Local UUID 0x%x",
+ "interaction: Remote UUID 0x{:x} Local UUID 0x{:x}",
remote_uuid16, local_uuid16);
BNEP_ConnectResp(handle, BNEP_CONN_FAILED_SRC_UUID);
return;
@@ -200,7 +202,7 @@
/* There are connections other than this one
** so we cann't accept PANU role. Reject
*/
- LOG_ERROR(
+ log::error(
"Dst UUID should be either GN or NAP only because there are other "
"connections");
BNEP_ConnectResp(handle, BNEP_CONN_FAILED_DST_UUID);
@@ -209,8 +211,8 @@
/* If it is already in connected state check for bridging status */
if (pcb->con_state == PAN_STATE_CONNECTED) {
- LOG_VERBOSE("PAN Role changing New Src 0x%x Dst 0x%x", remote_uuid16,
- local_uuid16);
+ log::verbose("PAN Role changing New Src 0x{:x} Dst 0x{:x}", remote_uuid16,
+ local_uuid16);
pcb->prv_src_uuid = pcb->src_uuid;
pcb->prv_dst_uuid = pcb->dst_uuid;
@@ -235,22 +237,22 @@
*/
if (pan_cb.num_conns && (local_uuid16 == UUID_SERVCLASS_PANU ||
pan_cb.active_role == PAN_ROLE_CLIENT)) {
- LOG_ERROR("PAN already have a connection and can't be user");
+ log::error("PAN already have a connection and can't be user");
BNEP_ConnectResp(handle, BNEP_CONN_FAILED_DST_UUID);
return;
}
}
/* This is a new connection */
- LOG_VERBOSE("New connection indication for handle %d", handle);
+ log::verbose("New connection indication for handle {}", handle);
pcb = pan_allocate_pcb(p_bda, handle);
if (!pcb) {
- LOG_ERROR("PAN no control block for new connection");
+ log::error("PAN no control block for new connection");
BNEP_ConnectResp(handle, BNEP_CONN_FAILED);
return;
}
- LOG_VERBOSE("PAN connection destination UUID is 0x%x", local_uuid16);
+ log::verbose("PAN connection destination UUID is 0x{:x}", local_uuid16);
/* Set the latest active PAN role */
pan_cb.active_role = req_role;
pcb->src_uuid = local_uuid16;
@@ -287,11 +289,11 @@
tPAN_CONN* pcb;
uint8_t peer_role;
- LOG_VERBOSE("pan_connect_state_cb - for handle %d, result %d", handle,
- result);
+ log::verbose("pan_connect_state_cb - for handle {}, result {}", handle,
+ result);
pcb = pan_get_pcb_by_handle(handle);
if (!pcb) {
- LOG_ERROR("PAN State change indication for wrong handle %d", handle);
+ log::error("PAN State change indication for wrong handle {}", handle);
return;
}
@@ -307,7 +309,7 @@
if (pcb->con_state != PAN_STATE_CONNECTED &&
(pcb->con_flags & PAN_FLAGS_CONN_COMPLETED)) {
/* restore the original values */
- LOG_VERBOSE("restoring the connection state to active");
+ log::verbose("restoring the connection state to active");
pcb->con_state = PAN_STATE_CONNECTED;
pcb->con_flags &= (~PAN_FLAGS_CONN_COMPLETED);
@@ -352,7 +354,7 @@
/* Create bridge if the destination role is NAP */
if (pan_cb.pan_bridge_req_cb && pcb->src_uuid == UUID_SERVCLASS_NAP) {
- LOG_VERBOSE("PAN requesting for bridge");
+ log::verbose("PAN requesting for bridge");
(*pan_cb.pan_bridge_req_cb)(pcb->rem_bda, true);
}
}
@@ -389,14 +391,14 @@
/* Check if the connection is in right state */
pcb = pan_get_pcb_by_handle(handle);
if (!pcb) {
- LOG_ERROR("PAN Data buffer indication for wrong handle %d", handle);
+ log::error("PAN Data buffer indication for wrong handle {}", handle);
osi_free(p_buf);
return;
}
if (pcb->con_state != PAN_STATE_CONNECTED) {
- LOG_ERROR("PAN Data indication in wrong state %d for handle %d",
- pcb->con_state, handle);
+ log::error("PAN Data indication in wrong state {} for handle {}",
+ pcb->con_state, handle);
pcb->read.drops++;
osi_free(p_buf);
return;
@@ -408,8 +410,8 @@
pcb->read.octets += len;
pcb->read.packets++;
- LOG_VERBOSE(
- "pan_data_buf_ind_cb - for handle %d, protocol 0x%x, length %d, ext %d",
+ log::verbose(
+ "pan_data_buf_ind_cb - for handle {}, protocol 0x{:x}, length {}, ext {}",
handle, protocol, len, ext);
if (pcb->src_uuid == UUID_SERVCLASS_NAP)
@@ -420,8 +422,9 @@
/* Check if it is broadcast or multicast packet */
if (pcb->src_uuid != UUID_SERVCLASS_PANU) {
if (dst.address[0] & 0x01) {
- LOG_VERBOSE("PAN received broadcast packet on handle %d, src uuid 0x%x",
- handle, pcb->src_uuid);
+ log::verbose(
+ "PAN received broadcast packet on handle {}, src uuid 0x{:x}", handle,
+ pcb->src_uuid);
for (i = 0; i < MAX_PAN_CONNS; i++) {
if (pan_cb.pcb[i].con_state == PAN_STATE_CONNECTED &&
pan_cb.pcb[i].handle != handle &&
@@ -445,15 +448,15 @@
/* Check if it is for any other PAN connection */
dst_pcb = pan_get_pcb_by_addr(dst);
if (dst_pcb) {
- LOG_VERBOSE(
- "%s - destination PANU found on handle %d and sending data, len: %d",
- __func__, dst_pcb->handle, len);
+ log::verbose(
+ "destination PANU found on handle {} and sending data, len: {}",
+ dst_pcb->handle, len);
result =
BNEP_Write(dst_pcb->handle, dst, p_data, len, protocol, src, ext);
if (result != BNEP_SUCCESS && result != BNEP_IGNORE_CMD)
- LOG_ERROR("Failed to write data for PAN connection handle %d",
- dst_pcb->handle);
+ log::error("Failed to write data for PAN connection handle {}",
+ dst_pcb->handle);
pcb->read.errors++;
osi_free(p_buf);
return;
@@ -515,9 +518,9 @@
void pan_proto_filt_ind_cb(uint16_t handle, bool indication,
tBNEP_RESULT result, uint16_t num_filters,
uint8_t* p_filters) {
- LOG_VERBOSE(
- "pan_proto_filt_ind_cb - called for handle %d with ind %d, result %d, "
- "num %d",
+ log::verbose(
+ "pan_proto_filt_ind_cb - called for handle {} with ind {}, result {}, "
+ "num {}",
handle, indication, result, num_filters);
if (pan_cb.pan_pfilt_ind_cb)
@@ -549,9 +552,9 @@
void pan_mcast_filt_ind_cb(uint16_t handle, bool indication,
tBNEP_RESULT result, uint16_t num_filters,
uint8_t* p_filters) {
- LOG_VERBOSE(
- "pan_mcast_filt_ind_cb - called for handle %d with ind %d, result %d, "
- "num %d",
+ log::verbose(
+ "pan_mcast_filt_ind_cb - called for handle {} with ind {}, result {}, "
+ "num {}",
handle, indication, result, num_filters);
if (pan_cb.pan_mfilt_ind_cb)
diff --git a/system/stack/pan/pan_utils.cc b/system/stack/pan/pan_utils.cc
index e33f1e3..6156d16 100644
--- a/system/stack/pan/pan_utils.cc
+++ b/system/stack/pan/pan_utils.cc
@@ -26,6 +26,7 @@
#define LOG_TAG "pan"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <cstdint>
@@ -38,6 +39,7 @@
#include "stack/pan/pan_int.h"
#include "types/raw_address.h"
+using namespace bluetooth;
using namespace bluetooth::legacy::stack::sdp;
static const uint8_t pan_proto_elem_data[] = {
@@ -76,7 +78,7 @@
sdp_handle = get_legacy_stack_sdp_api()->handle.SDP_CreateRecord();
if (sdp_handle == 0) {
- LOG_ERROR("PAN_SetRole - could not create SDP record");
+ log::error("PAN_SetRole - could not create SDP record");
return 0;
}
@@ -279,13 +281,13 @@
uint16_t i;
tPAN_CONN* p_pcb;
- LOG_VERBOSE("PAN role %x, active role %d, num_conns %d", pan_cb.role,
- pan_cb.active_role, pan_cb.num_conns);
+ log::verbose("PAN role {:x}, active role {}, num_conns {}", pan_cb.role,
+ pan_cb.active_role, pan_cb.num_conns);
for (i = 0, p_pcb = pan_cb.pcb; i < MAX_PAN_CONNS; i++, p_pcb++) {
- VLOG(1) << +i << " state:" << p_pcb->con_state
- << ", handle:" << p_pcb->handle << ", src" << p_pcb->src_uuid
- << ", BD:" << p_pcb->rem_bda;
+ log::verbose("{} state:{}, handle:{}, src{}, BD:{}", i, p_pcb->con_state,
+ p_pcb->handle, p_pcb->src_uuid,
+ ADDRESS_TO_LOGGABLE_STR(p_pcb->rem_bda));
}
#endif
}
diff --git a/system/stack/rfcomm/port_api.cc b/system/stack/rfcomm/port_api.cc
index 0ac308b..daf9b897 100644
--- a/system/stack/rfcomm/port_api.cc
+++ b/system/stack/rfcomm/port_api.cc
@@ -27,6 +27,7 @@
#include "stack/include/port_api.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <cstdint>
@@ -41,8 +42,7 @@
#include "stack/rfcomm/rfc_int.h"
#include "types/raw_address.h"
-#define error(fmt, ...) \
- LOG_ERROR("## ERROR : %s: " fmt "##", __func__, ##__VA_ARGS__)
+using namespace bluetooth;
/* Mapping from PORT_* result codes to human readable strings. */
static const char* result_code_strings[] = {"Success",
@@ -113,11 +113,9 @@
if ((scn == 0) || (scn > RFCOMM_MAX_SCN)) {
// Server Channel Number (SCN) should be in range [1, 30]
- LOG(ERROR) << __func__ << ": Invalid SCN, bd_addr=" << bd_addr
- << ", scn=" << static_cast<int>(scn)
- << ", is_server=" << is_server
- << ", mtu=" << static_cast<int>(mtu)
- << ", uuid=" << loghex(uuid);
+ log::error("Invalid SCN, bd_addr={}, scn={}, is_server={}, mtu={}, uuid={}",
+ ADDRESS_TO_LOGGABLE_STR(bd_addr), static_cast<int>(scn),
+ is_server, static_cast<int>(mtu), loghex(uuid));
return (PORT_INVALID_SCN);
}
@@ -139,16 +137,15 @@
if (p_port != nullptr) {
// if existing port is also a client port, error out
if (!p_port->is_server) {
- LOG(ERROR) << __func__ << ": already at opened state "
- << static_cast<int>(p_port->state)
- << ", RFC_state=" << static_cast<int>(p_port->rfc.state)
- << ", MCB_state="
- << (p_port->rfc.p_mcb ? p_port->rfc.p_mcb->state : 0)
- << ", bd_addr=" << bd_addr << ", scn=" << std::to_string(scn)
- << ", is_server=" << is_server << ", mtu=" << mtu
- << ", uuid=" << loghex(uuid) << ", dlci=" << +dlci
- << ", p_mcb=" << p_mcb
- << ", port=" << std::to_string(p_port->handle);
+ log::error(
+ "already at opened state {}, RFC_state={}, MCB_state={}, "
+ "bd_addr={}, scn={}, is_server={}, mtu={}, uuid={}, dlci={}, "
+ "p_mcb={}, port={}",
+ static_cast<int>(p_port->state),
+ static_cast<int>(p_port->rfc.state),
+ (p_port->rfc.p_mcb ? p_port->rfc.p_mcb->state : 0),
+ ADDRESS_TO_LOGGABLE_STR(bd_addr), scn, is_server, mtu, loghex(uuid),
+ dlci, fmt::ptr(p_mcb), p_port->handle);
*p_handle = p_port->handle;
return (PORT_ALREADY_OPENED);
}
@@ -158,10 +155,11 @@
// On the server side, always allocate a new port.
p_port = port_allocate_port(dlci, bd_addr);
if (p_port == nullptr) {
- LOG(ERROR) << __func__ << ": no resources, bd_addr=" << bd_addr
- << ", scn=" << std::to_string(scn) << ", is_server=" << is_server
- << ", mtu=" << mtu << ", uuid=" << loghex(uuid)
- << ", dlci=" << +dlci;
+ log::error(
+ "no resources, bd_addr={}, scn={}, is_server={}, mtu={}, uuid={}, "
+ "dlci={}",
+ ADDRESS_TO_LOGGABLE_STR(bd_addr), scn, is_server, mtu, loghex(uuid),
+ dlci);
return PORT_NO_RESOURCES;
}
p_port->sec_mask = sec_mask;
@@ -219,12 +217,11 @@
p_port->p_mgmt_callback = p_mgmt_cb;
p_port->bd_addr = bd_addr;
- LOG(INFO) << __func__ << ": bd_addr=" << bd_addr
- << ", scn=" << std::to_string(scn) << ", is_server=" << is_server
- << ", mtu=" << mtu << ", uuid=" << loghex(uuid)
- << ", dlci=" << std::to_string(dlci)
- << ", signal_state=" << loghex(p_port->default_signal_state)
- << ", p_port=" << p_port;
+ log::info(
+ "bd_addr={}, scn={}, is_server={}, mtu={}, uuid={}, dlci={}, "
+ "signal_state={}, p_port={}",
+ ADDRESS_TO_LOGGABLE_STR(bd_addr), scn, is_server, mtu, loghex(uuid), dlci,
+ loghex(p_port->default_signal_state), fmt::ptr(p_port));
// If this is not initiator of the connection need to just wait
if (p_port->is_server) {
@@ -288,17 +285,17 @@
int RFCOMM_RemoveConnection(uint16_t handle) {
tPORT* p_port;
- LOG_VERBOSE("RFCOMM_RemoveConnection() handle:%d", handle);
+ log::verbose("RFCOMM_RemoveConnection() handle:{}", handle);
/* Check if handle is valid to avoid crashing */
if ((handle == 0) || (handle > MAX_RFC_PORTS)) {
- LOG_ERROR("RFCOMM_RemoveConnection() BAD handle:%d", handle);
+ log::error("RFCOMM_RemoveConnection() BAD handle:{}", handle);
return (PORT_BAD_HANDLE);
}
p_port = &rfc_cb.port.port[handle - 1];
if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) {
- LOG_VERBOSE("RFCOMM_RemoveConnection() Not opened:%d", handle);
+ log::verbose("RFCOMM_RemoveConnection() Not opened:{}", handle);
return (PORT_SUCCESS);
}
@@ -321,7 +318,7 @@
int RFCOMM_RemoveServer(uint16_t handle) {
/* Check if handle is valid to avoid crashing */
if ((handle == 0) || (handle > MAX_RFC_PORTS)) {
- LOG(ERROR) << __func__ << ": bad handle " << handle;
+ log::error("bad handle {}", handle);
return (PORT_BAD_HANDLE);
}
tPORT* p_port = &rfc_cb.port.port[handle - 1];
@@ -330,10 +327,10 @@
p_port->p_mgmt_callback = nullptr;
if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) {
- LOG_DEBUG("handle %u not opened", handle);
+ log::debug("handle {} not opened", handle);
return (PORT_SUCCESS);
}
- LOG(INFO) << __func__ << ": handle=" << handle;
+ log::info("handle={}", handle);
/* this port will be deallocated after closing */
p_port->keep_port_handle = false;
@@ -373,7 +370,7 @@
return (PORT_NOT_OPENED);
}
- LOG_VERBOSE("PORT_SetEventCallback() handle:%d", port_handle);
+ log::verbose("PORT_SetEventCallback() handle:{}", port_handle);
p_port->p_callback = p_port_cb;
@@ -419,8 +416,8 @@
tPORT_DATA_CO_CALLBACK* p_port_cb) {
tPORT* p_port;
- LOG_VERBOSE("PORT_SetDataCOCallback() handle:%d cb 0x%p", port_handle,
- p_port_cb);
+ log::verbose("PORT_SetDataCOCallback() handle:{} cb 0x{}", port_handle,
+ fmt::ptr(p_port_cb));
/* Check if handle is valid to avoid crashing */
if ((port_handle == 0) || (port_handle > MAX_RFC_PORTS)) {
@@ -451,7 +448,7 @@
int PORT_SetEventMask(uint16_t port_handle, uint32_t mask) {
tPORT* p_port;
- LOG_VERBOSE("PORT_SetEventMask() handle:%d mask:0x%x", port_handle, mask);
+ log::verbose("PORT_SetEventMask() handle:{} mask:0x{:x}", port_handle, mask);
/* Check if handle is valid to avoid crashing */
if ((port_handle == 0) || (port_handle > MAX_RFC_PORTS)) {
@@ -488,10 +485,10 @@
return (PORT_BAD_HANDLE);
}
tPORT* p_port = &rfc_cb.port.port[handle - 1];
- LOG_VERBOSE(
- "%s: handle=%d, in_use=%d, port_state=%d, p_mcb=%p, peer_ready=%d, "
- "rfc_state=%d",
- __func__, handle, p_port->in_use, p_port->state, p_port->rfc.p_mcb,
+ log::verbose(
+ "handle={}, in_use={}, port_state={}, p_mcb={}, peer_ready={}, "
+ "rfc_state={}",
+ handle, p_port->in_use, p_port->state, fmt::ptr(p_port->rfc.p_mcb),
(p_port->rfc.p_mcb ? p_port->rfc.p_mcb->peer_ready : -1),
p_port->rfc.state);
@@ -527,7 +524,7 @@
if ((multiplexer_cb.state > RFC_MX_STATE_IDLE) &&
(multiplexer_cb.state < RFC_MX_STATE_CONNECTED)) {
*bd_addr = multiplexer_cb.bd_addr;
- LOG_INFO(
+ log::info(
"Found a rfc_mcb in the middle of opening a port, returning true");
return true;
}
@@ -544,20 +541,20 @@
}
}
- LOG_INFO("RFC_MX_STATE_CONNECTED, found_port=%d, tRFC_PORT_STATE=%d",
- found_port, p_port != nullptr ? p_port->rfc.state : 0);
+ log::info("RFC_MX_STATE_CONNECTED, found_port={}, tRFC_PORT_STATE={}",
+ found_port, p_port != nullptr ? p_port->rfc.state : 0);
if ((!found_port) ||
(found_port && (p_port->rfc.state < RFC_STATE_OPENED))) {
/* Port is not established yet. */
*bd_addr = multiplexer_cb.bd_addr;
- LOG_INFO(
+ log::info(
"In RFC_MX_STATE_CONNECTED but port is not established yet, "
"returning true");
return true;
}
}
}
- LOG_INFO("false");
+ log::info("false");
return false;
}
@@ -578,7 +575,7 @@
tPORT* p_port;
uint8_t baud_rate;
- LOG_VERBOSE("PORT_SetState() handle:%d", handle);
+ log::verbose("PORT_SetState() handle:{}", handle);
/* Check if handle is valid to avoid crashing */
if ((handle == 0) || (handle > MAX_RFC_PORTS)) {
@@ -595,8 +592,8 @@
return (PORT_LINE_ERR);
}
- LOG_VERBOSE("PORT_SetState() handle:%d FC_TYPE:0x%x", handle,
- p_settings->fc_type);
+ log::verbose("PORT_SetState() handle:{} FC_TYPE:0x{:x}", handle,
+ p_settings->fc_type);
baud_rate = p_port->user_port_pars.baud_rate;
p_port->user_port_pars = *p_settings;
@@ -623,7 +620,7 @@
int PORT_GetState(uint16_t handle, tPORT_STATE* p_settings) {
tPORT* p_port;
- LOG_VERBOSE("PORT_GetState() handle:%d", handle);
+ log::verbose("PORT_GetState() handle:{}", handle);
/* Check if handle is valid to avoid crashing */
if ((handle == 0) || (handle > MAX_RFC_PORTS)) {
@@ -663,7 +660,7 @@
bool old_fc;
uint32_t events;
- LOG_VERBOSE("PORT_FlowControl() handle:%d enable: %d", handle, enable);
+ log::verbose("PORT_FlowControl() handle:{} enable: {}", handle, enable);
/* Check if handle is valid to avoid crashing */
if ((handle == 0) || (handle > MAX_RFC_PORTS)) {
@@ -731,7 +728,7 @@
BT_HDR* p_buf;
uint16_t count;
- LOG_VERBOSE("PORT_ReadData() handle:%d max_len:%d", handle, max_len);
+ log::verbose("PORT_ReadData() handle:{} max_len:{}", handle, max_len);
/* Initialize this in case of an error */
*p_len = 0;
@@ -748,7 +745,7 @@
}
if (p_port->state == PORT_CONNECTION_STATE_OPENING) {
- LOG_WARN("Trying to read a port in PORT_CONNECTION_STATE_OPENING state");
+ log::warn("Trying to read a port in PORT_CONNECTION_STATE_OPENING state");
}
if (p_port->line_status) {
@@ -756,7 +753,7 @@
}
if (fixed_queue_is_empty(p_port->rx.queue)) {
- LOG_WARN("Read on empty input queue");
+ log::warn("Read on empty input queue");
return (PORT_SUCCESS);
}
@@ -803,11 +800,11 @@
}
if (*p_len == 1) {
- LOG_VERBOSE("PORT_ReadData queue:%d returned:%d %x", p_port->rx.queue_size,
- *p_len, (p_data[0]));
+ log::verbose("PORT_ReadData queue:{} returned:{} {:x}",
+ p_port->rx.queue_size, *p_len, (p_data[0]));
} else {
- LOG_VERBOSE("PORT_ReadData queue:%d returned:%d", p_port->rx.queue_size,
- *p_len);
+ log::verbose("PORT_ReadData queue:{} returned:{}", p_port->rx.queue_size,
+ *p_len);
}
/* If rfcomm suspended traffic from the peer based on the rx_queue_size */
@@ -846,7 +843,7 @@
(PORT_CTRL_REQ_SENT | PORT_CTRL_IND_RECEIVED))) {
if ((p_port->tx.queue_size > PORT_TX_CRITICAL_WM) ||
(fixed_queue_length(p_port->tx.queue) > PORT_TX_BUF_CRITICAL_WM)) {
- LOG_WARN("PORT_Write: Queue size: %d", p_port->tx.queue_size);
+ log::warn("PORT_Write: Queue size: {}", p_port->tx.queue_size);
osi_free(p_buf);
@@ -856,9 +853,9 @@
return (PORT_TX_FULL);
}
- LOG_VERBOSE(
- "PORT_Write : Data is enqued. flow disabled %d peer_ready %d state %d "
- "ctrl_state %x",
+ log::verbose(
+ "PORT_Write : Data is enqued. flow disabled {} peer_ready {} state {} "
+ "ctrl_state {:x}",
p_port->tx.peer_fc,
(p_port->rfc.p_mcb && p_port->rfc.p_mcb->peer_ready), p_port->rfc.state,
p_port->port_ctrl);
@@ -868,7 +865,7 @@
return (PORT_CMD_PENDING);
} else {
- LOG_VERBOSE("PORT_Write : Data is being sent");
+ log::verbose("PORT_Write : Data is being sent");
RFCOMM_DataReq(p_port->rfc.p_mcb, p_port->dlci, p_buf);
return (PORT_SUCCESS);
@@ -894,7 +891,7 @@
int rc = 0;
uint16_t length;
- LOG_VERBOSE("PORT_WriteDataCO() handle:%d", handle);
+ log::verbose("PORT_WriteDataCO() handle:{}", handle);
*p_len = 0;
/* Check if handle is valid to avoid crashing */
@@ -904,12 +901,12 @@
p_port = &rfc_cb.port.port[handle - 1];
if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) {
- LOG_WARN("PORT_WriteDataByFd() no port state:%d", p_port->state);
+ log::warn("PORT_WriteDataByFd() no port state:{}", p_port->state);
return (PORT_NOT_OPENED);
}
if (!p_port->peer_mtu) {
- LOG_ERROR("PORT_WriteDataByFd() peer_mtu:%d", p_port->peer_mtu);
+ log::error("PORT_WriteDataByFd() peer_mtu:{}", p_port->peer_mtu);
return (PORT_UNKNOWN_ERROR);
}
int available = 0;
@@ -917,9 +914,9 @@
if (!p_port->p_data_co_callback(handle, (uint8_t*)&available,
sizeof(available),
DATA_CO_CALLBACK_TYPE_OUTGOING_SIZE)) {
- LOG_ERROR(
+ log::error(
"p_data_co_callback DATA_CO_CALLBACK_TYPE_INCOMING_SIZE failed, "
- "available:%d",
+ "available:{}",
available);
return (PORT_UNKNOWN_ERROR);
}
@@ -944,9 +941,9 @@
available, DATA_CO_CALLBACK_TYPE_OUTGOING))
{
- error(
+ log::error(
"p_data_co_callback DATA_CO_CALLBACK_TYPE_OUTGOING failed, "
- "available:%d",
+ "available:{}",
available);
mutex_global_unlock();
return (PORT_UNKNOWN_ERROR);
@@ -975,8 +972,8 @@
(fixed_queue_length(p_port->tx.queue) > PORT_TX_BUF_HIGH_WM)) {
port_flow_control_user(p_port);
event |= PORT_EV_FC;
- LOG_VERBOSE(
- "tx queue is full,tx.queue_size:%d,tx.queue.count:%zu,available:%d",
+ log::verbose(
+ "tx queue is full,tx.queue_size:{},tx.queue.count:{},available:{}",
p_port->tx.queue_size, fixed_queue_length(p_port->tx.queue),
available);
break;
@@ -998,13 +995,13 @@
if (!p_port->p_data_co_callback(handle,
(uint8_t*)(p_buf + 1) + p_buf->offset,
length, DATA_CO_CALLBACK_TYPE_OUTGOING)) {
- error(
- "p_data_co_callback DATA_CO_CALLBACK_TYPE_OUTGOING failed, length:%d",
+ log::error(
+ "p_data_co_callback DATA_CO_CALLBACK_TYPE_OUTGOING failed, length:{}",
length);
return (PORT_UNKNOWN_ERROR);
}
- LOG_VERBOSE("PORT_WriteData %d bytes", length);
+ log::verbose("PORT_WriteData {} bytes", length);
rc = port_write(p_port, p_buf);
@@ -1051,7 +1048,7 @@
int rc = 0;
uint16_t length;
- LOG_VERBOSE("PORT_WriteData() max_len:%d", max_len);
+ log::verbose("PORT_WriteData() max_len:{}", max_len);
*p_len = 0;
@@ -1062,16 +1059,16 @@
p_port = &rfc_cb.port.port[handle - 1];
if (!p_port->in_use || (p_port->state == PORT_CONNECTION_STATE_CLOSED)) {
- LOG_WARN("PORT_WriteData() no port state:%d", p_port->state);
+ log::warn("PORT_WriteData() no port state:{}", p_port->state);
return (PORT_NOT_OPENED);
}
if (p_port->state == PORT_CONNECTION_STATE_OPENING) {
- LOG_WARN("Write data received but port is in OPENING state");
+ log::warn("Write data received but port is in OPENING state");
}
if (!max_len || !p_port->peer_mtu) {
- LOG_ERROR("PORT_WriteData() peer_mtu:%d", p_port->peer_mtu);
+ log::error("PORT_WriteData() peer_mtu:{}", p_port->peer_mtu);
return (PORT_UNKNOWN_ERROR);
}
@@ -1118,7 +1115,7 @@
memcpy((uint8_t*)(p_buf + 1) + p_buf->offset, p_data, length);
- LOG_VERBOSE("PORT_WriteData %d bytes", length);
+ log::verbose("PORT_WriteData {} bytes", length);
rc = port_write(p_port, p_buf);
diff --git a/system/stack/rfcomm/port_rfc.cc b/system/stack/rfcomm/port_rfc.cc
index 2f59087..973740b 100644
--- a/system/stack/rfcomm/port_rfc.cc
+++ b/system/stack/rfcomm/port_rfc.cc
@@ -27,6 +27,7 @@
#include <base/functional/callback.h>
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <frameworks/proto_logging/stats/enums/bluetooth/enums.pb.h>
#include <cstdint>
@@ -47,6 +48,8 @@
#include "stack/rfcomm/port_int.h"
#include "stack/rfcomm/rfc_int.h"
+using namespace bluetooth;
+
/*
* Local function definitions
*/
@@ -65,12 +68,12 @@
*
******************************************************************************/
int port_open_continue(tPORT* p_port) {
- LOG_VERBOSE("port_open_continue, p_port:%p", p_port);
+ log::verbose("port_open_continue, p_port:{}", fmt::ptr(p_port));
/* Check if multiplexer channel has already been established */
tRFC_MCB* p_mcb = rfc_alloc_multiplexer_channel(p_port->bd_addr, true);
if (p_mcb == nullptr) {
- LOG_WARN("port_open_continue no mx channel");
+ log::warn("port_open_continue no mx channel");
port_release_port(p_port);
return (PORT_NO_RESOURCES);
}
@@ -93,8 +96,8 @@
} else {
// MX state machine ignores RFC_MX_EVENT_START_REQ in these states
// When it enters RFC_MX_STATE_CONNECTED, it will check any openning ports
- LOG_VERBOSE("port_open_continue: mx state(%d) mx channel is opening",
- p_mcb->state);
+ log::verbose("port_open_continue: mx state({}) mx channel is opening",
+ p_mcb->state);
}
return (PORT_SUCCESS);
}
@@ -193,7 +196,7 @@
void PORT_StartCnf(tRFC_MCB* p_mcb, uint16_t result) {
bool no_ports_up = true;
- LOG_VERBOSE("%s: result %d", __func__, result);
+ log::verbose("result {}", result);
tPORT* p_port = &rfc_cb.port.port[0];
for (int i = 0; i < MAX_RFC_PORTS; i++, p_port++) {
@@ -201,10 +204,10 @@
no_ports_up = false;
if (result == RFCOMM_SUCCESS) {
- LOG_VERBOSE("%s: dlci %d", __func__, p_port->dlci);
+ log::verbose("dlci {}", p_port->dlci);
RFCOMM_ParameterNegotiationRequest(p_mcb, p_port->dlci, p_port->mtu);
} else {
- LOG_WARN("%s: failed result:%d", __func__, result);
+ log::warn("failed result:{}", result);
/* Warning: result is also set to 4 when l2cap connection
fails due to l2cap connect cnf (no_resources) */
@@ -253,13 +256,13 @@
tPORT* p_port;
int i;
- LOG_VERBOSE("PORT_StartInd");
+ log::verbose("PORT_StartInd");
p_port = &rfc_cb.port.port[0];
for (i = 0; i < MAX_RFC_PORTS; i++, p_port++) {
if ((p_port->rfc.p_mcb == NULL) || (p_port->rfc.p_mcb == p_mcb)) {
- LOG_VERBOSE("PORT_StartInd, RFCOMM_StartRsp RFCOMM_SUCCESS: p_mcb:%p",
- p_mcb);
+ log::verbose("PORT_StartInd, RFCOMM_StartRsp RFCOMM_SUCCESS: p_mcb:{}",
+ fmt::ptr(p_mcb));
RFCOMM_StartRsp(p_mcb, RFCOMM_SUCCESS);
return;
}
@@ -279,16 +282,16 @@
******************************************************************************/
void PORT_ParNegInd(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl,
uint8_t k) {
- LOG_VERBOSE("%s: bd_addr=%s, dlci=%d, mtu=%d", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(p_mcb->bd_addr), dlci, mtu);
+ log::verbose("bd_addr={}, dlci={}, mtu={}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_mcb->bd_addr), dlci, mtu);
tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
if (!p_port) {
/* This can be a first request for this port */
p_port = port_find_dlci_port(dlci);
if (!p_port) {
- LOG(ERROR) << __func__ << ": Disconnect RFCOMM, port not found, dlci="
- << std::to_string(dlci) << ", p_mcb=" << p_mcb
- << ", bd_addr=" << p_mcb->bd_addr;
+ log::error(
+ "Disconnect RFCOMM, port not found, dlci={}, p_mcb={}, bd_addr={}",
+ dlci, fmt::ptr(p_mcb), ADDRESS_TO_LOGGABLE_STR(p_mcb->bd_addr));
/* If the port cannot be opened, send a DM. Per Errata 1205 */
rfc_send_dm(p_mcb, dlci, false);
/* check if this is the last port open, some headsets have
@@ -296,8 +299,8 @@
rfc_check_mcb_active(p_mcb);
return;
}
- LOG_VERBOSE("%s: port_handles[dlci:%d]:%d->%d", __func__, dlci,
- p_mcb->port_handles[dlci], p_port->handle);
+ log::verbose("port_handles[dlci:{}]:{}->{}", dlci,
+ p_mcb->port_handles[dlci], p_port->handle);
p_mcb->port_handles[dlci] = p_port->handle;
}
@@ -368,10 +371,10 @@
******************************************************************************/
void PORT_ParNegCnf(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint8_t cl,
uint8_t k) {
- LOG_VERBOSE("PORT_ParNegCnf dlci:%d mtu:%d cl: %d k: %d", dlci, mtu, cl, k);
+ log::verbose("PORT_ParNegCnf dlci:{} mtu:{} cl: {} k: {}", dlci, mtu, cl, k);
tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
if (!p_port) {
- LOG(WARNING) << __func__ << ": port is null for " << p_mcb->bd_addr;
+ log::warn("port is null for {}", ADDRESS_TO_LOGGABLE_STR(p_mcb->bd_addr));
return;
}
@@ -382,7 +385,7 @@
/* This is illegal-- negotiation fails. */
if ((PORT_FC_DEFAULT == PORT_FC_TS710) &&
(cl == RFCOMM_PN_CONV_LAYER_CBFC_R)) {
- LOG_WARN("%s, negotiation fails, index=%d", __func__, p_port->handle);
+ log::warn("negotiation fails, index={}", p_port->handle);
rfc_send_disc(p_mcb, p_port->dlci);
rfc_port_closed(p_port);
return;
@@ -427,8 +430,9 @@
void PORT_DlcEstablishInd(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu) {
tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
- LOG_VERBOSE("p_mcb:%p, dlci:%d mtu:%di, p_port:%p, bd_addr:%s", p_mcb, dlci,
- mtu, p_port, ADDRESS_TO_LOGGABLE_CSTR(p_mcb->bd_addr));
+ log::verbose("p_mcb:{}, dlci:{} mtu:{}i, p_port:{}, bd_addr:{}",
+ fmt::ptr(p_mcb), dlci, mtu, fmt::ptr(p_port),
+ ADDRESS_TO_LOGGABLE_CSTR(p_mcb->bd_addr));
if (!p_port) {
/* This can be a first request for this port */
@@ -477,8 +481,8 @@
uint16_t result) {
tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
- LOG_VERBOSE("PORT_DlcEstablishCnf dlci:%d mtu:%d result:%d", dlci, mtu,
- result);
+ log::verbose("PORT_DlcEstablishCnf dlci:{} mtu:{} result:{}", dlci, mtu,
+ result);
if (!p_port) return;
@@ -533,7 +537,7 @@
uint16_t param_mask) {
tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
- LOG_VERBOSE("PORT_PortNegInd");
+ log::verbose("PORT_PortNegInd");
if (!p_port) {
/* This can be a first request for this port */
@@ -562,10 +566,10 @@
UNUSED_ATTR tPORT_STATE* p_pars, uint16_t result) {
tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
- LOG_VERBOSE("PORT_PortNegCnf");
+ log::verbose("PORT_PortNegCnf");
if (!p_port) {
- LOG_WARN("PORT_PortNegCnf no port");
+ log::warn("PORT_PortNegCnf no port");
return;
}
/* Port negotiation failed. Drop the connection */
@@ -583,7 +587,7 @@
if (!(p_port->port_ctrl & PORT_CTRL_REQ_SENT)) {
RFCOMM_ControlReq(p_port->rfc.p_mcb, p_port->dlci, &p_port->local_ctrl);
} else {
- LOG_WARN("PORT_PortNegCnf Control Already sent");
+ log::warn("PORT_PortNegCnf Control Already sent");
}
}
@@ -600,7 +604,7 @@
uint32_t event;
uint8_t old_signals;
- LOG_VERBOSE("PORT_ControlInd");
+ log::verbose("PORT_ControlInd");
if (!p_port) return;
@@ -631,11 +635,11 @@
*/
if (event && p_port->p_callback) (p_port->p_callback)(event, p_port->handle);
- LOG_VERBOSE("PORT_ControlInd DTR_DSR : %d, RTS_CTS : %d, RI : %d, DCD : %d",
- ((p_port->peer_ctrl.modem_signal & MODEM_SIGNAL_DTRDSR) ? 1 : 0),
- ((p_port->peer_ctrl.modem_signal & MODEM_SIGNAL_RTSCTS) ? 1 : 0),
- ((p_port->peer_ctrl.modem_signal & MODEM_SIGNAL_RI) ? 1 : 0),
- ((p_port->peer_ctrl.modem_signal & MODEM_SIGNAL_DCD) ? 1 : 0));
+ log::verbose("PORT_ControlInd DTR_DSR : {}, RTS_CTS : {}, RI : {}, DCD : {}",
+ ((p_port->peer_ctrl.modem_signal & MODEM_SIGNAL_DTRDSR) ? 1 : 0),
+ ((p_port->peer_ctrl.modem_signal & MODEM_SIGNAL_RTSCTS) ? 1 : 0),
+ ((p_port->peer_ctrl.modem_signal & MODEM_SIGNAL_RI) ? 1 : 0),
+ ((p_port->peer_ctrl.modem_signal & MODEM_SIGNAL_DCD) ? 1 : 0));
}
/*******************************************************************************
@@ -651,7 +655,7 @@
tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
uint32_t event = 0;
- LOG_VERBOSE("PORT_ControlCnf");
+ log::verbose("PORT_ControlCnf");
if (!p_port) return;
@@ -683,7 +687,7 @@
tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
uint32_t event = 0;
- LOG_VERBOSE("PORT_LineStatusInd");
+ log::verbose("PORT_LineStatusInd");
if (!p_port) return;
@@ -708,8 +712,8 @@
*
******************************************************************************/
void PORT_DlcReleaseInd(tRFC_MCB* p_mcb, uint8_t dlci) {
- LOG_VERBOSE("dlci:%u, bd_addr:%s", dlci,
- ADDRESS_TO_LOGGABLE_CSTR(p_mcb->bd_addr));
+ log::verbose("dlci:{}, bd_addr:{}", dlci,
+ ADDRESS_TO_LOGGABLE_CSTR(p_mcb->bd_addr));
tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
if (!p_port) return;
port_rfc_closed(p_port, PORT_CLOSED);
@@ -729,7 +733,7 @@
tPORT* p_port;
int i;
- LOG_VERBOSE("PORT_CloseInd");
+ log::verbose("PORT_CloseInd");
p_port = &rfc_cb.port.port[0];
for (i = 0; i < MAX_RFC_PORTS; i++, p_port++) {
@@ -755,7 +759,7 @@
tPORT* p_port;
int i;
- LOG_VERBOSE("PORT_TimeOutCloseMux");
+ log::verbose("PORT_TimeOutCloseMux");
p_port = &rfc_cb.port.port[0];
for (i = 0; i < MAX_RFC_PORTS; i++, p_port++) {
@@ -783,8 +787,8 @@
uint8_t* p;
int i;
- LOG_VERBOSE("PORT_DataInd with data length %d, p_mcb:%p,p_port:%p,dlci:%d",
- p_buf->len, p_mcb, p_port, dlci);
+ log::verbose("PORT_DataInd with data length {}, p_mcb:{},p_port:{},dlci:{}",
+ p_buf->len, fmt::ptr(p_mcb), fmt::ptr(p_port), dlci);
if (!p_port) {
osi_free(p_buf);
return;
@@ -814,7 +818,7 @@
/* Check if rx queue exceeds the limit */
if ((p_port->rx.queue_size + p_buf->len > PORT_RX_CRITICAL_WM) ||
(fixed_queue_length(p_port->rx.queue) + 1 > p_port->rx_buf_critical)) {
- LOG_VERBOSE("PORT_DataInd. Buffer over run. Dropping the buffer");
+ log::verbose("PORT_DataInd. Buffer over run. Dropping the buffer");
osi_free(p_buf);
RFCOMM_LineStatusReq(p_mcb, dlci, LINE_STATUS_OVERRUN);
return;
@@ -871,7 +875,7 @@
uint32_t events = 0;
int i;
- LOG_VERBOSE("PORT_FlowInd fc:%d", enable_data);
+ log::verbose("PORT_FlowInd fc:{}", enable_data);
if (dlci == 0) {
p_mcb->peer_ready = enable_data;
@@ -935,8 +939,8 @@
mutex_global_unlock();
- LOG_VERBOSE("Sending RFCOMM_DataReq tx.queue_size=%d",
- p_port->tx.queue_size);
+ log::verbose("Sending RFCOMM_DataReq tx.queue_size={}",
+ p_port->tx.queue_size);
RFCOMM_DataReq(p_port->rfc.p_mcb, p_port->dlci, p_buf);
@@ -975,7 +979,7 @@
if ((p_port->state == PORT_CONNECTION_STATE_OPENING) && (p_port->is_server)) {
/* The server side was not informed that connection is up, ignore */
- LOG_WARN("port_rfc_closed in OPENING state ignored");
+ log::warn("port_rfc_closed in OPENING state ignored");
rfc_port_timer_stop(p_port);
p_port->rfc.state = RFC_STATE_CLOSED;
@@ -1031,13 +1035,12 @@
p_port->rfc.state = RFC_STATE_CLOSED;
- LOG(INFO) << __func__ << ": RFCOMM connection closed, index="
- << std::to_string(p_port->handle)
- << ", state=" << std::to_string(p_port->state)
- << ", reason=" << PORT_GetResultString(res) << "["
- << std::to_string(res) << "], UUID=" << loghex(p_port->uuid)
- << ", bd_addr=" << p_port->bd_addr
- << ", is_server=" << p_port->is_server;
+ log::info(
+ "RFCOMM connection closed, index={}, state={}, reason={}[{}], UUID={}, "
+ "bd_addr={}, is_server={}",
+ p_port->handle, p_port->state, PORT_GetResultString(res), res,
+ loghex(p_port->uuid), ADDRESS_TO_LOGGABLE_STR(p_port->bd_addr),
+ p_port->is_server);
port_release_port(p_port);
}
diff --git a/system/stack/rfcomm/port_utils.cc b/system/stack/rfcomm/port_utils.cc
index 9023923..79de26e 100644
--- a/system/stack/rfcomm/port_utils.cc
+++ b/system/stack/rfcomm/port_utils.cc
@@ -25,6 +25,7 @@
#define LOG_TAG "rfcomm_port_utils"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <cstdint>
#include <cstring>
@@ -40,6 +41,8 @@
#include "stack/rfcomm/rfc_int.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
static const tPORT_STATE default_port_pars = {
PORT_BAUD_RATE_9600,
PORT_8_BITS,
@@ -85,16 +88,15 @@
p_port->dlci = dlci;
p_port->bd_addr = bd_addr;
rfc_cb.rfc.last_port_index = port_index;
- LOG_VERBOSE(
- "%s: rfc_cb.port.port[%d]:%p chosen, "
- "last_port_index:%d, bd_addr=%s",
- __func__, port_index, p_port, rfc_cb.rfc.last_port_index,
+ log::verbose(
+ "rfc_cb.port.port[{}]:{} chosen, last_port_index:{}, bd_addr={}",
+ port_index, fmt::ptr(p_port), rfc_cb.rfc.last_port_index,
ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return p_port;
}
}
- LOG(WARNING) << __func__ << ": running out of free ports for dlci "
- << std::to_string(dlci) << ", bd_addr " << bd_addr;
+ log::warn("running out of free ports for dlci {}, bd_addr {}", dlci,
+ ADDRESS_TO_LOGGABLE_STR(bd_addr));
return nullptr;
}
@@ -151,7 +153,8 @@
get_btm_client_interface().peer.BTM_GetMaxPacketSize(p_port->bd_addr);
if (packet_size == 0) {
/* something is very wrong */
- LOG(WARNING) << __func__ << ": bad packet size 0 for" << p_port->bd_addr;
+ log::warn("bad packet size 0 for{}",
+ ADDRESS_TO_LOGGABLE_STR(p_port->bd_addr));
p_port->mtu = RFCOMM_DEFAULT_MTU;
} else {
/* We try to negotiate MTU that each packet can be split into whole
@@ -171,16 +174,14 @@
p_port->mtu = ((L2CAP_MTU_SIZE + L2CAP_PKT_OVERHEAD) / packet_size *
packet_size) -
RFCOMM_DATA_OVERHEAD - L2CAP_PKT_OVERHEAD;
- LOG_VERBOSE("%s: selected %d based on connection speed", __func__,
- p_port->mtu);
+ log::verbose("selected {} based on connection speed", p_port->mtu);
} else {
p_port->mtu = L2CAP_MTU_SIZE - RFCOMM_DATA_OVERHEAD;
- LOG_VERBOSE("%s: selected %d based on l2cap PDU size", __func__,
- p_port->mtu);
+ log::verbose("selected {} based on l2cap PDU size", p_port->mtu);
}
}
} else {
- LOG_VERBOSE("%s: application selected %d", __func__, p_port->mtu);
+ log::verbose("application selected {}", p_port->mtu);
}
p_port->credit_rx_max = (PORT_RX_HIGH_WM / p_port->mtu);
if (p_port->credit_rx_max > PORT_RX_BUF_HIGH_WM)
@@ -191,9 +192,9 @@
p_port->rx_buf_critical = (PORT_RX_CRITICAL_WM / p_port->mtu);
if (p_port->rx_buf_critical > PORT_RX_BUF_CRITICAL_WM)
p_port->rx_buf_critical = PORT_RX_BUF_CRITICAL_WM;
- LOG_VERBOSE("%s: credit_rx_max %d, credit_rx_low %d, rx_buf_critical %d",
- __func__, p_port->credit_rx_max, p_port->credit_rx_low,
- p_port->rx_buf_critical);
+ log::verbose("credit_rx_max {}, credit_rx_low {}, rx_buf_critical {}",
+ p_port->credit_rx_max, p_port->credit_rx_low,
+ p_port->rx_buf_critical);
}
/*******************************************************************************
@@ -206,8 +207,8 @@
*
******************************************************************************/
void port_release_port(tPORT* p_port) {
- LOG_VERBOSE("%s p_port: %p state: %d keep_handle: %d", __func__, p_port,
- p_port->rfc.state, p_port->keep_port_handle);
+ log::verbose("p_port: {} state: {} keep_handle: {}", fmt::ptr(p_port),
+ p_port->rfc.state, p_port->keep_port_handle);
mutex_global_lock();
BT_HDR* p_buf;
@@ -246,7 +247,7 @@
mutex_global_unlock();
if (p_port->keep_port_handle) {
- LOG_VERBOSE("%s Re-initialize handle: %d", __func__, p_port->handle);
+ log::verbose("Re-initialize handle: {}", p_port->handle);
/* save event mask and callback */
uint32_t mask = p_port->ev_mask;
@@ -268,7 +269,7 @@
p_port->local_ctrl.modem_signal = p_port->default_signal_state;
p_port->bd_addr = RawAddress::kAny;
} else {
- LOG_VERBOSE("%s Clean-up handle: %d", __func__, p_port->handle);
+ log::verbose("Clean-up handle: {}", p_port->handle);
alarm_free(p_port->rfc.port_timer);
memset(p_port, 0, sizeof(tPORT));
}
@@ -287,13 +288,13 @@
for (tRFC_MCB& mcb : rfc_cb.port.rfc_mcb) {
if ((mcb.state != RFC_MX_STATE_IDLE) && (mcb.bd_addr == bd_addr)) {
/* Multiplexer channel found do not change anything */
- LOG_VERBOSE("found, bd_addr:%s, rfc_mcb:%p, lcid:%s",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), &mcb,
- loghex(mcb.lcid).c_str());
+ log::verbose("found, bd_addr:{}, rfc_mcb:{}, lcid:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(bd_addr), fmt::ptr(&mcb),
+ loghex(mcb.lcid));
return &mcb;
}
}
- LOG_WARN("not found, bd_addr:%s", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
+ log::warn("not found, bd_addr:{}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
return nullptr;
}
@@ -311,22 +312,21 @@
******************************************************************************/
tPORT* port_find_mcb_dlci_port(tRFC_MCB* p_mcb, uint8_t dlci) {
if (!p_mcb) {
- LOG(ERROR) << __func__ << ": p_mcb is null, dlci=" << std::to_string(dlci);
+ log::error("p_mcb is null, dlci={}", dlci);
return nullptr;
}
if (dlci > RFCOMM_MAX_DLCI) {
- LOG(WARNING) << __func__ << ": DLCI " << std::to_string(dlci)
- << " is too large, bd_addr=" << p_mcb->bd_addr
- << ", p_mcb=" << p_mcb;
+ log::warn("DLCI {} is too large, bd_addr={}, p_mcb={}", dlci,
+ ADDRESS_TO_LOGGABLE_STR(p_mcb->bd_addr), fmt::ptr(p_mcb));
return nullptr;
}
uint8_t handle = p_mcb->port_handles[dlci];
if (handle == 0) {
- LOG(INFO) << __func__ << ": Cannot find allocated RFCOMM app port for DLCI "
- << std::to_string(dlci) << " on " << p_mcb->bd_addr
- << ", p_mcb=" << p_mcb;
+ log::info(
+ "Cannot find allocated RFCOMM app port for DLCI {} on {}, p_mcb={}",
+ dlci, ADDRESS_TO_LOGGABLE_STR(p_mcb->bd_addr), fmt::ptr(p_mcb));
return nullptr;
}
return &rfc_cb.port.port[handle - 1];
@@ -521,7 +521,7 @@
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) {
- LOG_VERBOSE("PORT_DataInd Data reached HW. Sending FC set.");
+ log::verbose("PORT_DataInd Data reached HW. Sending FC set.");
p_port->rx.peer_fc = true;
RFCOMM_FlowReq(p_port->rfc.p_mcb, p_port->dlci, false);
diff --git a/system/stack/rfcomm/rfc_event.h b/system/stack/rfcomm/rfc_event.h
index 47f4f46..5ba2ad6 100644
--- a/system/stack/rfcomm/rfc_event.h
+++ b/system/stack/rfcomm/rfc_event.h
@@ -16,6 +16,8 @@
#pragma once
+#include <bluetooth/log.h>
+
#include <cstdint>
#include "macros.h"
@@ -136,3 +138,12 @@
return std::string("UNKNOWN[") + std::to_string(event) + std::string("]");
}
}
+
+namespace fmt {
+template <>
+struct formatter<tRFC_EVENT> : enum_formatter<tRFC_EVENT> {};
+template <>
+struct formatter<tRFC_MX_EVENT> : enum_formatter<tRFC_MX_EVENT> {};
+template <>
+struct formatter<tRFC_PORT_EVENT> : enum_formatter<tRFC_PORT_EVENT> {};
+} // namespace fmt
diff --git a/system/stack/rfcomm/rfc_l2cap_if.cc b/system/stack/rfcomm/rfc_l2cap_if.cc
index 5bc9301..907889a 100644
--- a/system/stack/rfcomm/rfc_l2cap_if.cc
+++ b/system/stack/rfcomm/rfc_l2cap_if.cc
@@ -23,6 +23,7 @@
******************************************************************************/
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <cstddef>
#include <cstdint>
@@ -40,6 +41,8 @@
#include "stack/rfcomm/rfc_int.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
/*
* Define Callback functions to be called by L2CAP
*/
@@ -101,9 +104,9 @@
* continues as initiator */
/* if timeout, local device disconnects outgoing connection and continues
* as acceptor */
- LOG_VERBOSE(
+ log::verbose(
"RFCOMM_ConnectInd start timer for collision, initiator's "
- "LCID(0x%x), acceptor's LCID(0x%x)",
+ "LCID(0x{:x}), acceptor's LCID(0x{:x})",
p_mcb->lcid, p_mcb->pending_lcid);
rfc_timer_start(
@@ -142,7 +145,7 @@
tRFC_MCB* p_mcb = rfc_find_lcid_mcb(lcid);
if (!p_mcb) {
- LOG_ERROR("RFCOMM_ConnectCnf LCID:0x%x", lcid);
+ log::error("RFCOMM_ConnectCnf LCID:0x{:x}", lcid);
return;
}
@@ -152,8 +155,8 @@
if (result != L2CAP_CONN_OK) {
return;
} else {
- LOG_VERBOSE("RFCOMM_ConnectCnf peer gave up pending LCID(0x%x)",
- p_mcb->pending_lcid);
+ log::verbose("RFCOMM_ConnectCnf peer gave up pending LCID(0x{:x})",
+ p_mcb->pending_lcid);
/* Peer gave up its connection request, make sure cleaning up L2CAP
* channel */
@@ -180,14 +183,14 @@
******************************************************************************/
void RFCOMM_ConfigInd(uint16_t lcid, tL2CAP_CFG_INFO* p_cfg) {
if (p_cfg == nullptr) {
- LOG_ERROR("Received l2cap configuration info with nullptr");
+ log::error("Received l2cap configuration info with nullptr");
return;
}
tRFC_MCB* p_mcb = rfc_find_lcid_mcb(lcid);
if (!p_mcb) {
- LOG_ERROR("RFCOMM_ConfigInd LCID:0x%x", lcid);
+ log::error("RFCOMM_ConfigInd LCID:0x{:x}", lcid);
for (auto& [cid, mcb] : rfc_lcid_mcb) {
if (mcb != nullptr && mcb->pending_lcid == lcid) {
tL2CAP_CFG_INFO l2cap_cfg_info(*p_cfg);
@@ -218,7 +221,7 @@
tRFC_MCB* p_mcb = rfc_find_lcid_mcb(lcid);
if (!p_mcb) {
- LOG_ERROR("RFCOMM_ConfigCnf no MCB LCID:0x%x", lcid);
+ log::error("RFCOMM_ConfigCnf no MCB LCID:0x{:x}", lcid);
return;
}
uintptr_t result_as_ptr = L2CAP_CFG_OK;
@@ -234,11 +237,10 @@
*
******************************************************************************/
void RFCOMM_DisconnectInd(uint16_t lcid, bool is_conf_needed) {
- LOG_VERBOSE("lcid:%s, is_conf_needed:%d", loghex(lcid).c_str(),
- is_conf_needed);
+ log::verbose("lcid:{}, is_conf_needed:{}", loghex(lcid), is_conf_needed);
tRFC_MCB* p_mcb = rfc_find_lcid_mcb(lcid);
if (!p_mcb) {
- LOG(WARNING) << __func__ << ": no mcb for lcid " << loghex(lcid);
+ log::warn("no mcb for lcid {}", loghex(lcid));
return;
}
rfc_mx_sm_execute(p_mcb, RFC_MX_EVENT_DISC_IND, nullptr);
@@ -258,8 +260,7 @@
tRFC_MCB* p_mcb = rfc_find_lcid_mcb(lcid);
if (!p_mcb) {
- LOG(WARNING) << __func__ << ": Cannot find RFCOMM multiplexer for lcid "
- << loghex(lcid);
+ log::warn("Cannot find RFCOMM multiplexer for lcid {}", loghex(lcid));
osi_free(p_buf);
return;
}
@@ -268,15 +269,16 @@
/* If the frame did not pass validation just ignore it */
if (event == RFC_EVENT_BAD_FRAME) {
- LOG(WARNING) << __func__ << ": Bad RFCOMM frame from lcid=" << loghex(lcid)
- << ", bd_addr=" << p_mcb->bd_addr << ", p_mcb=" << p_mcb;
+ log::warn("Bad RFCOMM frame from lcid={}, bd_addr={}, p_mcb={}",
+ loghex(lcid), ADDRESS_TO_LOGGABLE_STR(p_mcb->bd_addr),
+ fmt::ptr(p_mcb));
osi_free(p_buf);
return;
}
if (rfc_cb.rfc.rx_frame.dlci == RFCOMM_MX_DLCI) {
- LOG_VERBOSE("%s: handle multiplexer event %d, p_mcb=%p", __func__, event,
- p_mcb);
+ log::verbose("handle multiplexer event {}, p_mcb={}", event,
+ fmt::ptr(p_mcb));
/* Take special care of the Multiplexer Control Messages */
if (event == RFC_EVENT_UIH) {
rfc_process_mx_message(p_mcb, p_buf);
@@ -294,14 +296,14 @@
if (p_port == nullptr || !p_port->rfc.p_mcb) {
/* If this is a SABME on new port, check if any app is waiting for it */
if (event != RFC_EVENT_SABME) {
- LOG(WARNING) << __func__
- << ": no for none-SABME event, lcid=" << loghex(lcid)
- << ", bd_addr=" << p_mcb->bd_addr << ", p_mcb=" << p_mcb;
+ log::warn("no for none-SABME event, lcid={}, bd_addr={}, p_mcb={}",
+ loghex(lcid), ADDRESS_TO_LOGGABLE_STR(p_mcb->bd_addr),
+ fmt::ptr(p_mcb));
if ((p_mcb->is_initiator && !rfc_cb.rfc.rx_frame.cr) ||
(!p_mcb->is_initiator && rfc_cb.rfc.rx_frame.cr)) {
- LOG(ERROR) << __func__
- << ": Disconnecting RFCOMM, lcid=" << loghex(lcid)
- << ", bd_addr=" << p_mcb->bd_addr << ", p_mcb=" << p_mcb;
+ log::error("Disconnecting RFCOMM, lcid={}, bd_addr={}, p_mcb={}",
+ loghex(lcid), ADDRESS_TO_LOGGABLE_STR(p_mcb->bd_addr),
+ fmt::ptr(p_mcb));
rfc_send_dm(p_mcb, rfc_cb.rfc.rx_frame.dlci, rfc_cb.rfc.rx_frame.pf);
}
osi_free(p_buf);
@@ -310,24 +312,26 @@
p_port = port_find_dlci_port(rfc_cb.rfc.rx_frame.dlci);
if (p_port == nullptr) {
- LOG(ERROR) << __func__ << ":Disconnecting RFCOMM, no port for dlci "
- << +rfc_cb.rfc.rx_frame.dlci << ", lcid=" << loghex(lcid)
- << ", bd_addr=" << p_mcb->bd_addr << ", p_mcb=" << p_mcb;
+ log::error(
+ "Disconnecting RFCOMM, no port for dlci {}, lcid={}, bd_addr={}, "
+ "p_mcb={}",
+ rfc_cb.rfc.rx_frame.dlci, loghex(lcid),
+ ADDRESS_TO_LOGGABLE_STR(p_mcb->bd_addr), fmt::ptr(p_mcb));
rfc_send_dm(p_mcb, rfc_cb.rfc.rx_frame.dlci, true);
osi_free(p_buf);
return;
}
- LOG_VERBOSE("%s: port_handles[dlci=%d]:%d->%d, p_mcb=%p", __func__,
- rfc_cb.rfc.rx_frame.dlci,
- p_mcb->port_handles[rfc_cb.rfc.rx_frame.dlci], p_port->handle,
- p_mcb);
+ log::verbose("port_handles[dlci={}]:{}->{}, p_mcb={}",
+ rfc_cb.rfc.rx_frame.dlci,
+ p_mcb->port_handles[rfc_cb.rfc.rx_frame.dlci], p_port->handle,
+ fmt::ptr(p_mcb));
p_mcb->port_handles[rfc_cb.rfc.rx_frame.dlci] = p_port->handle;
p_port->rfc.p_mcb = p_mcb;
}
if (event == RFC_EVENT_UIH) {
- LOG_VERBOSE("%s: Handling UIH event, buf_len=%u, credit=%u", __func__,
- p_buf->len, rfc_cb.rfc.rx_frame.credit);
+ log::verbose("Handling UIH event, buf_len={}, credit={}", p_buf->len,
+ rfc_cb.rfc.rx_frame.credit);
if (p_buf->len > 0) {
rfc_port_sm_execute(p_port, static_cast<tRFC_PORT_EVENT>(event), p_buf);
} else {
@@ -356,10 +360,10 @@
tRFC_MCB* p_mcb = rfc_find_lcid_mcb(lcid);
if (!p_mcb) {
- LOG_ERROR("RFCOMM_CongestionStatusInd dropped LCID:0x%x", lcid);
+ log::error("RFCOMM_CongestionStatusInd dropped LCID:0x{:x}", lcid);
return;
} else {
- LOG_VERBOSE("RFCOMM_CongestionStatusInd LCID:0x%x", lcid);
+ log::verbose("RFCOMM_CongestionStatusInd LCID:0x{:x}", lcid);
}
rfc_process_l2cap_congestion(p_mcb, is_congested);
}
@@ -375,8 +379,8 @@
tRFC_MCB* p_mcb = rfc_lcid_mcb[lcid];
if (p_mcb != nullptr) {
if (p_mcb->lcid != lcid) {
- LOG(WARNING) << __func__ << "LCID reused lcid=:" << loghex(lcid)
- << ", current_lcid=" << loghex(p_mcb->lcid);
+ log::warn("LCID reused lcid=:{}, current_lcid={}", loghex(lcid),
+ loghex(p_mcb->lcid));
return nullptr;
}
}
diff --git a/system/stack/rfcomm/rfc_mx_fsm.cc b/system/stack/rfcomm/rfc_mx_fsm.cc
index 0d99fd3..e406670 100644
--- a/system/stack/rfcomm/rfc_mx_fsm.cc
+++ b/system/stack/rfcomm/rfc_mx_fsm.cc
@@ -24,6 +24,7 @@
******************************************************************************/
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <cstdint>
@@ -40,6 +41,8 @@
#define L2CAP_SUCCESS 0
#define L2CAP_ERROR 1
+using namespace bluetooth;
+
/******************************************************************************/
/* L O C A L F U N C T I O N P R O T O T Y P E S */
/******************************************************************************/
@@ -74,10 +77,9 @@
void rfc_mx_sm_execute(tRFC_MCB* p_mcb, tRFC_MX_EVENT event, void* p_data) {
CHECK(p_mcb != nullptr) << __func__ << ": NULL mcb for event " << event;
- LOG_INFO(
- "RFCOMM peer:%s event:%d state:%s",
- ADDRESS_TO_LOGGABLE_CSTR(p_mcb->bd_addr), event,
- rfcomm_mx_state_text(static_cast<tRFC_MX_STATE>(p_mcb->state)).c_str());
+ log::info("RFCOMM peer:{} event:{} state:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_mcb->bd_addr), event,
+ rfcomm_mx_state_text(static_cast<tRFC_MX_STATE>(p_mcb->state)));
switch (p_mcb->state) {
case RFC_MX_STATE_IDLE:
@@ -109,8 +111,8 @@
break;
default:
- LOG_ERROR("Received unexpected event:%hu in state:%hhu", event,
- p_mcb->state);
+ log::error("Received unexpected event:{} in state:{}", event,
+ p_mcb->state);
}
}
@@ -133,8 +135,8 @@
uint16_t lcid = L2CA_ConnectReq(BT_PSM_RFCOMM, p_mcb->bd_addr);
if (lcid == 0) {
- LOG(ERROR) << __func__ << ": failed to open L2CAP channel for "
- << p_mcb->bd_addr;
+ log::error("failed to open L2CAP channel for {}",
+ ADDRESS_TO_LOGGABLE_STR(p_mcb->bd_addr));
rfc_save_lcid_mcb(nullptr, p_mcb->lcid);
p_mcb->lcid = 0;
PORT_StartCnf(p_mcb, RFCOMM_ERROR);
@@ -171,10 +173,10 @@
return;
default:
- LOG_ERROR("Mx error state %d event %d", p_mcb->state, event);
+ log::error("Mx error state {} event {}", p_mcb->state, event);
return;
}
- LOG_VERBOSE("RFCOMM MX ignored - evt:%d in state:%d", event, p_mcb->state);
+ log::verbose("RFCOMM MX ignored - evt:{} in state:{}", event, p_mcb->state);
}
/*******************************************************************************
@@ -189,10 +191,10 @@
******************************************************************************/
void rfc_mx_sm_state_wait_conn_cnf(tRFC_MCB* p_mcb, tRFC_MX_EVENT event,
void* p_data) {
- LOG_VERBOSE("%s: evt %d", __func__, event);
+ log::verbose("evt {}", event);
switch (event) {
case RFC_MX_EVENT_START_REQ:
- LOG_ERROR("Mx error state %d event %d", p_mcb->state, event);
+ log::error("Mx error state {} event {}", p_mcb->state, event);
return;
/* There is some new timing so that Config Ind comes before security is
@@ -226,9 +228,9 @@
uint16_t i;
uint8_t handle;
- LOG_VERBOSE(
- "RFCOMM MX retry as acceptor in collision case - evt:%d in "
- "state:%d",
+ log::verbose(
+ "RFCOMM MX retry as acceptor in collision case - evt:{} in "
+ "state:{}",
event, p_mcb->state);
rfc_save_lcid_mcb(NULL, p_mcb->lcid);
@@ -244,8 +246,8 @@
p_mcb->port_handles[i] = 0;
p_mcb->port_handles[i + 1] = handle;
rfc_cb.port.port[handle - 1].dlci += 1;
- LOG_VERBOSE("RFCOMM MX - DLCI:%d -> %d", i,
- rfc_cb.port.port[handle - 1].dlci);
+ log::verbose("RFCOMM MX - DLCI:{} -> {}", i,
+ rfc_cb.port.port[handle - 1].dlci);
}
}
@@ -255,10 +257,10 @@
}
return;
default:
- LOG_ERROR("Received unexpected event:%hu in state:%hhu", event,
- p_mcb->state);
+ log::error("Received unexpected event:{} in state:{}", event,
+ p_mcb->state);
}
- LOG_VERBOSE("RFCOMM MX ignored - evt:%d in state:%d", event, p_mcb->state);
+ log::verbose("RFCOMM MX ignored - evt:{} in state:{}", event, p_mcb->state);
}
/*******************************************************************************
@@ -273,12 +275,12 @@
******************************************************************************/
void rfc_mx_sm_state_configure(tRFC_MCB* p_mcb, tRFC_MX_EVENT event,
void* p_data) {
- LOG_VERBOSE("%s: event %d", __func__, event);
+ log::verbose("event {}", event);
switch (event) {
case RFC_MX_EVENT_START_REQ:
case RFC_MX_EVENT_CONN_CNF:
- LOG_ERROR("Mx error state %d event %d", p_mcb->state, event);
+ log::error("Mx error state {} event {}", p_mcb->state, event);
return;
case RFC_MX_EVENT_CONF_IND:
@@ -295,18 +297,18 @@
return;
case RFC_MX_EVENT_TIMEOUT:
- LOG(ERROR) << __func__ << ": L2CAP configuration timeout for "
- << p_mcb->bd_addr;
+ log::error("L2CAP configuration timeout for {}",
+ ADDRESS_TO_LOGGABLE_STR(p_mcb->bd_addr));
p_mcb->state = RFC_MX_STATE_IDLE;
L2CA_DisconnectReq(p_mcb->lcid);
PORT_StartCnf(p_mcb, RFCOMM_ERROR);
return;
default:
- LOG_ERROR("Received unexpected event:%hu in state:%hhu", event,
- p_mcb->state);
+ log::error("Received unexpected event:{} in state:{}", event,
+ p_mcb->state);
}
- LOG_VERBOSE("RFCOMM MX ignored - evt:%d in state:%d", event, p_mcb->state);
+ log::verbose("RFCOMM MX ignored - evt:{} in state:{}", event, p_mcb->state);
}
/*******************************************************************************
@@ -321,11 +323,11 @@
******************************************************************************/
void rfc_mx_sm_sabme_wait_ua(tRFC_MCB* p_mcb, tRFC_MX_EVENT event,
UNUSED_ATTR void* p_data) {
- LOG_VERBOSE("%s: event %d", __func__, event);
+ log::verbose("event {}", event);
switch (event) {
case RFC_MX_EVENT_START_REQ:
case RFC_MX_EVENT_CONN_CNF:
- LOG_ERROR("Mx error state %d event %d", p_mcb->state, event);
+ log::error("Mx error state {} event {}", p_mcb->state, event);
return;
/* workaround: we don't support reconfig */
@@ -366,10 +368,10 @@
PORT_StartCnf(p_mcb, RFCOMM_ERROR);
return;
default:
- LOG_ERROR("Received unexpected event:%hu in state:%hhu", event,
- p_mcb->state);
+ log::error("Received unexpected event:{} in state:{}", event,
+ p_mcb->state);
}
- LOG_VERBOSE("RFCOMM MX ignored - evt:%d in state:%d", event, p_mcb->state);
+ log::verbose("RFCOMM MX ignored - evt:{} in state:{}", event, p_mcb->state);
}
/*******************************************************************************
@@ -384,7 +386,7 @@
******************************************************************************/
void rfc_mx_sm_state_wait_sabme(tRFC_MCB* p_mcb, tRFC_MX_EVENT event,
void* p_data) {
- LOG_VERBOSE("%s: event %d", __func__, event);
+ log::verbose("event {}", event);
switch (event) {
case RFC_MX_EVENT_DISC_IND:
p_mcb->state = RFC_MX_STATE_IDLE;
@@ -432,9 +434,9 @@
return;
default:
- LOG_WARN("RFCOMM MX ignored - evt:%d in state:%d", event, p_mcb->state);
+ log::warn("RFCOMM MX ignored - evt:{} in state:{}", event, p_mcb->state);
}
- LOG_VERBOSE("RFCOMM MX ignored - evt:%d in state:%d", event, p_mcb->state);
+ log::verbose("RFCOMM MX ignored - evt:{} in state:{}", event, p_mcb->state);
}
/*******************************************************************************
@@ -449,7 +451,7 @@
******************************************************************************/
void rfc_mx_sm_state_connected(tRFC_MCB* p_mcb, tRFC_MX_EVENT event,
UNUSED_ATTR void* p_data) {
- LOG_VERBOSE("%s: event %d", __func__, event);
+ log::verbose("event {}", event);
switch (event) {
case RFC_MX_EVENT_TIMEOUT:
@@ -475,10 +477,10 @@
PORT_CloseInd(p_mcb);
return;
default:
- LOG_ERROR("Received unexpected event:%hu in state:%hhu", event,
- p_mcb->state);
+ log::error("Received unexpected event:{} in state:{}", event,
+ p_mcb->state);
}
- LOG_VERBOSE("RFCOMM MX ignored - evt:%d in state:%d", event, p_mcb->state);
+ log::verbose("RFCOMM MX ignored - evt:{} in state:{}", event, p_mcb->state);
}
/*******************************************************************************
@@ -495,7 +497,7 @@
void* p_data) {
BT_HDR* p_buf;
- LOG_VERBOSE("%s: event %d", __func__, event);
+ log::verbose("event {}", event);
switch (event) {
case RFC_MX_EVENT_UA:
case RFC_MX_EVENT_DM:
@@ -554,10 +556,10 @@
case RFC_MX_EVENT_QOS_VIOLATION_IND:
break;
default:
- LOG_ERROR("Received unexpected event:%hu in state:%hhu", event,
- p_mcb->state);
+ log::error("Received unexpected event:{} in state:{}", event,
+ p_mcb->state);
}
- LOG_VERBOSE("RFCOMM MX ignored - evt:%d in state:%d", event, p_mcb->state);
+ log::verbose("RFCOMM MX ignored - evt:{} in state:{}", event, p_mcb->state);
}
void rfc_on_l2cap_error(uint16_t lcid, uint16_t result) {
@@ -568,8 +570,9 @@
/* if peer rejects our connect request but peer's connect request is pending
*/
if (p_mcb->pending_lcid) {
- LOG_VERBOSE("RFCOMM_ConnectCnf retry as acceptor on pending LCID(0x%x)",
- p_mcb->pending_lcid);
+ log::verbose(
+ "RFCOMM_ConnectCnf retry as acceptor on pending LCID(0x{:x})",
+ p_mcb->pending_lcid);
/* remove mcb from mapping table */
rfc_save_lcid_mcb(NULL, p_mcb->lcid);
@@ -588,13 +591,13 @@
p_mcb->port_handles[i] = 0;
p_mcb->port_handles[i + 1] = handle;
rfc_cb.port.port[handle - 1].dlci += 1;
- LOG_VERBOSE("RFCOMM MX, port_handle=%d, DLCI[%d->%d]", handle, i,
- rfc_cb.port.port[handle - 1].dlci);
+ log::verbose("RFCOMM MX, port_handle={}, DLCI[{}->{}]", handle, i,
+ rfc_cb.port.port[handle - 1].dlci);
}
}
rfc_mx_sm_execute(p_mcb, RFC_MX_EVENT_CONN_IND, nullptr);
if (p_mcb->pending_configure_complete) {
- LOG_INFO("Configuration of the pending connection was completed");
+ log::info("Configuration of the pending connection was completed");
p_mcb->pending_configure_complete = false;
uintptr_t result_as_ptr = L2CAP_CFG_OK;
rfc_mx_sm_execute(p_mcb, RFC_MX_EVENT_CONF_IND,
@@ -607,11 +610,11 @@
p_mcb->lcid = lcid;
rfc_mx_sm_execute(p_mcb, RFC_MX_EVENT_CONN_CNF, &result);
} else if (result == L2CAP_CFG_FAILED_NO_REASON) {
- LOG(ERROR) << __func__ << ": failed to configure L2CAP for "
- << p_mcb->bd_addr;
+ log::error("failed to configure L2CAP for {}",
+ ADDRESS_TO_LOGGABLE_STR(p_mcb->bd_addr));
if (p_mcb->is_initiator) {
- LOG(ERROR) << __func__ << ": disconnect L2CAP due to config failure for "
- << p_mcb->bd_addr;
+ log::error("disconnect L2CAP due to config failure for {}",
+ ADDRESS_TO_LOGGABLE_STR(p_mcb->bd_addr));
PORT_StartCnf(p_mcb, result);
L2CA_DisconnectReq(p_mcb->lcid);
}
diff --git a/system/stack/rfcomm/rfc_port_fsm.cc b/system/stack/rfcomm/rfc_port_fsm.cc
index b9724c3..08d7fb3 100644
--- a/system/stack/rfcomm/rfc_port_fsm.cc
+++ b/system/stack/rfcomm/rfc_port_fsm.cc
@@ -24,6 +24,7 @@
******************************************************************************/
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <cstdint>
#include <cstring>
@@ -42,6 +43,8 @@
#include "stack/rfcomm/port_int.h"
#include "stack/rfcomm/rfc_int.h"
+using namespace bluetooth;
+
static const std::set<uint16_t> uuid_logging_acceptlist = {
UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY,
UUID_SERVCLASS_AG_HANDSFREE,
@@ -81,9 +84,9 @@
******************************************************************************/
void rfc_port_sm_execute(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) {
CHECK(p_port != nullptr) << __func__ << ": NULL port event " << event;
- LOG_INFO("bd_addr:%s, port:%u, state:%u, event:%d",
- ADDRESS_TO_LOGGABLE_CSTR(p_port->bd_addr), p_port->handle,
- p_port->rfc.state, event);
+ log::info("bd_addr:{}, port:{}, state:{}, event:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_port->bd_addr), p_port->handle,
+ p_port->rfc.state, event);
switch (p_port->rfc.state) {
case RFC_STATE_CLOSED:
rfc_port_sm_state_closed(p_port, event, p_data);
@@ -158,7 +161,7 @@
return;
case RFC_PORT_EVENT_DM:
- LOG_WARN("%s, RFC_EVENT_DM, index=%d", __func__, p_port->handle);
+ log::warn("RFC_EVENT_DM, index={}", p_port->handle);
rfc_port_closed(p_port);
return;
@@ -173,14 +176,14 @@
case RFC_PORT_EVENT_TIMEOUT:
PORT_TimeOutCloseMux(p_port->rfc.p_mcb);
- LOG_ERROR("Port error state %d event %d", p_port->rfc.state, event);
+ log::error("Port error state {} event {}", p_port->rfc.state, event);
return;
default:
- LOG_ERROR("Received unexpected event:%hu in state:%hhu", event,
- p_port->rfc.state);
+ log::error("Received unexpected event:{} in state:{}", event,
+ p_port->rfc.state);
}
- LOG_WARN("Port state closed Event ignored %d", event);
+ log::warn("Port state closed Event ignored {}", event);
return;
}
@@ -199,7 +202,7 @@
switch (event) {
case RFC_PORT_EVENT_OPEN:
case RFC_PORT_EVENT_ESTABLISH_RSP:
- LOG_ERROR("Port error state %d event %d", p_port->rfc.state, event);
+ log::error("Port error state {} event {}", p_port->rfc.state, event);
return;
case RFC_PORT_EVENT_CLOSE:
@@ -210,7 +213,7 @@
return;
case RFC_PORT_EVENT_CLEAR:
- LOG_WARN("%s, RFC_PORT_EVENT_CLEAR, index=%d", __func__, p_port->handle);
+ log::warn("RFC_PORT_EVENT_CLEAR, index={}", p_port->handle);
rfc_port_closed(p_port);
return;
@@ -251,7 +254,7 @@
return;
case RFC_PORT_EVENT_DM:
- LOG_WARN("%s, RFC_EVENT_DM, index=%d", __func__, p_port->handle);
+ log::warn("RFC_EVENT_DM, index={}", p_port->handle);
p_port->rfc.p_mcb->is_disc_initiator = true;
PORT_DlcEstablishCnf(p_port->rfc.p_mcb, p_port->dlci,
p_port->rfc.p_mcb->peer_l2cap_mtu, RFCOMM_ERROR);
@@ -259,7 +262,7 @@
return;
case RFC_PORT_EVENT_DISC:
- LOG_WARN("%s, RFC_EVENT_DISC, index=%d", __func__, p_port->handle);
+ log::warn("RFC_EVENT_DISC, index={}", p_port->handle);
rfc_send_ua(p_port->rfc.p_mcb, p_port->dlci);
PORT_DlcEstablishCnf(p_port->rfc.p_mcb, p_port->dlci,
p_port->rfc.p_mcb->peer_l2cap_mtu, RFCOMM_ERROR);
@@ -281,10 +284,10 @@
p_port->rfc.p_mcb->peer_l2cap_mtu, RFCOMM_ERROR);
return;
default:
- LOG_ERROR("Received unexpected event:%hu in state:%hhu", event,
- p_port->rfc.state);
+ log::error("Received unexpected event:{} in state:{}", event,
+ p_port->rfc.state);
}
- LOG_WARN("Port state sabme_wait_ua Event ignored %d", event);
+ log::warn("Port state sabme_wait_ua Event ignored {}", event);
}
/*******************************************************************************
@@ -319,17 +322,17 @@
case RFC_PORT_EVENT_OPEN:
case RFC_PORT_EVENT_CLOSE:
- LOG_ERROR("Port error state %d event %d", p_port->rfc.state, event);
+ log::error("Port error state {} event {}", p_port->rfc.state, event);
return;
case RFC_PORT_EVENT_CLEAR:
- LOG_WARN("%s, RFC_PORT_EVENT_CLEAR, index=%d", __func__, p_port->handle);
+ log::warn("RFC_PORT_EVENT_CLEAR, index={}", p_port->handle);
btm_sec_abort_access_req(p_port->rfc.p_mcb->bd_addr);
rfc_port_closed(p_port);
return;
case RFC_PORT_EVENT_DATA:
- LOG_ERROR("Port error state Term Wait Sec event Data");
+ log::error("Port error state Term Wait Sec event Data");
osi_free(p_data);
return;
@@ -383,10 +386,10 @@
}
return;
default:
- LOG_ERROR("Received unexpected event:%hu in state:%hhu", event,
- p_port->rfc.state);
+ log::error("Received unexpected event:{} in state:{}", event,
+ p_port->rfc.state);
}
- LOG_WARN("Port state term_wait_sec_check Event ignored %d", event);
+ log::warn("Port state term_wait_sec_check Event ignored {}", event);
}
/*******************************************************************************
@@ -405,8 +408,8 @@
switch (event) {
case RFC_PORT_EVENT_SEC_COMPLETE:
if (*((uint8_t*)p_data) != BTM_SUCCESS) {
- LOG_ERROR("%s, RFC_PORT_EVENT_SEC_COMPLETE, index=%d, result=%d",
- __func__, p_port->handle, *((uint8_t*)p_data));
+ log::error("RFC_PORT_EVENT_SEC_COMPLETE, index={}, result={}",
+ p_port->handle, *((uint8_t*)p_data));
p_port->rfc.p_mcb->is_disc_initiator = true;
PORT_DlcEstablishCnf(p_port->rfc.p_mcb, p_port->dlci, 0,
RFCOMM_SECURITY_ERR);
@@ -420,17 +423,17 @@
case RFC_PORT_EVENT_OPEN:
case RFC_PORT_EVENT_SABME: /* Peer should not use the same dlci */
- LOG_ERROR("Port error state %d event %d", p_port->rfc.state, event);
+ log::error("Port error state {} event {}", p_port->rfc.state, event);
return;
case RFC_PORT_EVENT_CLOSE:
- LOG_WARN("%s, RFC_PORT_EVENT_CLOSE, index=%d", __func__, p_port->handle);
+ log::warn("RFC_PORT_EVENT_CLOSE, index={}", p_port->handle);
btm_sec_abort_access_req(p_port->rfc.p_mcb->bd_addr);
rfc_port_closed(p_port);
return;
case RFC_PORT_EVENT_DATA:
- LOG_ERROR("Port error state Orig Wait Sec event Data");
+ log::error("Port error state Orig Wait Sec event Data");
osi_free(p_data);
return;
@@ -438,10 +441,10 @@
osi_free(p_data);
return;
default:
- LOG_ERROR("Received unexpected event:%hu in state:%hhu", event,
- p_port->rfc.state);
+ log::error("Received unexpected event:{} in state:{}", event,
+ p_port->rfc.state);
}
- LOG_WARN("Port state orig_wait_sec_check Event ignored %d", event);
+ log::warn("Port state orig_wait_sec_check Event ignored {}", event);
}
/*******************************************************************************
@@ -457,7 +460,7 @@
void rfc_port_sm_opened(tPORT* p_port, tRFC_PORT_EVENT event, void* p_data) {
switch (event) {
case RFC_PORT_EVENT_OPEN:
- LOG_ERROR("Port error state %d event %d", p_port->rfc.state, event);
+ log::error("Port error state {} event {}", p_port->rfc.state, event);
return;
case RFC_PORT_EVENT_CLOSE:
@@ -468,7 +471,7 @@
return;
case RFC_PORT_EVENT_CLEAR:
- LOG_WARN("%s, RFC_PORT_EVENT_CLEAR, index=%d", __func__, p_port->handle);
+ log::warn("RFC_PORT_EVENT_CLEAR, index={}", p_port->handle);
rfc_port_closed(p_port);
return;
@@ -500,7 +503,7 @@
return;
case RFC_PORT_EVENT_DM:
- LOG_WARN("%s, RFC_EVENT_DM, index=%d", __func__, p_port->handle);
+ log::warn("RFC_EVENT_DM, index={}", p_port->handle);
PORT_DlcReleaseInd(p_port->rfc.p_mcb, p_port->dlci);
rfc_port_closed(p_port);
return;
@@ -510,7 +513,7 @@
rfc_send_ua(p_port->rfc.p_mcb, p_port->dlci);
if (!fixed_queue_is_empty(p_port->rx.queue)) {
/* give a chance to upper stack to close port properly */
- LOG_VERBOSE("port queue is not empty");
+ log::verbose("port queue is not empty");
rfc_port_timer_start(p_port, RFC_DISC_TIMEOUT);
} else
PORT_DlcReleaseInd(p_port->rfc.p_mcb, p_port->dlci);
@@ -522,13 +525,13 @@
case RFC_PORT_EVENT_TIMEOUT:
PORT_TimeOutCloseMux(p_port->rfc.p_mcb);
- LOG_ERROR("Port error state %d event %d", p_port->rfc.state, event);
+ log::error("Port error state {} event {}", p_port->rfc.state, event);
return;
default:
- LOG_ERROR("Received unexpected event:%hu in state:%hhu", event,
- p_port->rfc.state);
+ log::error("Received unexpected event:{} in state:{}", event,
+ p_port->rfc.state);
}
- LOG_WARN("Port state opened Event ignored %d", event);
+ log::warn("Port state opened Event ignored {}", event);
}
/*******************************************************************************
@@ -546,11 +549,11 @@
switch (event) {
case RFC_PORT_EVENT_OPEN:
case RFC_PORT_EVENT_ESTABLISH_RSP:
- LOG_ERROR("Port error state %d event %d", p_port->rfc.state, event);
+ log::error("Port error state {} event {}", p_port->rfc.state, event);
return;
case RFC_PORT_EVENT_CLEAR:
- LOG_WARN("%s, RFC_PORT_EVENT_CLEAR, index=%d", __func__, p_port->handle);
+ log::warn("RFC_PORT_EVENT_CLEAR, index={}", p_port->handle);
rfc_port_closed(p_port);
return;
@@ -563,8 +566,8 @@
FALLTHROUGH_INTENDED; /* FALLTHROUGH */
case RFC_PORT_EVENT_DM:
- LOG_WARN("%s, RFC_EVENT_DM|RFC_EVENT_UA[%d], index=%d", __func__, event,
- p_port->handle);
+ log::warn("RFC_EVENT_DM|RFC_EVENT_UA[{}], index={}", event,
+ p_port->handle);
rfc_port_closed(p_port);
return;
@@ -582,15 +585,15 @@
return;
case RFC_PORT_EVENT_TIMEOUT:
- LOG_ERROR("%s, RFC_EVENT_TIMEOUT, index=%d", __func__, p_port->handle);
+ log::error("RFC_EVENT_TIMEOUT, index={}", p_port->handle);
rfc_port_closed(p_port);
return;
default:
- LOG_ERROR("Received unexpected event:%hu in state:%hhu", event,
- p_port->rfc.state);
+ log::error("Received unexpected event:{} in state:{}", event,
+ p_port->rfc.state);
}
- LOG_WARN("Port state disc_wait_ua Event ignored %d", event);
+ log::warn("Port state disc_wait_ua Event ignored {}", event);
}
/*******************************************************************************
@@ -613,9 +616,9 @@
*
******************************************************************************/
void rfc_process_pn(tRFC_MCB* p_mcb, bool is_command, MX_FRAME* p_frame) {
- LOG_VERBOSE("%s: is_initiator=%d, is_cmd=%d, state=%d, bd_addr=%s", __func__,
- p_mcb->is_initiator, is_command, p_mcb->state,
- ADDRESS_TO_LOGGABLE_CSTR(p_mcb->bd_addr));
+ log::verbose("is_initiator={}, is_cmd={}, state={}, bd_addr={}",
+ p_mcb->is_initiator, is_command, p_mcb->state,
+ ADDRESS_TO_LOGGABLE_CSTR(p_mcb->bd_addr));
uint8_t dlci = p_frame->dlci;
if (is_command) {
@@ -624,9 +627,8 @@
PORT_ParNegInd(p_mcb, dlci, p_frame->u.pn.mtu, p_frame->u.pn.conv_layer,
p_frame->u.pn.k);
} else {
- LOG(WARNING) << __func__
- << ": MX PN while disconnecting, bd_addr=" << p_mcb->bd_addr
- << ", p_mcb=" << p_mcb;
+ log::warn("MX PN while disconnecting, bd_addr={}, p_mcb={}",
+ ADDRESS_TO_LOGGABLE_STR(p_mcb->bd_addr), fmt::ptr(p_mcb));
rfc_send_dm(p_mcb, dlci, false);
}
@@ -635,9 +637,8 @@
/* If we are not awaiting response just ignore it */
tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
if ((p_port == nullptr) || !(p_port->rfc.expected_rsp & RFC_RSP_PN)) {
- LOG(WARNING) << ": Ignore unwanted response, p_mcb=" << p_mcb
- << ", bd_addr=" << p_mcb->bd_addr
- << ", dlci=" << std::to_string(dlci);
+ log::warn(": Ignore unwanted response, p_mcb={}, bd_addr={}, dlci={}",
+ fmt::ptr(p_mcb), ADDRESS_TO_LOGGABLE_STR(p_mcb->bd_addr), dlci);
return;
}
@@ -695,8 +696,7 @@
p_port = port_find_mcb_dlci_port(p_mcb, p_frame->dlci);
if ((p_port == nullptr) ||
!(p_port->rfc.expected_rsp & (RFC_RSP_RPN | RFC_RSP_RPN_REPLY))) {
- LOG(WARNING) << __func__ << ": ignore DLC parameter negotiation as we are"
- << " not waiting for any";
+ log::warn("ignore DLC parameter negotiation as we are not waiting for any");
return;
}
diff --git a/system/stack/rfcomm/rfc_port_if.cc b/system/stack/rfcomm/rfc_port_if.cc
index f6eb46f..ca7eb8f 100644
--- a/system/stack/rfcomm/rfc_port_if.cc
+++ b/system/stack/rfcomm/rfc_port_if.cc
@@ -25,6 +25,8 @@
#define LOG_TAG "rfcomm"
+#include <bluetooth/log.h>
+
#include <cstdint>
#include <unordered_map>
@@ -35,6 +37,8 @@
#include "stack/rfcomm/port_int.h"
#include "stack/rfcomm/rfc_int.h"
+using namespace bluetooth;
+
tRFC_CB rfc_cb;
std::unordered_map<uint16_t /* sci */, tRFC_MCB*> rfc_lcid_mcb;
@@ -85,7 +89,7 @@
tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
if (p_port == nullptr) {
- LOG_WARN("%s Unable to find DLCI port dlci:%d", __func__, dlci);
+ log::warn("Unable to find DLCI port dlci:{}", dlci);
return;
}
@@ -109,7 +113,7 @@
tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
if (p_port == nullptr) {
- LOG_WARN("%s Unable to find DLCI port dlci:%d", __func__, dlci);
+ log::warn("Unable to find DLCI port dlci:{}", dlci);
return;
}
rfc_port_sm_execute(p_port, RFC_PORT_EVENT_ESTABLISH_RSP, &result);
@@ -134,7 +138,7 @@
tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
if (p_port == nullptr) {
- LOG_WARN("%s Unable to find DLCI port dlci:%d", __func__, dlci);
+ log::warn("Unable to find DLCI port dlci:{}", dlci);
return;
}
@@ -203,7 +207,7 @@
tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
if (p_port == nullptr) {
- LOG_WARN("%s Unable to find DLCI port dlci:%d", __func__, dlci);
+ log::warn("Unable to find DLCI port dlci:{}", dlci);
return;
}
@@ -244,7 +248,7 @@
void RFCOMM_ControlReq(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_CTRL* p_pars) {
tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
if (p_port == nullptr) {
- LOG_WARN("%s Unable to find DLCI port dlci:%d", __func__, dlci);
+ log::warn("Unable to find DLCI port dlci:{}", dlci);
return;
}
@@ -272,7 +276,7 @@
void RFCOMM_FlowReq(tRFC_MCB* p_mcb, uint8_t dlci, bool enable) {
tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
if (p_port == nullptr) {
- LOG_WARN("%s Unable to find DLCI port dlci:%d", __func__, dlci);
+ log::warn("Unable to find DLCI port dlci:{}", dlci);
return;
}
@@ -299,7 +303,7 @@
void RFCOMM_LineStatusReq(tRFC_MCB* p_mcb, uint8_t dlci, uint8_t status) {
tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
if (p_port == nullptr) {
- LOG_WARN("%s Unable to find DLCI port dlci:%d", __func__, dlci);
+ log::warn("Unable to find DLCI port dlci:{}", dlci);
return;
}
diff --git a/system/stack/rfcomm/rfc_ts_frames.cc b/system/stack/rfcomm/rfc_ts_frames.cc
index 8db32d6..cf49eda 100644
--- a/system/stack/rfcomm/rfc_ts_frames.cc
+++ b/system/stack/rfcomm/rfc_ts_frames.cc
@@ -25,6 +25,7 @@
#define LOG_TAG "rfcomm"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <log/log.h>
#include <cstdint>
@@ -38,6 +39,8 @@
#include "stack/rfcomm/port_int.h"
#include "stack/rfcomm/rfc_int.h"
+using namespace bluetooth;
+
/*******************************************************************************
*
* Function rfc_send_sabme
@@ -518,13 +521,13 @@
uint16_t len;
if (p_buf->len < RFCOMM_CTRL_FRAME_LEN) {
- LOG_ERROR("Bad Length1: %d", p_buf->len);
+ log::error("Bad Length1: {}", p_buf->len);
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_CTRL_FIELD(ead, p_frame->cr, p_frame->dlci, p_data);
if (!ead) {
- LOG_ERROR("Bad Address(EA must be 1)");
+ log::error("Bad Address(EA must be 1)");
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_TYPE_FIELD(p_frame->type, p_frame->pf, p_data);
@@ -534,12 +537,12 @@
if (eal == 0 && p_buf->len > RFCOMM_CTRL_FRAME_LEN) {
len += (*(p_data)++ << RFCOMM_SHIFT_LENGTH2);
} else if (eal == 0) {
- LOG_ERROR("Bad Length when EAL = 0: %d", p_buf->len);
+ log::error("Bad Length when EAL = 0: {}", p_buf->len);
return RFC_EVENT_BAD_FRAME;
}
if (p_buf->len < (3 + !ead + !eal + 1)) {
- LOG_ERROR("Bad Length: %d", p_buf->len);
+ log::error("Bad Length: {}", p_buf->len);
return RFC_EVENT_BAD_FRAME;
}
p_buf->len -= (3 + !ead + !eal + 1); /* Additional 1 for FCS */
@@ -549,7 +552,7 @@
if ((p_mcb->flow == PORT_FC_CREDIT) && (p_frame->type == RFCOMM_UIH) &&
(p_frame->dlci != RFCOMM_MX_DLCI) && (p_frame->pf == 1)) {
if (p_buf->len < sizeof(uint8_t)) {
- LOG_ERROR("Bad Length in flow control: %d", p_buf->len);
+ log::error("Bad Length in flow control: {}", p_buf->len);
return RFC_EVENT_BAD_FRAME;
}
p_frame->credit = *p_data++;
@@ -560,7 +563,7 @@
}
if (p_buf->len != len) {
- LOG_ERROR("Bad Length2 %d %d", p_buf->len, len);
+ log::error("Bad Length2 {} {}", p_buf->len, len);
return (RFC_EVENT_BAD_FRAME);
}
@@ -575,7 +578,7 @@
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
- LOG_ERROR("Bad SABME");
+ log::error("Bad SABME");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_SABME);
@@ -584,7 +587,7 @@
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
- LOG_ERROR("Bad UA");
+ log::error("Bad UA");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_UA);
@@ -593,7 +596,7 @@
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) || len ||
!RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
- LOG_ERROR("Bad DM");
+ log::error("Bad DM");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DM);
@@ -602,21 +605,21 @@
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
- LOG_ERROR("Bad DISC");
+ log::error("Bad DISC");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DISC);
case RFCOMM_UIH:
if (!RFCOMM_VALID_DLCI(p_frame->dlci)) {
- LOG_ERROR("Bad UIH - invalid DLCI");
+ log::error("Bad UIH - invalid DLCI");
return (RFC_EVENT_BAD_FRAME);
} else if (!rfc_check_fcs(2, p_start, fcs)) {
- LOG_ERROR("Bad UIH - FCS");
+ log::error("Bad UIH - FCS");
return (RFC_EVENT_BAD_FRAME);
} else if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr)) {
/* we assume that this is ok to allow bad implementations to work */
- LOG_ERROR("Bad UIH - response");
+ log::error("Bad UIH - response");
return (RFC_EVENT_UIH);
} else {
return (RFC_EVENT_UIH);
@@ -641,8 +644,7 @@
uint8_t ea, cr, mx_len;
if (length < 2) {
- LOG_ERROR("%s: Illegal MX Frame len when reading EA, C/R. len:%d < 2",
- __func__, length);
+ log::error("Illegal MX Frame len when reading EA, C/R. len:{} < 2", length);
osi_free(p_buf);
return;
}
@@ -651,9 +653,8 @@
p_rx_frame->type = *p_data++ & ~(RFCOMM_CR_MASK | RFCOMM_EA_MASK);
if (!p_rx_frame->ea || !length) {
- LOG(ERROR) << __func__
- << ": Invalid MX frame ea=" << std::to_string(p_rx_frame->ea)
- << ", len=" << length << ", bd_addr=" << p_mcb->bd_addr;
+ log::error("Invalid MX frame ea={}, len={}, bd_addr={}", p_rx_frame->ea,
+ length, ADDRESS_TO_LOGGABLE_STR(p_mcb->bd_addr));
osi_free(p_buf);
return;
}
@@ -669,8 +670,7 @@
if (!ea) {
if (length < 1) {
- LOG_ERROR("%s: Illegal MX Frame when EA = 0. len:%d < 1", __func__,
- length);
+ log::error("Illegal MX Frame when EA = 0. len:{} < 1", length);
osi_free(p_buf);
return;
}
@@ -679,19 +679,19 @@
}
if (mx_len != length) {
- LOG(ERROR) << __func__ << ": Bad MX frame, p_mcb=" << p_mcb
- << ", bd_addr=" << p_mcb->bd_addr;
+ log::error("Bad MX frame, p_mcb={}, bd_addr={}", fmt::ptr(p_mcb),
+ ADDRESS_TO_LOGGABLE_STR(p_mcb->bd_addr));
osi_free(p_buf);
return;
}
- LOG_VERBOSE("%s: type=0x%02x, bd_addr=%s", __func__, p_rx_frame->type,
- ADDRESS_TO_LOGGABLE_CSTR(p_mcb->bd_addr));
+ log::verbose("type=0x{:02x}, bd_addr={}", p_rx_frame->type,
+ ADDRESS_TO_LOGGABLE_CSTR(p_mcb->bd_addr));
switch (p_rx_frame->type) {
case RFCOMM_MX_PN:
if (length != RFCOMM_MX_PN_LEN) {
- LOG(ERROR) << __func__ << ": Invalid PN length, p_mcb=" << p_mcb
- << ", bd_addr=" << p_mcb->bd_addr;
+ log::error("Invalid PN length, p_mcb={}, bd_addr={}", fmt::ptr(p_mcb),
+ ADDRESS_TO_LOGGABLE_STR(p_mcb->bd_addr));
break;
}
@@ -708,8 +708,8 @@
if (!p_rx_frame->dlci || !RFCOMM_VALID_DLCI(p_rx_frame->dlci) ||
(p_rx_frame->u.pn.mtu < RFCOMM_MIN_MTU) ||
(p_rx_frame->u.pn.mtu > RFCOMM_MAX_MTU)) {
- LOG(ERROR) << __func__ << ": Bad PN frame, p_mcb=" << p_mcb
- << ", bd_addr=" << p_mcb->bd_addr;
+ log::error("Bad PN frame, p_mcb={}, bd_addr={}", fmt::ptr(p_mcb),
+ ADDRESS_TO_LOGGABLE_STR(p_mcb->bd_addr));
break;
}
@@ -752,7 +752,7 @@
case RFCOMM_MX_MSC:
if (length != RFCOMM_MX_MSC_LEN_WITH_BREAK &&
length != RFCOMM_MX_MSC_LEN_NO_BREAK) {
- LOG_ERROR("%s: Illegal MX MSC Frame len:%d", __func__, length);
+ log::error("Illegal MX MSC Frame len:{}", length);
osi_free(p_buf);
return;
}
@@ -762,7 +762,7 @@
if (!ea || !cr || !p_rx_frame->dlci ||
!RFCOMM_VALID_DLCI(p_rx_frame->dlci)) {
- LOG_ERROR("Bad MSC frame");
+ log::error("Bad MSC frame");
break;
}
@@ -804,7 +804,7 @@
if (!ea || !cr || !p_rx_frame->dlci ||
!RFCOMM_VALID_DLCI(p_rx_frame->dlci)) {
- LOG_ERROR("Bad RPN frame");
+ log::error("Bad RPN frame");
break;
}
@@ -845,7 +845,7 @@
if (!ea || !cr || !p_rx_frame->dlci ||
!RFCOMM_VALID_DLCI(p_rx_frame->dlci)) {
- LOG_ERROR("Bad RPN frame");
+ log::error("Bad RPN frame");
break;
}
diff --git a/system/stack/rfcomm/rfc_utils.cc b/system/stack/rfcomm/rfc_utils.cc
index 16439f1..91651ba 100644
--- a/system/stack/rfcomm/rfc_utils.cc
+++ b/system/stack/rfcomm/rfc_utils.cc
@@ -25,6 +25,7 @@
#define LOG_TAG "rfcomm"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <cstdint>
@@ -38,6 +39,8 @@
#include "stack/rfcomm/rfc_int.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
/*******************************************************************************
*
* Function rfc_calc_fcs
@@ -134,13 +137,13 @@
bool is_initiator) {
int i, j;
tRFC_MCB* p_mcb = NULL;
- LOG_VERBOSE("bd_addr:%s, is_initiator:%d", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
- is_initiator);
+ log::verbose("bd_addr:{}, is_initiator:{}", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
+ is_initiator);
for (i = 0; i < MAX_BD_CONNECTIONS; i++) {
- LOG_VERBOSE("rfc_cb.port.rfc_mcb[%d] - state:%d, bd_addr:%s", i,
- rfc_cb.port.rfc_mcb[i].state,
- ADDRESS_TO_LOGGABLE_CSTR(rfc_cb.port.rfc_mcb[i].bd_addr));
+ log::verbose("rfc_cb.port.rfc_mcb[{}] - state:{}, bd_addr:{}", i,
+ rfc_cb.port.rfc_mcb[i].state,
+ ADDRESS_TO_LOGGABLE_CSTR(rfc_cb.port.rfc_mcb[i].bd_addr));
if ((rfc_cb.port.rfc_mcb[i].state != RFC_MX_STATE_IDLE) &&
rfc_cb.port.rfc_mcb[i].bd_addr == bd_addr) {
@@ -148,10 +151,11 @@
/* If there was an inactivity timer running stop it now */
if (rfc_cb.port.rfc_mcb[i].state == RFC_MX_STATE_CONNECTED)
rfc_timer_stop(&rfc_cb.port.rfc_mcb[i]);
- LOG_VERBOSE(
- "rfc_alloc_multiplexer_channel:is_initiator:%d, found, state:%d, "
- "p_mcb:%p",
- is_initiator, rfc_cb.port.rfc_mcb[i].state, &rfc_cb.port.rfc_mcb[i]);
+ log::verbose(
+ "rfc_alloc_multiplexer_channel:is_initiator:{}, found, state:{}, "
+ "p_mcb:{}",
+ is_initiator, rfc_cb.port.rfc_mcb[i].state,
+ fmt::ptr(&rfc_cb.port.rfc_mcb[i]));
return (&rfc_cb.port.rfc_mcb[i]);
}
}
@@ -167,10 +171,10 @@
fixed_queue_free(p_mcb->cmd_q, NULL);
memset(p_mcb, 0, sizeof(tRFC_MCB));
p_mcb->bd_addr = bd_addr;
- LOG_VERBOSE(
- "rfc_alloc_multiplexer_channel:is_initiator:%d, create new p_mcb:%p, "
- "index:%d",
- is_initiator, &rfc_cb.port.rfc_mcb[j], j);
+ log::verbose(
+ "rfc_alloc_multiplexer_channel:is_initiator:{}, create new p_mcb:{}, "
+ "index:{}",
+ is_initiator, fmt::ptr(&rfc_cb.port.rfc_mcb[j]), j);
p_mcb->mcb_timer = alarm_new("rfcomm_mcb.mcb_timer");
p_mcb->cmd_q = fixed_queue_new(SIZE_MAX);
@@ -220,7 +224,7 @@
*
******************************************************************************/
void rfc_timer_start(tRFC_MCB* p_mcb, uint16_t timeout) {
- LOG_VERBOSE("%s - timeout:%d seconds", __func__, timeout);
+ log::verbose("- timeout:{} seconds", timeout);
uint64_t interval_ms = timeout * 1000;
alarm_set_on_mloop(p_mcb->mcb_timer, interval_ms, rfcomm_mcb_timer_timeout,
@@ -235,7 +239,7 @@
*
******************************************************************************/
void rfc_timer_stop(tRFC_MCB* p_mcb) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
alarm_cancel(p_mcb->mcb_timer);
}
@@ -248,7 +252,7 @@
*
******************************************************************************/
void rfc_port_timer_start(tPORT* p_port, uint16_t timeout) {
- LOG_VERBOSE("%s - timeout:%d seconds", __func__, timeout);
+ log::verbose("- timeout:{} seconds", timeout);
uint64_t interval_ms = timeout * 1000;
alarm_set_on_mloop(p_port->rfc.port_timer, interval_ms,
@@ -263,7 +267,7 @@
*
******************************************************************************/
void rfc_port_timer_stop(tPORT* p_port) {
- LOG_VERBOSE("%s", __func__);
+ log::verbose("");
alarm_cancel(p_port->rfc.port_timer);
}
@@ -376,7 +380,7 @@
if (p_port->rfc.p_mcb->flow == PORT_FC_CREDIT) {
p_port->credit_tx += credit;
- LOG_VERBOSE("rfc_inc_credit:%d", p_port->credit_tx);
+ log::verbose("rfc_inc_credit:{}", p_port->credit_tx);
if (p_port->tx.peer_fc) PORT_FlowInd(p_port->rfc.p_mcb, p_port->dlci, true);
}
@@ -415,9 +419,9 @@
/* if passed a buffer queue it */
if (p_buf != NULL) {
if (p_mcb->cmd_q == NULL) {
- LOG_ERROR(
- "%s: empty queue: p_mcb = %p p_mcb->lcid = %u cached p_mcb = %p",
- __func__, p_mcb, p_mcb->lcid, rfc_find_lcid_mcb(p_mcb->lcid));
+ log::error("empty queue: p_mcb = {} p_mcb->lcid = {} cached p_mcb = {}",
+ fmt::ptr(p_mcb), p_mcb->lcid,
+ fmt::ptr(rfc_find_lcid_mcb(p_mcb->lcid)));
}
fixed_queue_enqueue(p_mcb->cmd_q, p_buf);
}
diff --git a/system/stack/sdp/sdp_api.cc b/system/stack/sdp/sdp_api.cc
index a3c2808..aad95ad 100644
--- a/system/stack/sdp/sdp_api.cc
+++ b/system/stack/sdp/sdp_api.cc
@@ -26,13 +26,13 @@
#include "stack/include/sdp_api.h"
+#include <bluetooth/log.h>
#include <string.h>
#include <cstdint>
#include "internal_include/bt_target.h"
#include "os/log.h"
-#include "osi/include/osi.h" // PTR_TO_UINT
#include "stack/include/bt_types.h"
#include "stack/include/bt_uuid16.h"
#include "stack/include/sdp_api.h"
@@ -43,6 +43,7 @@
#include "types/raw_address.h"
using bluetooth::Uuid;
+using namespace bluetooth;
/**********************************************************************
* C L I E N T F U N C T I O N P R O T O T Y P E S *
@@ -78,10 +79,10 @@
/* verify the parameters */
if (p_db == NULL || (sizeof(tSDP_DISCOVERY_DB) > len) ||
num_attr > SDP_MAX_ATTR_FILTERS || num_uuid > SDP_MAX_UUID_FILTERS) {
- LOG_ERROR(
- "SDP_InitDiscoveryDb Illegal param: p_db 0x%x, len %d, num_uuid %d, "
- "num_attr %d",
- PTR_TO_UINT(p_db), len, num_uuid, num_attr);
+ log::error(
+ "SDP_InitDiscoveryDb Illegal param: p_db {}, len {}, num_uuid {}, "
+ "num_attr {}",
+ fmt::ptr(p_db), len, num_uuid, num_attr);
return (false);
}
@@ -396,13 +397,14 @@
p_sattr = p_sattr->p_next_attr) {
if ((SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) == UUID_DESC_TYPE) &&
(SDP_DISC_ATTR_LEN(p_sattr->attr_len_type) == 2)) {
- LOG_VERBOSE(
- "SDP_FindServiceInDb - p_sattr value = 0x%x serviceuuid = 0x%x",
+ log::verbose(
+ "SDP_FindServiceInDb - p_sattr value = 0x{:x} serviceuuid = "
+ "0x{:x}",
p_sattr->attr_value.v.u16, service_uuid);
if (service_uuid == UUID_SERVCLASS_HDP_PROFILE) {
if ((p_sattr->attr_value.v.u16 == UUID_SERVCLASS_HDP_SOURCE) ||
(p_sattr->attr_value.v.u16 == UUID_SERVCLASS_HDP_SINK)) {
- LOG_VERBOSE("SDP_FindServiceInDb found HDP source or sink\n");
+ log::verbose("SDP_FindServiceInDb found HDP source or sink\n");
return (p_rec);
}
}
@@ -807,11 +809,10 @@
memcpy(dst, (const void*)p_attr->attr_value.v.array, len);
dst[len] = '\0';
} else {
- LOG_ERROR("unexpected attr type=%d, expected=%d",
- type, expected_type);
+ log::error("unexpected attr type={}, expected={}", type, expected_type);
}
} else {
- LOG_ERROR("p_attr is NULL");
+ log::error("p_attr is NULL");
}
}
diff --git a/system/stack/sdp/sdp_db.cc b/system/stack/sdp/sdp_db.cc
index fab13b9..7ec98fb 100644
--- a/system/stack/sdp/sdp_db.cc
+++ b/system/stack/sdp/sdp_db.cc
@@ -25,6 +25,7 @@
#define LOG_TAG "sdp"
+#include <bluetooth/log.h>
#include <string.h>
#include <cstdint>
@@ -38,6 +39,8 @@
#include "stack/sdp/sdp_discovery_db.h"
#include "stack/sdp/sdpint.h"
+using namespace bluetooth;
+
/******************************************************************************/
/* L O C A L F U N C T I O N P R O T O T Y P E S */
/******************************************************************************/
@@ -125,7 +128,7 @@
type = *p++;
p = sdpu_get_len_from_type(p, p_end, type, &len);
if (p == NULL || (p + len) > p_end) {
- LOG_WARN("%s: bad length", __func__);
+ log::warn("bad length");
break;
}
type = type >> 3;
@@ -275,7 +278,7 @@
p_db->record[p_db->num_records].record_handle = handle;
p_db->num_records++;
- LOG_VERBOSE("SDP_CreateRecord ok, num_records:%d", 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,
@@ -283,8 +286,8 @@
return (p_db->record[p_db->num_records - 1].record_handle);
} else
- LOG_ERROR("SDP_CreateRecord fail, exceed maximum records:%d",
- SDP_MAX_RECORDS);
+ log::error("SDP_CreateRecord fail, exceed maximum records:{}",
+ SDP_MAX_RECORDS);
return (0);
}
@@ -328,8 +331,8 @@
sdp_cb.server_db.num_records--;
- LOG_VERBOSE("SDP_DeleteRecord ok, num_records:%d",
- 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) {
@@ -363,7 +366,7 @@
tSDP_RECORD* p_rec = &sdp_cb.server_db.record[0];
if (p_val == nullptr) {
- LOG_WARN("Trying to add attribute with p_val == nullptr, skipped");
+ log::warn("Trying to add attribute with p_val == nullptr, skipped");
return (false);
}
@@ -378,39 +381,41 @@
#define MAX_ARR_LEN 200
// one extra byte for storing terminating zero byte
- uint8_t num_array[2 * MAX_ARR_LEN + 1] = {0};
+ char num_array[2 * MAX_ARR_LEN + 1] = {0};
uint32_t len = (attr_len > MAX_ARR_LEN) ? MAX_ARR_LEN : attr_len;
#undef MAX_ARR_LEN
for (uint32_t i = 0; i < len; i++) {
- snprintf((char*)&num_array[i * 2], sizeof(num_array) - i * 2, "%02X",
+ snprintf(&num_array[i * 2], sizeof(num_array) - i * 2, "%02X",
(uint8_t)(p_val[i]));
}
- LOG_VERBOSE(
- "SDP_AddAttribute: handle:%X, id:%04X, type:%d, len:%d, p_val:%p, "
- "*p_val:%s",
- handle, attr_id, attr_type, attr_len, p_val, num_array);
+ log::verbose(
+ "SDP_AddAttribute: handle:{:X}, id:{:04X}, type:{}, len:{}, "
+ "p_val:{}, *p_val:{}",
+ handle, attr_id, attr_type, attr_len, fmt::ptr(p_val), num_array);
} else if (attr_type == BOOLEAN_DESC_TYPE) {
- LOG_VERBOSE(
- "SDP_AddAttribute: handle:%X, id:%04X, type:%d, len:%d, p_val:%p, "
- "*p_val:%d",
- handle, attr_id, attr_type, attr_len, p_val, *p_val);
+ log::verbose(
+ "SDP_AddAttribute: handle:{:X}, id:{:04X}, type:{}, len:{}, "
+ "p_val:{}, *p_val:{}",
+ handle, attr_id, attr_type, attr_len, fmt::ptr(p_val), *p_val);
} else if ((attr_type == TEXT_STR_DESC_TYPE) ||
(attr_type == URL_DESC_TYPE)) {
if (p_val[attr_len - 1] == '\0') {
- LOG_VERBOSE(
- "SDP_AddAttribute: handle:%X, id:%04X, type:%d, len:%d, p_val:%p, "
- "*p_val:%s",
- handle, attr_id, attr_type, attr_len, p_val, (char*)p_val);
+ log::verbose(
+ "SDP_AddAttribute: handle:{:X}, id:{:04X}, type:{}, len:{}, "
+ "p_val:{}, *p_val:{}",
+ handle, attr_id, attr_type, attr_len, fmt::ptr(p_val),
+ (char*)p_val);
} else {
- LOG_VERBOSE(
- "SDP_AddAttribute: handle:%X, id:%04X, type:%d, len:%d, p_val:%p",
- handle, attr_id, attr_type, attr_len, p_val);
+ log::verbose(
+ "SDP_AddAttribute: handle:{:X}, id:{:04X}, type:{}, len:{}, "
+ "p_val:{}",
+ handle, attr_id, attr_type, attr_len, fmt::ptr(p_val));
}
} else {
- LOG_VERBOSE(
- "SDP_AddAttribute: handle:%X, id:%04X, type:%d, len:%d, p_val:%p",
- handle, attr_id, attr_type, attr_len, p_val);
+ log::verbose(
+ "SDP_AddAttribute: handle:{:X}, id:{:04X}, type:{}, len:{}, p_val:{}",
+ handle, attr_id, attr_type, attr_len, fmt::ptr(p_val));
}
}
@@ -420,9 +425,9 @@
// error out early, no need to look up
if (p_rec->free_pad_ptr >= SDP_MAX_PAD_LEN) {
- LOG_ERROR(
- "the free pad for SDP record with handle %d is "
- "full, skip adding the attribute",
+ log::error(
+ "the free pad for SDP record with handle {} is full, skip adding "
+ "the attribute",
handle);
return (false);
}
@@ -481,17 +486,17 @@
if (p_rec->free_pad_ptr + attr_len >= SDP_MAX_PAD_LEN) {
if (p_rec->free_pad_ptr >= SDP_MAX_PAD_LEN) {
- LOG_ERROR(
- "SDP_AddAttributeToRecord failed: free pad %d equals or exceeds max "
- "padding length %d",
+ log::error(
+ "SDP_AddAttributeToRecord failed: free pad {} equals or exceeds max "
+ "padding length {}",
p_rec->free_pad_ptr, SDP_MAX_PAD_LEN);
return (false);
}
/* do truncate only for text string type descriptor */
if (attr_type == TEXT_STR_DESC_TYPE) {
- LOG_WARN(
- "SDP_AddAttributeToRecord: attr_len:%d too long. truncate to (%d)",
+ log::warn(
+ "SDP_AddAttributeToRecord: attr_len:{} too long. truncate to ({})",
attr_len, SDP_MAX_PAD_LEN - p_rec->free_pad_ptr);
attr_len = SDP_MAX_PAD_LEN - p_rec->free_pad_ptr;
@@ -507,9 +512,9 @@
p_rec->free_pad_ptr += attr_len;
} else if (attr_len == 0 && p_attr->len != 0) {
/* if truncate to 0 length, simply don't add */
- LOG_ERROR(
- "SDP_AddAttributeToRecord fail, length exceed maximum: ID %d: "
- "attr_len:%d ",
+ log::error(
+ "SDP_AddAttributeToRecord fail, length exceed maximum: ID {}: "
+ "attr_len:{}",
attr_id, attr_len);
p_attr->id = p_attr->type = p_attr->len = 0;
return (false);
@@ -575,12 +580,12 @@
p = p_head;
if (p_head == p_buff) {
/* the first element exceed the max length */
- LOG_ERROR("SDP_AddSequence - too long(attribute is not added)!!");
+ log::error("SDP_AddSequence - too long(attribute is not added)!!");
osi_free(p_buff);
return false;
} else
- LOG_ERROR("SDP_AddSequence - too long, add %d elements of %d", xx,
- num_elem);
+ log::error("SDP_AddSequence - too long, add {} elements of {}", xx,
+ num_elem);
break;
}
}
@@ -619,8 +624,8 @@
UINT16_TO_BE_STREAM(p, *p_uuids);
if ((p - p_buff) > max_len) {
- LOG_WARN("SDP_AddUuidSequence - too long, add %d uuids of %d", xx,
- num_uuids);
+ log::warn("SDP_AddUuidSequence - too long, add {} uuids of {}", xx,
+ num_uuids);
break;
}
}
diff --git a/system/stack/sdp/sdp_discovery.cc b/system/stack/sdp/sdp_discovery.cc
index c447292..a007c1e 100644
--- a/system/stack/sdp/sdp_discovery.cc
+++ b/system/stack/sdp/sdp_discovery.cc
@@ -24,6 +24,8 @@
#define LOG_TAG "sdp_discovery"
+#include <bluetooth/log.h>
+
#include <cstdint>
#include "internal_include/bt_target.h"
@@ -38,6 +40,7 @@
#include "types/raw_address.h"
using bluetooth::Uuid;
+using namespace bluetooth;
/******************************************************************************/
/* L O C A L F U N C T I O N P R O T O T Y P E S */
@@ -277,7 +280,7 @@
}
if (invalid_pdu) {
- LOG_WARN("SDP - Unexp. PDU: %d in state: %d", rsp_pdu, p_ccb->disc_state);
+ log::warn("SDP - Unexp. PDU: {} in state: {}", rsp_pdu, p_ccb->disc_state);
sdp_disconnect(p_ccb, SDP_GENERIC_ERROR);
}
}
@@ -310,7 +313,7 @@
orig = p_ccb->num_handles;
p_ccb->num_handles += cur_handles;
if (p_ccb->num_handles == 0 || p_ccb->num_handles < orig) {
- LOG_WARN("SDP - Rcvd ServiceSearchRsp, no matches");
+ log::warn("SDP - Rcvd ServiceSearchRsp, no matches");
sdp_disconnect(p_ccb, SDP_NO_RECS_MATCH);
return;
}
@@ -380,11 +383,11 @@
uint8_t* old_p = p;
p = sdpu_get_len_from_type(p, p_end, type, &list_len);
if (p == NULL || (p + list_len) > p_end) {
- LOG_WARN("%s: bad length", __func__);
+ log::warn("bad length");
return false;
}
if ((int)cpy_len < (p - old_p)) {
- LOG_WARN("%s: no bytes left for data", __func__);
+ log::warn("no bytes left for data");
return false;
}
cpy_len -= (p - old_p);
@@ -394,7 +397,7 @@
}
rem_len = SDP_MAX_LIST_BYTE_COUNT - (unsigned int)(p - &p_ccb->rsp_list[0]);
if (cpy_len > rem_len) {
- LOG_WARN("rem_len :%d less than cpy_len:%d", rem_len, cpy_len);
+ log::warn("rem_len :{} less than cpy_len:{}", rem_len, cpy_len);
cpy_len = rem_len;
}
memcpy(&p_ccb->p_db->raw_data[p_ccb->p_db->raw_used], p, cpy_len);
@@ -456,9 +459,9 @@
}
cont_request_needed = true;
} else {
- LOG_WARN("process_service_attr_rsp");
+ log::warn("process_service_attr_rsp");
if (!sdp_copy_raw_data(p_ccb, false)) {
- LOG_ERROR("sdp_copy_raw_data failed");
+ log::error("sdp_copy_raw_data failed");
sdp_disconnect(p_ccb, SDP_ILLEGAL_PARAMETER);
return;
}
@@ -666,7 +669,7 @@
/*******************************************************************/
if (!sdp_copy_raw_data(p_ccb, true)) {
- LOG_ERROR("sdp_copy_raw_data failed");
+ log::error("sdp_copy_raw_data failed");
sdp_disconnect(p_ccb, SDP_ILLEGAL_PARAMETER);
return;
}
@@ -677,13 +680,13 @@
type = *p++;
if ((type >> 3) != DATA_ELE_SEQ_DESC_TYPE) {
- LOG_WARN("Wrong element in attr_rsp type:0x%02x", type);
+ log::warn("Wrong element in attr_rsp type:0x{:02x}", type);
sdp_disconnect(p_ccb, SDP_ILLEGAL_PARAMETER);
return;
}
p = sdpu_get_len_from_type(p, p + p_ccb->list_len, type, &seq_len);
if (p == NULL || (p + seq_len) > (p + p_ccb->list_len)) {
- LOG_WARN("Illegal search attribute length");
+ log::warn("Illegal search attribute length");
sdp_disconnect(p_ccb, SDP_ILLEGAL_PARAMETER);
return;
}
@@ -726,19 +729,19 @@
type = *p++;
if ((type >> 3) != DATA_ELE_SEQ_DESC_TYPE) {
- LOG_WARN("SDP - Wrong type: 0x%02x in attr_rsp", type);
+ log::warn("SDP - Wrong type: 0x{:02x} in attr_rsp", type);
return (NULL);
}
p = sdpu_get_len_from_type(p, p_msg_end, type, &seq_len);
if (p == NULL || (p + seq_len) > p_msg_end) {
- LOG_WARN("SDP - Bad len in attr_rsp %d", seq_len);
+ log::warn("SDP - Bad len in attr_rsp {}", seq_len);
return (NULL);
}
/* Create a record */
p_rec = add_record(p_ccb->p_db, p_ccb->device_address);
if (!p_rec) {
- LOG_WARN("SDP - DB full add_record");
+ log::warn("SDP - DB full add_record");
return (NULL);
}
@@ -749,11 +752,12 @@
type = *p++;
p = sdpu_get_len_from_type(p, p_msg_end, type, &attr_len);
if (p == NULL || (p + attr_len) > p_seq_end) {
- LOG_WARN("%s: Bad len in attr_rsp %d", __func__, attr_len);
+ log::warn("Bad len in attr_rsp {}", attr_len);
return (NULL);
}
if (((type >> 3) != UINT_DESC_TYPE) || (attr_len != 2)) {
- LOG_WARN("SDP - Bad type: 0x%02x or len: %d in attr_rsp", type, attr_len);
+ log::warn("SDP - Bad type: 0x{:02x} or len: {} in attr_rsp", type,
+ attr_len);
return (NULL);
}
BE_STREAM_TO_UINT16(attr_id, p);
@@ -762,7 +766,7 @@
p = add_attr(p, p_seq_end, p_ccb->p_db, p_rec, attr_id, NULL, 0);
if (!p) {
- LOG_WARN("SDP - DB full add_attr");
+ log::warn("SDP - DB full add_attr");
return (NULL);
}
}
@@ -836,7 +840,7 @@
type = *p++;
p = sdpu_get_len_from_type(p, p_end, type, &attr_len);
if (p == NULL || (p + attr_len) > p_end) {
- LOG_WARN("%s: bad length in attr_rsp", __func__);
+ log::warn("bad length in attr_rsp");
return NULL;
}
attr_len &= SDP_DISC_ATTR_LEN_MASK;
@@ -850,7 +854,7 @@
p_attr_end = p + attr_len;
if (p_attr_end > p_end) {
- LOG_WARN("%s: SDP - Attribute length beyond p_end", __func__);
+ log::warn("SDP - Attribute length beyond p_end");
return NULL;
}
@@ -881,7 +885,7 @@
/* LOG_VERBOSE ("SDP - attr nest level:%d(list)", nest_level); */
if (nest_level >= MAX_NEST_LEVELS) {
- LOG_ERROR("SDP - attr nesting too deep");
+ log::error("SDP - attr nesting too deep");
return p_attr_end;
}
@@ -945,7 +949,7 @@
}
break;
default:
- LOG_WARN("SDP - bad len in UUID attr: %d", attr_len);
+ log::warn("SDP - bad len in UUID attr: {}", attr_len);
return p_attr_end;
}
break;
@@ -960,7 +964,7 @@
/* LOG_VERBOSE ("SDP - attr nest level:%d", nest_level); */
if (nest_level >= MAX_NEST_LEVELS) {
- LOG_ERROR("SDP - attr nesting too deep");
+ log::error("SDP - attr nesting too deep");
return p_attr_end;
}
if (is_additional_list != 0 ||
@@ -988,7 +992,7 @@
p_attr->attr_value.v.u8 = *p++;
break;
default:
- LOG_WARN("SDP - bad len in boolean attr: %d", attr_len);
+ log::warn("SDP - bad len in boolean attr: {}", attr_len);
return p_attr_end;
}
break;
diff --git a/system/stack/sdp/sdp_main.cc b/system/stack/sdp/sdp_main.cc
index 485bb44..8070636 100644
--- a/system/stack/sdp/sdp_main.cc
+++ b/system/stack/sdp/sdp_main.cc
@@ -25,6 +25,7 @@
#define LOG_TAG "sdp"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <string.h> // memset
#include "common/init_flags.h"
@@ -39,6 +40,8 @@
#include "stack/sdp/sdpint.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
/******************************************************************************/
/* G L O B A L S D P D A T A */
/******************************************************************************/
@@ -95,7 +98,7 @@
/* Now, register with L2CAP */
if (!L2CA_Register2(BT_PSM_SDP, sdp_cb.reg_info, true /* enable_snoop */,
nullptr, SDP_MTU_SIZE, 0, BTM_SEC_NONE)) {
- LOG_ERROR("SDP Registration failed");
+ log::error("SDP Registration failed");
}
}
@@ -153,7 +156,7 @@
/* Find CCB based on CID */
p_ccb = sdpu_find_ccb_by_cid(l2cap_cid);
if (p_ccb == NULL) {
- LOG_WARN("SDP - Rcvd conn cnf for unknown CID 0x%x", l2cap_cid);
+ log::warn("SDP - Rcvd conn cnf for unknown CID 0x{:x}", l2cap_cid);
return;
}
@@ -162,7 +165,7 @@
if ((result == L2CAP_CONN_OK) && (p_ccb->con_state == SDP_STATE_CONN_SETUP)) {
p_ccb->con_state = SDP_STATE_CFG_SETUP;
} else {
- LOG(ERROR) << __func__ << ": invoked with non OK status";
+ log::error("invoked with non OK status");
}
}
@@ -182,7 +185,7 @@
/* Find CCB based on CID */
p_ccb = sdpu_find_ccb_by_cid(l2cap_cid);
if (p_ccb == NULL) {
- LOG_WARN("SDP - Rcvd L2CAP cfg ind, unknown CID: 0x%x", l2cap_cid);
+ log::warn("SDP - Rcvd L2CAP cfg ind, unknown CID: 0x{:x}", l2cap_cid);
return;
}
@@ -198,7 +201,7 @@
p_ccb->rem_mtu_size = p_cfg->mtu;
}
- LOG_VERBOSE("SDP - Rcvd cfg ind, sent cfg cfm, CID: 0x%x", l2cap_cid);
+ log::verbose("SDP - Rcvd cfg ind, sent cfg cfm, CID: 0x{:x}", l2cap_cid);
}
/*******************************************************************************
@@ -217,12 +220,12 @@
tCONN_CB* p_ccb;
- LOG_VERBOSE("SDP - Rcvd cfg cfm, CID: 0x%x", l2cap_cid);
+ log::verbose("SDP - Rcvd cfg cfm, CID: 0x{:x}", l2cap_cid);
/* Find CCB based on CID */
p_ccb = sdpu_find_ccb_by_cid(l2cap_cid);
if (p_ccb == NULL) {
- LOG_WARN("SDP - Rcvd L2CAP cfg ind, unknown CID: 0x%x", l2cap_cid);
+ log::warn("SDP - Rcvd L2CAP cfg ind, unknown CID: 0x{:x}", l2cap_cid);
return;
}
@@ -254,7 +257,7 @@
/* Find CCB based on CID */
p_ccb = sdpu_find_ccb_by_cid(l2cap_cid);
if (p_ccb == NULL) {
- LOG_WARN("SDP - Rcvd L2CAP disc, unknown CID: 0x%x", l2cap_cid);
+ log::warn("SDP - Rcvd L2CAP disc, unknown CID: 0x{:x}", l2cap_cid);
return;
}
tCONN_CB& ccb = *p_ccb;
@@ -264,10 +267,10 @@
sdpu_callback(ccb, reason);
if (ack_needed) {
- LOG_WARN("SDP - Rcvd L2CAP disc, process pend sdp ccb: 0x%x", l2cap_cid);
+ log::warn("SDP - Rcvd L2CAP disc, process pend sdp ccb: 0x{:x}", l2cap_cid);
sdpu_process_pend_ccb_new_cid(ccb);
} else {
- LOG_WARN("SDP - Rcvd L2CAP disc, clear pend sdp ccb: 0x%x", l2cap_cid);
+ log::warn("SDP - Rcvd L2CAP disc, clear pend sdp ccb: 0x{:x}", l2cap_cid);
sdpu_clear_pend_ccb(ccb);
}
@@ -301,11 +304,11 @@
else
sdp_server_handle_client_req(p_ccb, p_msg);
} else {
- LOG_WARN("SDP - Ignored L2CAP data while in state: %d, CID: 0x%x",
- p_ccb->con_state, l2cap_cid);
+ log::warn("SDP - Ignored L2CAP data while in state: {}, CID: 0x{:x}",
+ p_ccb->con_state, l2cap_cid);
}
} else {
- LOG_WARN("SDP - Rcvd L2CAP data, unknown CID: 0x%x", l2cap_cid);
+ log::warn("SDP - Rcvd L2CAP data, unknown CID: 0x{:x}", l2cap_cid);
}
osi_free(p_msg);
@@ -328,13 +331,12 @@
/* Allocate a new CCB. Return if none available. */
p_ccb = sdpu_allocate_ccb();
if (p_ccb == NULL) {
- LOG_WARN("%s: no spare CCB for peer %s", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(p_bd_addr));
+ log::warn("no spare CCB for peer {}", ADDRESS_TO_LOGGABLE_CSTR(p_bd_addr));
return (NULL);
}
- LOG_VERBOSE("%s: SDP - Originate started for peer %s", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(p_bd_addr));
+ log::verbose("SDP - Originate started for peer {}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_bd_addr));
/* Look for any active sdp connection on the remote device */
cid = sdpu_get_active_ccb_cid(p_bd_addr);
@@ -352,14 +354,14 @@
cid = L2CA_ConnectReq2(BT_PSM_SDP, p_bd_addr, BTM_SEC_NONE);
} else {
p_ccb->con_state = SDP_STATE_CONN_PEND;
- LOG_WARN("SDP already active for peer %s. cid=%#0x",
- ADDRESS_TO_LOGGABLE_CSTR(p_bd_addr), cid);
+ log::warn("SDP already active for peer {}. cid={:#0x}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_bd_addr), cid);
}
/* Check if L2CAP started the connection process */
if (cid == 0) {
- LOG_WARN("%s: SDP - Originate failed for peer %s", __func__,
- ADDRESS_TO_LOGGABLE_CSTR(p_bd_addr));
+ log::warn("SDP - Originate failed for peer {}",
+ ADDRESS_TO_LOGGABLE_CSTR(p_bd_addr));
sdpu_release_ccb(*p_ccb);
return (NULL);
}
@@ -378,7 +380,7 @@
******************************************************************************/
void sdp_disconnect(tCONN_CB* p_ccb, tSDP_REASON reason) {
tCONN_CB& ccb = *p_ccb;
- LOG_VERBOSE("SDP - disconnect CID: 0x%x", ccb.connection_id);
+ log::verbose("SDP - disconnect CID: 0x{:x}", ccb.connection_id);
/* Check if we have a connection ID */
if (ccb.connection_id != 0) {
@@ -417,12 +419,12 @@
/* Find CCB based on CID */
p_ccb = sdpu_find_ccb_by_cid(l2cap_cid);
if (p_ccb == NULL) {
- LOG_WARN("SDP - Rcvd L2CAP disc cfm, unknown CID: 0x%x", l2cap_cid);
+ log::warn("SDP - Rcvd L2CAP disc cfm, unknown CID: 0x{:x}", l2cap_cid);
return;
}
tCONN_CB& ccb = *p_ccb;
- LOG_VERBOSE("SDP - Rcvd L2CAP disc cfm, CID: 0x%x", l2cap_cid);
+ log::verbose("SDP - Rcvd L2CAP disc cfm, CID: 0x{:x}", l2cap_cid);
sdpu_callback(ccb, static_cast<tSDP_STATUS>(ccb.disconnect_reason));
sdpu_process_pend_ccb_new_cid(ccb);
@@ -442,8 +444,8 @@
void sdp_conn_timer_timeout(void* data) {
tCONN_CB& ccb = *(tCONN_CB*)data;
- LOG_VERBOSE("SDP - CCB timeout in state: %d CID: 0x%x", ccb.con_state,
- ccb.connection_id);
+ log::verbose("SDP - CCB timeout in state: {} CID: 0x{:x}", ccb.con_state,
+ ccb.connection_id);
L2CA_DisconnectReq(ccb.connection_id);
diff --git a/system/stack/sdp/sdp_server.cc b/system/stack/sdp/sdp_server.cc
index 021f1dd..20dbb38 100644
--- a/system/stack/sdp/sdp_server.cc
+++ b/system/stack/sdp/sdp_server.cc
@@ -25,6 +25,7 @@
#define LOG_TAG "sdp_server"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <string.h> // memcpy
#include <cstdint>
@@ -66,6 +67,8 @@
#define PBAP_1_2 0x0102
#define PBAP_1_2_BL_LEN 14
+using namespace bluetooth;
+
/* Used to set PBAP local SDP device record for PBAP 1.2 upgrade */
typedef struct {
int32_t rfcomm_channel_number;
@@ -180,9 +183,9 @@
} else {
p_attr->value_ptr[PROFILE_VERSION_POSITION] = HFP_PROFILE_MINOR_VERSION_7;
}
- LOG_VERBOSE("%s SDP Change HFP Version = %d for %s", __func__,
- p_attr->value_ptr[PROFILE_VERSION_POSITION],
- ADDRESS_TO_LOGGABLE_CSTR(remote_address));
+ log::verbose("SDP Change HFP Version = {} for {}",
+ p_attr->value_ptr[PROFILE_VERSION_POSITION],
+ ADDRESS_TO_LOGGABLE_CSTR(remote_address));
return true;
}
/******************************************************************************
@@ -197,7 +200,7 @@
void hfp_fallback(bool& is_hfp_fallback, const tSDP_ATTRIBUTE* p_attr) {
/* Update HFP version back to 1.6 */
p_attr->value_ptr[PROFILE_VERSION_POSITION] = HFP_PROFILE_MINOR_VERSION_6;
- LOG_VERBOSE("Restore HFP version to 1.6");
+ log::verbose("Restore HFP version to 1.6");
is_hfp_fallback = false;
}
@@ -266,7 +269,7 @@
default:
sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_REQ_SYNTAX,
SDP_TEXT_BAD_PDU);
- LOG_WARN("SDP - server got unknown PDU: 0x%x", pdu_id);
+ log::warn("SDP - server got unknown PDU: 0x{:x}", pdu_id);
break;
}
}
@@ -379,10 +382,10 @@
UINT16_TO_BE_STREAM(p_rsp, num_rsp_handles);
UINT16_TO_BE_STREAM(p_rsp, cur_handles);
- /* LOG_VERBOSE("SDP Service Rsp: tothdl %d, curhdlr %d, start %d, end %d,
- cont %d",
- num_rsp_handles, cur_handles, cont_offset,
- cont_offset + cur_handles-1, is_cont); */
+ /*
+ log::verbose("SDP Service Rsp: tothdl {}, curhdlr {}, start {}, end {}, cont
+ {}", num_rsp_handles, cur_handles, cont_offset, cont_offset + cur_handles-1,
+ is_cont); */
for (xx = cont_offset; xx < cont_offset + cur_handles; xx++)
UINT32_TO_BE_STREAM(p_rsp, rsp_handles[xx]);
@@ -474,7 +477,7 @@
pbap_pse_dynamic_version_upgrade_is_enabled()) {
p_rec = sdp_upgrade_pse_record(p_rec, p_ccb->device_address);
} else {
- LOG_WARN("PBAP PSE dynamic version upgrade is not enabled");
+ log::warn("PBAP PSE dynamic version upgrade is not enabled");
}
/* Free and reallocate buffer */
@@ -540,7 +543,7 @@
dynamic_avrcp_version_enhancement_is_enabled()) {
avrc_sdp_version = sdpu_is_avrcp_profile_description_list(
p_attr_profile_desc_list_id);
- LOG_ERROR("avrc_sdp_version in SDP records %x", avrc_sdp_version);
+ log::error("avrc_sdp_version in SDP records {:x}", avrc_sdp_version);
sdpu_set_avrc_target_features(p_attr, &(p_ccb->device_address),
avrc_sdp_version);
}
@@ -563,7 +566,7 @@
/* if there is a partial attribute pending to be sent */
if (p_ccb->cont_info.attr_offset) {
if (attr_len < p_ccb->cont_info.attr_offset) {
- LOG(ERROR) << "offset is bigger than attribute length";
+ log::error("offset is bigger than attribute length");
sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE,
SDP_TEXT_BAD_CONT_LEN);
return;
@@ -580,8 +583,8 @@
attr_len) /* Not enough space for attr... so add partially */
{
if (attr_len >= SDP_MAX_ATTR_LEN) {
- LOG_ERROR("SDP attr too big: max_list_len=%d,attr_len=%d",
- max_list_len, attr_len);
+ log::error("SDP attr too big: max_list_len={},attr_len={}",
+ max_list_len, attr_len);
sdpu_build_n_send_error(p_ccb, trans_num, SDP_NO_RESOURCES, NULL);
return;
}
@@ -791,7 +794,7 @@
pbap_pse_dynamic_version_upgrade_is_enabled()) {
p_rec = sdp_upgrade_pse_record(p_rec, p_ccb->device_address);
} else {
- LOG_WARN("PBAP PSE dynamic version upgrade is not enabled");
+ log::warn("PBAP PSE dynamic version upgrade is not enabled");
}
/* Allow space for attribute sequence type and length */
p_seq_start = p_rsp;
@@ -834,7 +837,8 @@
p_attr_profile_desc_list_id != nullptr) {
avrc_sdp_version = sdpu_is_avrcp_profile_description_list(
p_attr_profile_desc_list_id);
- LOG_ERROR("avrc_sdp_version in SDP records %x", avrc_sdp_version);
+ log::error("avrc_sdp_version in SDP records {:x}",
+ avrc_sdp_version);
sdpu_set_avrc_target_features(p_attr, &(p_ccb->device_address),
avrc_sdp_version);
}
@@ -858,7 +862,7 @@
/* if there is a partial attribute pending to be sent */
if (p_ccb->cont_info.attr_offset) {
if (attr_len < p_ccb->cont_info.attr_offset) {
- LOG(ERROR) << "offset is bigger than attribute length";
+ log::error("offset is bigger than attribute length");
sdpu_build_n_send_error(p_ccb, trans_num, SDP_INVALID_CONT_STATE,
SDP_TEXT_BAD_CONT_LEN);
return;
@@ -876,8 +880,8 @@
attr_len) /* Not enough space for attr... so add partially */
{
if (attr_len >= SDP_MAX_ATTR_LEN) {
- LOG_ERROR("SDP attr too big: max_list_len=%d,attr_len=%d",
- max_list_len, attr_len);
+ log::error("SDP attr too big: max_list_len={},attr_len={}",
+ max_list_len, attr_len);
sdpu_build_n_send_error(p_ccb, trans_num, SDP_NO_RESOURCES, NULL);
return;
}
@@ -979,12 +983,12 @@
sdp_pbap_pse_dynamic_attributes_len_update(p_ccb, &attr_seq_sav,
&uid_seq);
} else {
- LOG_WARN("PBAP PSE dynamic version upgrade is not enabled");
+ log::warn("PBAP PSE dynamic version upgrade is not enabled");
p_ccb->pse_dynamic_attributes_len = 0;
}
- LOG_VERBOSE("p_ccb->list_len = %d pse_dynamic_attributes_len = %d",
- p_ccb->list_len, p_ccb->pse_dynamic_attributes_len);
+ log::verbose("p_ccb->list_len = {} pse_dynamic_attributes_len = {}",
+ p_ccb->list_len, p_ccb->pse_dynamic_attributes_len);
/* Put in the sequence header (2 or 3 bytes) */
if (p_ccb->list_len > 255) {
@@ -1030,9 +1034,9 @@
p_ccb->cont_offset += len_to_send;
- LOG_VERBOSE(
- "p_ccb->pse_dynamic_attributes_len %d, cont_offset = %d, p_ccb->list_len "
- "= %d",
+ log::verbose(
+ "p_ccb->pse_dynamic_attributes_len {}, cont_offset = {}, p_ccb->list_len "
+ "= {}",
p_ccb->pse_dynamic_attributes_len, p_ccb->cont_offset,
p_ccb->list_len + p_ccb->pse_dynamic_attributes_len);
/* If anything left to send, continuation needed */
@@ -1073,7 +1077,7 @@
if (!check_for_1_2 &&
interop_match_addr_or_name(INTEROP_ADV_PBAP_VER_1_1, &remote_address,
&btif_storage_get_remote_device_property)) {
- LOG_VERBOSE("device is in allowlist for pbap version < 1.2 ");
+ log::verbose("device is in allowlist for pbap version < 1.2");
return true;
}
if (check_for_1_2) {
@@ -1081,14 +1085,15 @@
if (interop_match_addr_or_name(
INTEROP_ADV_PBAP_VER_1_2, &remote_address,
&btif_storage_get_remote_device_property)) {
- LOG_VERBOSE("device is in allowlist for pbap version 1.2 ");
+ log::verbose("device is in allowlist for pbap version 1.2");
return true;
}
} else {
const char* p_name = BTM_SecReadDevName(remote_address);
if ((p_name != NULL) &&
interop_match_name(INTEROP_ADV_PBAP_VER_1_2, p_name)) {
- LOG_VERBOSE("device is not paired & in allowlist for pbap version 1.2");
+ log::verbose(
+ "device is not paired & in allowlist for pbap version 1.2");
return true;
}
}
@@ -1122,10 +1127,9 @@
is_device_in_allowlist_for_pbap(p_ccb->device_address, true);
bool running_pts = osi_property_get_bool(SDP_ENABLE_PTS_PBAP, false);
- LOG_VERBOSE(
- "remote BD Addr : %s is_pbap_102_supported = %d "
- "is_pbap_101_allowlisted = %d is_pbap_102_allowlisted = %d "
- "running_pts = %d",
+ log::verbose(
+ "remote BD Addr : {} is_pbap_102_supported = {} is_pbap_101_allowlisted "
+ "= {} is_pbap_102_allowlisted = {} running_pts = {}",
ADDRESS_TO_LOGGABLE_CSTR(p_ccb->device_address), is_pbap_102_supported,
is_pbap_101_allowlisted, is_pbap_102_allowlisted, running_pts);
@@ -1145,16 +1149,15 @@
UUID_SERVCLASS_PBAP_PSE)) {
// PBAP PSE Record
p_rec = sdp_upgrade_pse_record(p_rec, p_ccb->device_address);
- LOG_VERBOSE("response has PBAP PSE record for allowlist device");
+ log::verbose("response has PBAP PSE record for allowlist device");
int att_index;
bool l2cap_psm_len_included = false, supp_attr_len_included = false;
for (xx = p_ccb->cont_info.next_attr_index; xx < attr_seq->num_attr;
xx++) {
- LOG_VERBOSE(
- "xx = %d attr_seq->num_attr = %d, "
- "attr_seq->attr_entry[xx].start = %d , "
- "attr_seq->attr_entry[xx].end = %d",
+ log::verbose(
+ "xx = {} attr_seq->num_attr = {}, attr_seq->attr_entry[xx].start = "
+ "{} , attr_seq->attr_entry[xx].end = {}",
xx, attr_seq->num_attr, attr_seq->attr_entry[xx].start,
attr_seq->attr_entry[xx].end);
@@ -1166,9 +1169,8 @@
cur_attr.id <= attr_seq->attr_entry[xx].end) {
l2cap_psm_len_included = true;
p_ccb->pse_dynamic_attributes_len += PBAP_GOEP_L2CAP_PSM_LEN;
- LOG_ERROR(
- "ATTR_ID_GOEP_L2CAP_PSM requested,"
- " need to change length by %d",
+ log::error(
+ "ATTR_ID_GOEP_L2CAP_PSM requested, need to change length by {}",
p_ccb->pse_dynamic_attributes_len);
} else if (cur_attr.id == ATTR_ID_PBAP_SUPPORTED_FEATURES &&
!supp_attr_len_included &&
@@ -1176,9 +1178,9 @@
cur_attr.id <= attr_seq->attr_entry[xx].end) {
supp_attr_len_included = true;
p_ccb->pse_dynamic_attributes_len += PBAP_SUPP_FEA_LEN;
- LOG_VERBOSE(
- "ATTR_ID_PBAP_SUPPORTED_FEATURES requested,"
- " need to change length by %d",
+ log::verbose(
+ "ATTR_ID_PBAP_SUPPORTED_FEATURES requested, need to change "
+ "length by {}",
p_ccb->pse_dynamic_attributes_len);
}
}
@@ -1187,8 +1189,8 @@
break;
}
}
- LOG_VERBOSE("pse_dynamic_attributes_len = %d",
- p_ccb->pse_dynamic_attributes_len);
+ log::verbose("pse_dynamic_attributes_len = {}",
+ p_ccb->pse_dynamic_attributes_len);
return p_ccb->pse_dynamic_attributes_len;
}
@@ -1221,11 +1223,10 @@
is_device_in_allowlist_for_pbap(remote_address, true);
bool running_pts = osi_property_get_bool(SDP_ENABLE_PTS_PBAP, false);
- LOG_VERBOSE(
- "%s remote BD Addr : %s is_pbap_102_supported : %d "
- "is_pbap_101_allowlisted = %d is_pbap_102_allowlisted = %d "
- "running_pts = %d",
- __func__, ADDRESS_TO_LOGGABLE_CSTR(remote_address), is_pbap_102_supported,
+ log::verbose(
+ "remote BD Addr : {} is_pbap_102_supported : {} is_pbap_101_allowlisted "
+ "= {} is_pbap_102_allowlisted = {} running_pts = {}",
+ ADDRESS_TO_LOGGABLE_CSTR(remote_address), is_pbap_102_supported,
is_pbap_101_allowlisted, is_pbap_102_allowlisted, running_pts);
if (is_pbap_101_allowlisted ||
@@ -1269,7 +1270,7 @@
UINT_DESC_TYPE, (uint32_t)2, temp);
if (!status) {
- LOG_ERROR("FAILED");
+ log::error("FAILED");
return p_rec;
}
return &pbap_102_sdp_rec;
@@ -1286,11 +1287,11 @@
if (!interop_match_addr_or_name(INTEROP_ADV_PBAP_VER_1_2, &remote_addr,
&btif_storage_get_remote_device_property)) {
interop_database_add_addr(INTEROP_ADV_PBAP_VER_1_2, &remote_addr, 3);
- LOG_VERBOSE("device: %s is added into interop list",
- ADDRESS_TO_LOGGABLE_CSTR(remote_addr));
+ log::verbose("device: {} is added into interop list",
+ ADDRESS_TO_LOGGABLE_CSTR(remote_addr));
} else {
- LOG_WARN("device: %s is already found on interop list",
- ADDRESS_TO_LOGGABLE_CSTR(remote_addr));
+ log::warn("device: {} is already found on interop list",
+ ADDRESS_TO_LOGGABLE_CSTR(remote_addr));
}
}
@@ -1308,7 +1309,7 @@
if (interop_match_addr_or_name(INTEROP_DISABLE_PCE_SDP_AFTER_PAIRING,
&remote_address,
&btif_storage_get_remote_device_property)) {
- LOG_VERBOSE("device is denylisted for PCE SDP ");
+ log::verbose("device is denylisted for PCE SDP");
return true;
} else {
return false;
@@ -1330,9 +1331,9 @@
int32_t profile_version,
uint32_t supported_features,
uint32_t supported_repositories) {
- LOG_WARN(
- "rfcomm_channel_number: 0x%x, l2cap_psm: 0x%x profile_version: 0x%x"
- "supported_features: 0x%x supported_repositories: 0x%x",
+ log::warn(
+ "rfcomm_channel_number: 0x{:x}, l2cap_psm: 0x{:x} profile_version: "
+ "0x{:x}supported_features: 0x{:x} supported_repositories: 0x{:x}",
rfcomm_channel_number, l2cap_psm, profile_version, supported_features,
supported_repositories);
sdpPseLocalRecord.rfcomm_channel_number = rfcomm_channel_number;
diff --git a/system/stack/sdp/sdp_utils.cc b/system/stack/sdp/sdp_utils.cc
index 2f19c46..3211e34 100644
--- a/system/stack/sdp/sdp_utils.cc
+++ b/system/stack/sdp/sdp_utils.cc
@@ -25,6 +25,7 @@
******************************************************************************/
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <log/log.h>
#include <array>
@@ -39,7 +40,6 @@
#include "btif/include/stack_manager_t.h"
#include "common/init_flags.h"
#include "device/include/interop.h"
-#include "gd/storage/config_keys.h"
#include "internal_include/bt_target.h"
#include "internal_include/bt_trace.h"
#include "os/log.h"
@@ -55,10 +55,12 @@
#include "stack/include/sdpdefs.h"
#include "stack/include/stack_metrics_logging.h"
#include "stack/sdp/sdpint.h"
+#include "storage/config_keys.h"
#include "types/bluetooth/uuid.h"
#include "types/raw_address.h"
using bluetooth::Uuid;
+using namespace bluetooth;
bool SDP_FindProtocolListElemInRec(const tSDP_DISC_REC* p_rec,
uint16_t layer_uuid,
@@ -107,8 +109,8 @@
// Safety check - each entry should itself be a sequence
if (SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type) !=
DATA_ELE_SEQ_DESC_TYPE) {
- LOG(WARNING) << __func__ << ": Descriptor type is not sequence: "
- << loghex(SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type));
+ log::warn("Descriptor type is not sequence: {}",
+ loghex(SDP_DISC_ATTR_TYPE(p_sattr->attr_len_type)));
return std::vector<std::pair<uint16_t, uint16_t>>();
}
// Now, see if the entry contains the profile UUID we are interested in
@@ -125,13 +127,11 @@
SDP_DISC_ATTR_TYPE(version_attr->attr_len_type) != UINT_DESC_TYPE ||
SDP_DISC_ATTR_LEN(version_attr->attr_len_type) != 2) {
if (version_attr == nullptr) {
- LOG(WARNING) << __func__ << ": version attr not found";
+ log::warn("version attr not found");
} else {
- LOG(WARNING) << __func__ << ": Bad version type "
- << loghex(
- SDP_DISC_ATTR_TYPE(version_attr->attr_len_type))
- << ", or length "
- << SDP_DISC_ATTR_LEN(version_attr->attr_len_type);
+ log::warn("Bad version type {}, or length {}",
+ loghex(SDP_DISC_ATTR_TYPE(version_attr->attr_len_type)),
+ SDP_DISC_ATTR_LEN(version_attr->attr_len_type));
}
return std::vector<std::pair<uint16_t, uint16_t>>();
}
@@ -179,7 +179,7 @@
}
}
} else {
- LOG(WARNING) << __func__ << ": Bad Service Class ID list attribute";
+ log::warn("Bad Service Class ID list attribute");
return 0;
}
} else if (p_attr->attr_id == ATTR_ID_SERVICE_ID) {
@@ -200,8 +200,8 @@
p_rec = p_rec->p_next_rec) {
uint16_t service_uuid = sdpu_find_most_specific_service_uuid(p_rec);
if (service_uuid == 0) {
- LOG(INFO) << __func__ << ": skipping record without service uuid "
- << ADDRESS_TO_LOGGABLE_STR(bda);
+ log::info("skipping record without service uuid {}",
+ ADDRESS_TO_LOGGABLE_STR(bda));
continue;
}
// Log the existence of a profile role
@@ -447,7 +447,7 @@
ccb.is_attr_search = false;
/* Free the response buffer */
- if (ccb.rsp_list) LOG_VERBOSE("releasing SDP rsp_list");
+ if (ccb.rsp_list) log::verbose("releasing SDP rsp_list");
osi_free_and_reset((void**)&ccb.rsp_list);
}
@@ -723,8 +723,8 @@
uint16_t rsp_param_len;
BT_HDR* p_buf = (BT_HDR*)osi_malloc(SDP_DATA_BUF_SIZE);
- LOG_WARN("SDP - sdpu_build_n_send_error code: 0x%x CID: 0x%x", error_code,
- p_ccb->connection_id);
+ log::warn("SDP - sdpu_build_n_send_error code: 0x{:x} CID: 0x{:x}",
+ error_code, p_ccb->connection_id);
/* Send the packet to L2CAP */
p_buf->offset = L2CAP_MIN_OFFSET;
@@ -1074,7 +1074,7 @@
if (((len1 != 2) && (len1 != 4) && (len1 != 16)) ||
((len2 != 2) && (len2 != 4) && (len2 != 16))) {
- LOG_ERROR("%s: invalid length", __func__);
+ log::error("invalid length");
return false;
}
@@ -1338,7 +1338,7 @@
uint16_t attr_len = sdpu_get_attrib_entry_len(p_attr);
if (len > SDP_MAX_ATTR_LEN) {
- LOG_ERROR("%s len %d exceeds SDP_MAX_ATTR_LEN", __func__, len);
+ log::error("len {} exceeds SDP_MAX_ATTR_LEN", len);
len = SDP_MAX_ATTR_LEN;
}
@@ -1450,10 +1450,10 @@
// Check attribute is AVRCP profile description list and get AVRC Target
// version
uint16_t avrcp_version = sdpu_is_avrcp_profile_description_list(p_attr);
- LOG_INFO("SDP AVRCP DB Version %x", avrcp_version);
+ log::info("SDP AVRCP DB Version {:x}", avrcp_version);
if (avrcp_version == 0) {
- LOG_INFO("Not AVRCP version attribute or version not valid for device %s",
- ADDRESS_TO_LOGGABLE_CSTR(*bdaddr));
+ log::info("Not AVRCP version attribute or version not valid for device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(*bdaddr));
return;
}
@@ -1464,7 +1464,7 @@
->profileSpecific_HACK->AVRC_GetProfileVersion()
: avrcp_version;
- LOG_INFO("Current DUT AVRCP Version %x", dut_avrcp_version);
+ log::info("Current DUT AVRCP Version {:x}", dut_avrcp_version);
// Some remote devices will have interoperation issue when receive higher
// AVRCP version. If those devices are in IOP database and our version higher
// than device, we reply a lower version to them.
@@ -1478,9 +1478,9 @@
}
if (iop_version != 0) {
- LOG_INFO(
- "device=%s is in IOP database. "
- "Reply AVRC Target version %x instead of %x.",
+ log::info(
+ "device={} is in IOP database. Reply AVRC Target version {:x} instead "
+ "of {:x}.",
ADDRESS_TO_LOGGABLE_CSTR(*bdaddr), iop_version, avrcp_version);
uint8_t* p_version = p_attr->value_ptr + 6;
UINT16_TO_BE_FIELD(p_version, iop_version);
@@ -1490,7 +1490,7 @@
// Dynamic AVRCP version. If our version high than remote device's version,
// reply version same as its. Otherwise, reply default version.
if (!osi_property_get_bool(AVRC_DYNAMIC_AVRCP_ENABLE_PROPERTY, true)) {
- LOG_INFO(
+ log::info(
"Dynamic AVRCP version feature is not enabled, skipping this method");
return;
}
@@ -1500,28 +1500,26 @@
size_t version_value_size = btif_config_get_bin_length(
bdaddr->ToString(), BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION);
if (version_value_size != sizeof(cached_version)) {
- LOG_ERROR(
- "cached value len wrong, bdaddr=%s. Len is %zu but should be %zu.",
- ADDRESS_TO_LOGGABLE_CSTR(*bdaddr), version_value_size,
- sizeof(cached_version));
+ log::error("cached value len wrong, bdaddr={}. Len is {} but should be {}.",
+ ADDRESS_TO_LOGGABLE_CSTR(*bdaddr), version_value_size,
+ sizeof(cached_version));
return;
}
if (!btif_config_get_bin(bdaddr->ToString(),
BTIF_STORAGE_KEY_AVRCP_CONTROLLER_VERSION,
(uint8_t*)&cached_version, &version_value_size)) {
- LOG_INFO(
- "no cached AVRC Controller version for %s. "
- "Reply default AVRC Target version %x."
- "DUT AVRC Target version %x.",
+ log::info(
+ "no cached AVRC Controller version for {}. Reply default AVRC Target "
+ "version {:x}.DUT AVRC Target version {:x}.",
ADDRESS_TO_LOGGABLE_CSTR(*bdaddr), avrcp_version, dut_avrcp_version);
return;
}
if (!spdu_is_avrcp_version_valid(cached_version)) {
- LOG_ERROR(
- "cached AVRC Controller version %x of %s is not valid. "
- "Reply default AVRC Target version %x.",
+ log::error(
+ "cached AVRC Controller version {:x} of {} is not valid. Reply default "
+ "AVRC Target version {:x}.",
cached_version, ADDRESS_TO_LOGGABLE_CSTR(*bdaddr), avrcp_version);
return;
}
@@ -1534,10 +1532,9 @@
uint16_t negotiated_avrcp_version =
std::min(dut_avrcp_version, cached_version);
- LOG_INFO(
- "read cached AVRC Controller version %x of %s. "
- "DUT AVRC Target version %x."
- "Negotiated AVRCP version to update peer %x. ",
+ log::info(
+ "read cached AVRC Controller version {:x} of {}. DUT AVRC Target version "
+ "{:x}.Negotiated AVRCP version to update peer {:x}.",
cached_version, ADDRESS_TO_LOGGABLE_CSTR(*bdaddr), dut_avrcp_version,
negotiated_avrcp_version);
uint8_t* p_version = p_attr->value_ptr + 6;
@@ -1559,24 +1556,24 @@
void sdpu_set_avrc_target_features(const tSDP_ATTRIBUTE* p_attr,
const RawAddress* bdaddr,
uint16_t avrcp_version) {
- LOG_INFO("SDP AVRCP Version %x", avrcp_version);
+ log::info("SDP AVRCP Version {:x}", avrcp_version);
if ((p_attr->id != ATTR_ID_SUPPORTED_FEATURES) || (p_attr->len != 2) ||
(p_attr->value_ptr == nullptr)) {
- LOG_INFO("Invalid request for AVRC feature ignore");
+ log::info("Invalid request for AVRC feature ignore");
return;
}
if (avrcp_version == 0) {
- LOG_INFO("AVRCP version not valid for device %s",
- ADDRESS_TO_LOGGABLE_CSTR(*bdaddr));
+ log::info("AVRCP version not valid for device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(*bdaddr));
return;
}
// Dynamic AVRCP version. If our version high than remote device's version,
// reply version same as its. Otherwise, reply default version.
if (!osi_property_get_bool(AVRC_DYNAMIC_AVRCP_ENABLE_PROPERTY, false)) {
- LOG_INFO(
+ log::info(
"Dynamic AVRCP version feature is not enabled, skipping this method");
return;
}
@@ -1585,17 +1582,16 @@
size_t version_value_size = btif_config_get_bin_length(
bdaddr->ToString(), BTIF_STORAGE_KEY_AV_REM_CTRL_FEATURES);
if (version_value_size != sizeof(avrcp_peer_features)) {
- LOG_ERROR(
- "cached value len wrong, bdaddr=%s. Len is %zu but should be %zu.",
- ADDRESS_TO_LOGGABLE_CSTR(*bdaddr), version_value_size,
- sizeof(avrcp_peer_features));
+ log::error("cached value len wrong, bdaddr={}. Len is {} but should be {}.",
+ ADDRESS_TO_LOGGABLE_CSTR(*bdaddr), version_value_size,
+ sizeof(avrcp_peer_features));
return;
}
if (!btif_config_get_bin(
bdaddr->ToString(), BTIF_STORAGE_KEY_AV_REM_CTRL_FEATURES,
(uint8_t*)&avrcp_peer_features, &version_value_size)) {
- LOG_ERROR("Unable to fetch cached AVRC features");
+ log::error("Unable to fetch cached AVRC features");
return;
}
@@ -1604,11 +1600,12 @@
bool coverart_supported =
((AVRCP_FEAT_CA_BIT & avrcp_peer_features) == AVRCP_FEAT_CA_BIT);
- LOG_INFO(
- "SDP AVRCP DB Version 0x%x, browse supported %d, cover art supported %d",
+ log::info(
+ "SDP AVRCP DB Version 0x{:x}, browse supported {}, cover art supported "
+ "{}",
avrcp_peer_features, browsing_supported, coverart_supported);
if (avrcp_version < AVRC_REV_1_4 || !browsing_supported) {
- LOG_INFO("Reset Browsing Feature ");
+ log::info("Reset Browsing Feature");
p_attr->value_ptr[AVRCP_SUPPORTED_FEATURES_POSITION] &=
~AVRCP_BROWSE_SUPPORT_BITMASK;
p_attr->value_ptr[AVRCP_SUPPORTED_FEATURES_POSITION] &=
@@ -1616,13 +1613,13 @@
}
if (avrcp_version < AVRC_REV_1_6 || !coverart_supported) {
- LOG_INFO("Reset CoverArt Feature ");
+ log::info("Reset CoverArt Feature");
p_attr->value_ptr[AVRCP_SUPPORTED_FEATURES_POSITION - 1] &=
~AVRCP_CA_SUPPORT_BITMASK;
}
if (avrcp_version >= AVRC_REV_1_4 && browsing_supported) {
- LOG_INFO("Set Browsing Feature ");
+ log::info("Set Browsing Feature");
p_attr->value_ptr[AVRCP_SUPPORTED_FEATURES_POSITION] |=
AVRCP_BROWSE_SUPPORT_BITMASK;
p_attr->value_ptr[AVRCP_SUPPORTED_FEATURES_POSITION] |=
@@ -1630,7 +1627,7 @@
}
if (avrcp_version == AVRC_REV_1_6 && coverart_supported) {
- LOG_INFO("Set CoverArt Feature ");
+ log::info("Set CoverArt Feature");
p_attr->value_ptr[AVRCP_SUPPORTED_FEATURES_POSITION - 1] |=
AVRCP_CA_SUPPORT_BITMASK;
}
diff --git a/system/stack/smp/smp_act.cc b/system/stack/smp/smp_act.cc
index b6c0e0e..fdc5290 100644
--- a/system/stack/smp/smp_act.cc
+++ b/system/stack/smp/smp_act.cc
@@ -19,6 +19,7 @@
#define LOG_TAG "smp_act"
#include <android_bluetooth_flags.h>
+#include <bluetooth/log.h>
#include <cstring>
@@ -41,6 +42,8 @@
#include "stack/include/smp_api_types.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
namespace {
constexpr char kBtmLogTag[] = "SMP";
}
@@ -1951,7 +1954,7 @@
}
if (!p_sc_oob_data->peer_oob_data.present) {
- LOG_VERBOSE("peer OOB data is absent");
+ log::verbose("peer OOB data is absent");
p_cb->peer_random = {0};
} else {
p_cb->peer_random = p_sc_oob_data->peer_oob_data.randomizer;
diff --git a/system/stack/test/common/mock_hcic_layer.cc b/system/stack/test/common/mock_hcic_layer.cc
index bb670a9..d885b9d 100644
--- a/system/stack/test/common/mock_hcic_layer.cc
+++ b/system/stack/test/common/mock_hcic_layer.cc
@@ -108,7 +108,6 @@
class MockInterface : public Interface {
public:
- virtual void InquiryCancel() const override { FAIL(); }
virtual void Disconnect(uint16_t handle, uint8_t reason) const override {
btsnd_hcic_disconnect(handle, reason);
}
diff --git a/system/stack/test/fuzzers/Android.bp b/system/stack/test/fuzzers/Android.bp
index 991d012..7fb9b3a 100644
--- a/system/stack/test/fuzzers/Android.bp
+++ b/system/stack/test/fuzzers/Android.bp
@@ -47,6 +47,7 @@
"libbte",
"libbtif",
"libbtif-core",
+ "libcom.android.sysprop.bluetooth.wrapped",
"libg722codec",
"liblc3",
"libopus",
diff --git a/system/test/Android.bp b/system/test/Android.bp
index 96d40a6..60e217b 100644
--- a/system/test/Android.bp
+++ b/system/test/Android.bp
@@ -190,7 +190,21 @@
filegroup {
name: "TestMockMainShim",
srcs: [
- "mock/mock_main_shim*.cc",
+ "mock/mock_main_shim.cc",
+ "mock/mock_main_shim_BtifConfigInterface.cc",
+ "mock/mock_main_shim_acl.cc",
+ "mock/mock_main_shim_acl_api.cc",
+ "mock/mock_main_shim_acl_legacy_interface.cc",
+ "mock/mock_main_shim_btm_api.cc",
+ "mock/mock_main_shim_controller.cc",
+ "mock/mock_main_shim_distance_measurement_manager.cc",
+ "mock/mock_main_shim_dumpsys.cc",
+ "mock/mock_main_shim_hci_layer.cc",
+ "mock/mock_main_shim_l2cap_api.cc",
+ "mock/mock_main_shim_le_advertising_manager.cc",
+ "mock/mock_main_shim_le_scanning_manager.cc",
+ "mock/mock_main_shim_metric_id_api.cc",
+ "mock/mock_main_shim_metrics_api.cc",
],
}
@@ -339,6 +353,13 @@
}
filegroup {
+ name: "TestMockJni",
+ srcs: [
+ "mock/mock_jni*.cc",
+ ],
+}
+
+filegroup {
name: "TestMockStackHid",
srcs: [
"mock/mock_stack_hid*.cc",
diff --git a/system/test/common/jni_thread.cc b/system/test/common/jni_thread.cc
index 8216671..720e6dd 100644
--- a/system/test/common/jni_thread.cc
+++ b/system/test/common/jni_thread.cc
@@ -20,7 +20,7 @@
#include <map>
-#include "osi/include/log.h"
+#include "os/log.h"
std::queue<base::OnceClosure> do_in_jni_thread_task_queue;
diff --git a/system/test/common/main_handler.cc b/system/test/common/main_handler.cc
index fa1b853..a1c2f1a 100644
--- a/system/test/common/main_handler.cc
+++ b/system/test/common/main_handler.cc
@@ -25,7 +25,7 @@
#include "common/message_loop_thread.h"
#include "include/hardware/bluetooth.h"
-#include "osi/include/log.h"
+#include "os/log.h"
using bluetooth::common::MessageLoopThread;
using BtMainClosure = std::function<void()>;
diff --git a/system/test/common/main_handler.h b/system/test/common/main_handler.h
index 2fee7aa..07fc190 100644
--- a/system/test/common/main_handler.h
+++ b/system/test/common/main_handler.h
@@ -22,6 +22,7 @@
#include <functional>
#include "common/message_loop_thread.h"
+#include "include/hardware/bluetooth.h"
using bluetooth::common::MessageLoopThread;
using BtMainClosure = std::function<void()>;
@@ -34,6 +35,6 @@
void post_on_bt_main(BtMainClosure closure);
void main_thread_start_up();
void main_thread_shut_down();
-extern int sync_timeout_in_ms;
+extern const int sync_timeout_in_ms;
void sync_main_handler();
bluetooth::common::MessageLoopThread* get_main_thread();
diff --git a/system/test/common/mock_functions.cc b/system/test/common/mock_functions.cc
index 776cf1d..638d5b3 100644
--- a/system/test/common/mock_functions.cc
+++ b/system/test/common/mock_functions.cc
@@ -18,7 +18,7 @@
#include <map>
-#include "osi/include/log.h"
+#include "os/log.h"
static std::map<std::string, int>& _get_func_call_count_map() {
static std::map<std::string, int> mock_function_count_map;
diff --git a/system/test/fake/fake_looper.cc b/system/test/fake/fake_looper.cc
index 582fe12..a9ea606 100644
--- a/system/test/fake/fake_looper.cc
+++ b/system/test/fake/fake_looper.cc
@@ -26,8 +26,8 @@
#include <mutex>
#include <queue>
+#include "os/log.h"
#include "osi/include/allocator.h"
-#include "osi/include/log.h"
#include "test/fake/fake_thread.h"
pid_t get_thread_id() {
diff --git a/system/test/headless/Android.bp b/system/test/headless/Android.bp
index 527d620..6df1aad 100644
--- a/system/test/headless/Android.bp
+++ b/system/test/headless/Android.bp
@@ -41,7 +41,8 @@
"HeadlessBuildTimestamp",
],
srcs: [
- "bt_property.cc",
+ "adapter/adapter.cc",
+ "bt_stack_info.cc",
"connect/connect.cc",
"discovery/discovery.cc",
"dumpsys/dumpsys.cc",
@@ -51,6 +52,7 @@
"log.cc",
"main.cc",
"messenger.cc",
+ "mode/mode.cc",
"nop/nop.cc",
"pairing/pairing.cc",
"property.cc",
@@ -59,11 +61,13 @@
"scan/scan.cc",
"sdp/sdp.cc",
"sdp/sdp_db.cc",
+ "text.cc",
"util.cc",
],
include_dirs: [
"packages/modules/Bluetooth/system",
"packages/modules/Bluetooth/system/gd",
+ "packages/modules/Bluetooth/system/include",
"packages/modules/Bluetooth/system/stack/include",
],
static_libs: [
@@ -102,6 +106,7 @@
"libbtif-core",
"libc++fs",
"libchrome",
+ "libcom.android.sysprop.bluetooth.wrapped",
"libevent",
"libflatbuffers-cpp",
"libg722codec",
diff --git a/system/test/headless/adapter/adapter.cc b/system/test/headless/adapter/adapter.cc
new file mode 100644
index 0000000..7de75c7
--- /dev/null
+++ b/system/test/headless/adapter/adapter.cc
@@ -0,0 +1,90 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "bt_headless_scan"
+
+#include "test/headless/adapter/adapter.h"
+
+#include "base/logging.h" // LOG() stdout and android log
+#include "gd/os/log.h"
+#include "test/headless/headless.h"
+#include "test/headless/interface.h"
+#include "test/headless/log.h"
+#include "test/headless/messenger.h"
+#include "test/headless/stopwatch.h"
+
+using namespace bluetooth::test;
+using namespace std::chrono_literals;
+
+namespace {
+
+unsigned kTimeoutMs = 5000;
+
+int get_adapter_info([[maybe_unused]] unsigned int num_loops) {
+ LOG(INFO) << "Started Device Adapter Properties";
+
+ ASSERT(bluetoothInterface.get_adapter_properties() == BT_STATUS_SUCCESS);
+ LOG_CONSOLE("Started get adapter properties");
+
+ headless::messenger::Context context{
+ .stop_watch = Stopwatch(__func__),
+ .timeout = 1s, // Poll time
+ .check_point = {},
+ .callbacks = {Callback::AdapterProperties},
+ };
+
+ bool adapter_properties_found = false;
+ while (context.stop_watch.LapMs() < kTimeoutMs) {
+ // If we have received callback results within this timeframe...
+ if (headless::messenger::await_callback(context)) {
+ while (!context.callback_ready_q.empty()) {
+ std::shared_ptr<callback_params_t> p = context.callback_ready_q.front();
+ context.callback_ready_q.pop_front();
+ switch (p->CallbackType()) {
+ case Callback::AdapterProperties: {
+ adapter_properties_params_t* q =
+ static_cast<adapter_properties_params_t*>(p.get());
+ for (const auto& p2 : q->properties()) {
+ LOG_CONSOLE(" %s prop:%s", p->Name().c_str(),
+ p2->ToString().c_str());
+ }
+ adapter_properties_found = true;
+ } break;
+ default:
+ LOG_CONSOLE("WARN Received callback for unasked:%s",
+ p->Name().c_str());
+ break;
+ }
+ }
+ }
+ if (adapter_properties_found) break;
+ }
+
+ LOG_CONSOLE("Retrieved adapter properties");
+ return 0;
+}
+
+} // namespace
+
+int bluetooth::test::headless::Adapter::Run() {
+ if (options_.loop_ < 1) {
+ LOG_CONSOLE("This test requires at least a single loop");
+ options_.Usage();
+ return -1;
+ }
+ return RunOnHeadlessStack<int>(
+ [this]() { return get_adapter_info(options_.loop_); });
+}
diff --git a/system/test/headless/adapter/adapter.h b/system/test/headless/adapter/adapter.h
new file mode 100644
index 0000000..b6b7e1c
--- /dev/null
+++ b/system/test/headless/adapter/adapter.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include "test/headless/get_options.h"
+#include "test/headless/headless.h"
+
+namespace bluetooth {
+namespace test {
+namespace headless {
+
+class Adapter : public HeadlessTest<int> {
+ public:
+ Adapter(const bluetooth::test::headless::GetOpt& options)
+ : HeadlessTest<int>(options) {}
+ virtual ~Adapter() = default;
+
+ int Run() override;
+};
+
+} // namespace headless
+} // namespace test
+} // namespace bluetooth
diff --git a/system/test/headless/android_namespace.cc b/system/test/headless/android_namespace.cc
new file mode 100644
index 0000000..4d4a1b1
--- /dev/null
+++ b/system/test/headless/android_namespace.cc
@@ -0,0 +1,21 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+extern "C" {
+struct android_namespace_t* android_get_exported_namespace(const char*) {
+ return nullptr;
+}
+} // "C"
diff --git a/system/test/headless/bt_property.cc b/system/test/headless/bt_property.cc
deleted file mode 100644
index 5b6c2d5..0000000
--- a/system/test/headless/bt_property.cc
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "bt_headless_property"
-
-#include "test/headless/bt_property.h"
-
-#include "base/logging.h" // LOG() stdout and android log
-#include "btif/include/btif_api.h"
-#include "osi/include/log.h" // android log only
-#include "stack/include/sdp_api.h"
-#include "test/headless/get_options.h"
-#include "test/headless/headless.h"
-#include "test/headless/interface.h"
-#include "test/headless/log.h"
-#include "test/headless/sdp/sdp.h"
-#include "test/headless/stopwatch.h"
-#include "types/bluetooth/uuid.h"
-#include "types/raw_address.h"
-
-using namespace bluetooth::test::headless;
-using namespace std::chrono_literals;
-
-namespace bluetooth {
-namespace test {
-namespace headless {
-
-void process_property(const RawAddress& bd_addr, const bt_property_t* prop) {
- LOG_INFO("%s bt_property type:%d len:%d val:%p",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), prop->type,
- prop->len, prop->val);
- switch (prop->type) {
- case BT_PROPERTY_BDNAME: {
- ASSERT(prop->len >= 0);
- std::string name(static_cast<const char*>(prop->val),
- static_cast<size_t>(prop->len));
- LOG_CONSOLE("BT_PROPERTY_BDNAME NAME:%s", name.c_str());
- } break;
- case BT_PROPERTY_BDADDR:
- LOG_CONSOLE("BT_PROPERTY_BDADDR");
- break;
- case BT_PROPERTY_UUIDS: {
- const size_t remainder = prop->len % sizeof(bluetooth::Uuid);
- ASSERT(remainder == 0);
- bluetooth::Uuid* uuid = reinterpret_cast<bluetooth::Uuid*>(prop->val);
- for (int len = prop->len; len > 0; len -= sizeof(*uuid)) {
- LOG_CONSOLE("BT_PROPERTY_UUIDS UUID:%s", uuid->ToString().c_str());
- uuid++;
- }
- } break;
- case BT_PROPERTY_CLASS_OF_DEVICE: {
- ASSERT(prop->len == 4);
- uint32_t cod = *(reinterpret_cast<uint32_t*>(prop->val));
- LOG_CONSOLE("BT_PROPERTY_CLASS_OF_DEVICE 0x%04x", cod);
- } break;
- case BT_PROPERTY_TYPE_OF_DEVICE: {
- ASSERT(prop->len == 4);
- uint32_t devtype = *(reinterpret_cast<uint32_t*>(prop->val));
- LOG_CONSOLE("BT_PROPERTY_TYPE_OF_DEVICE 0x%04x", devtype);
- } break;
- case BT_PROPERTY_SERVICE_RECORD:
- LOG_CONSOLE("BT_PROPERTY_SERVICE_RECORD");
- break;
- case BT_PROPERTY_ADAPTER_SCAN_MODE:
- LOG_CONSOLE("BT_PROPERTY_ADAPTER_SCAN_MODE");
- break;
- case BT_PROPERTY_ADAPTER_BONDED_DEVICES:
- LOG_CONSOLE("BT_PROPERTY_ADAPTER_BONDED_DEVICES");
- break;
- case BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT:
- LOG_CONSOLE("BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT");
- break;
- case BT_PROPERTY_REMOTE_FRIENDLY_NAME:
- LOG_CONSOLE("BT_PROPERTY_REMOTE_FRIENDLY_NAME");
- break;
- case BT_PROPERTY_REMOTE_RSSI:
- LOG_CONSOLE("BT_PROPERTY_REMOTE_RSSI");
- break;
- case BT_PROPERTY_REMOTE_VERSION_INFO:
- LOG_CONSOLE("BT_PROPERTY_REMOTE_VERSION_INFO");
- break;
- case BT_PROPERTY_LOCAL_LE_FEATURES:
- LOG_CONSOLE("BT_PROPERTY_LOCAL_LE_FEATURES");
- break;
- case BT_PROPERTY_LOCAL_IO_CAPS:
- LOG_CONSOLE("BT_PROPERTY_LOCAL_IO_CAPS");
- break;
- case BT_PROPERTY_DYNAMIC_AUDIO_BUFFER:
- LOG_CONSOLE("BT_PROPERTY_DYNAMIC_AUDIO_BUFFER");
- break;
- case BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER:
- LOG_CONSOLE("BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER");
- break;
- case BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP:
- LOG_CONSOLE("BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER");
- break;
- default: {
- LOG_CONSOLE("Unable to find BT property bd_addr:%s type:%d ptr:%p",
- ADDRESS_TO_LOGGABLE_CSTR(bd_addr), prop->type, prop);
- const uint8_t* p = reinterpret_cast<const uint8_t*>(prop);
- for (size_t i = 0; i < sizeof(bt_property_t); i++, p++) {
- LOG_CONSOLE(" %p:0x%02x", p, *p);
- }
- } break;
- }
-}
-
-} // namespace headless
-} // namespace test
-} // namespace bluetooth
diff --git a/system/test/headless/bt_property.h b/system/test/headless/bt_property.h
index 75cbd0c..cfec588 100644
--- a/system/test/headless/bt_property.h
+++ b/system/test/headless/bt_property.h
@@ -9,6 +9,8 @@
namespace headless {
void process_property(const RawAddress& bd_addr, const bt_property_t* prop);
-}
+void process_property2(const bt_property_t* prop);
+
+} // namespace headless
} // namespace test
} // namespace bluetooth
diff --git a/system/test/headless/bt_stack_info.cc b/system/test/headless/bt_stack_info.cc
new file mode 100644
index 0000000..943ab03
--- /dev/null
+++ b/system/test/headless/bt_stack_info.cc
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "test/headless/bt_stack_info.h"
+
+#include <unistd.h>
+
+#include "btif/include/btif_common.h" // do_in_jni_thread
+#include "btif/include/btif_hh.h" // DumpsysHid
+#include "main/shim/dumpsys.h"
+#include "stack/gatt/connection_manager.h"
+#include "stack/include/main_thread.h"
+#include "stack/include/pan_api.h" // PAN_Dumpsys
+#include "test/headless/log.h"
+
+BtStackInfo::BtStackInfo() {
+ {
+ std::promise<pid_t> promise;
+ auto future = promise.get_future();
+ do_in_main_thread(FROM_HERE, base::BindOnce(
+ [](std::promise<pid_t> promise) {
+ promise.set_value(getpid());
+ },
+ std::move(promise)));
+ main_pid_ = future.get();
+ }
+
+ {
+ std::promise<pid_t> promise;
+ auto future = promise.get_future();
+ do_in_jni_thread(FROM_HERE, base::BindOnce(
+ [](std::promise<pid_t> promise) {
+ promise.set_value(getpid());
+ },
+ std::move(promise)));
+ jni_pid_ = future.get();
+ }
+}
+
+void BtStackInfo::DumpsysLite() {
+ LOG_CONSOLE("main_pid:%u", main_pid_);
+ LOG_CONSOLE("jni_pid:%u", jni_pid_);
+
+ int fd = STDIN_FILENO;
+ const char** arguments = nullptr;
+
+ connection_manager::dump(fd);
+ PAN_Dumpsys(fd);
+ DumpsysHid(fd);
+ DumpsysBtaDm(fd);
+ bluetooth::shim::Dump(fd, arguments);
+}
diff --git a/system/test/headless/bt_stack_info.h b/system/test/headless/bt_stack_info.h
new file mode 100644
index 0000000..19afe0d
--- /dev/null
+++ b/system/test/headless/bt_stack_info.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <sys/types.h>
+
+class BtStackInfo {
+ public:
+ BtStackInfo();
+
+ void DumpsysLite();
+
+ pid_t MainPid() const { return main_pid_; }
+ pid_t JniPid() const { return jni_pid_; }
+
+ private:
+ pid_t main_pid_;
+ pid_t jni_pid_;
+};
diff --git a/system/test/headless/config.cc b/system/test/headless/config.cc
new file mode 100644
index 0000000..10cb1b0
--- /dev/null
+++ b/system/test/headless/config.cc
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "bt_config"
+
+#include "gd/hal/snoop_logger.h"
+#include "test/headless/log.h"
+
+using namespace bluetooth::hal;
+
+class Config {
+ Config(){};
+
+ void Help() const {
+ // setprop persist.bluetooth.btsnoopdefaultmode full
+ LOG_CONSOLE("Flag: %s", SnoopLogger::kBtSnoopLogPersists.c_str());
+ // setprop persist.bluetooth.btsnooplogpersists 1
+ }
+};
diff --git a/system/test/headless/connect/connect.cc b/system/test/headless/connect/connect.cc
index 06897ec..415501f 100644
--- a/system/test/headless/connect/connect.cc
+++ b/system/test/headless/connect/connect.cc
@@ -24,12 +24,12 @@
#include <cstdint>
#include <cstdio>
#include <future>
-#include <map>
#include <string>
#include "base/logging.h" // LOG() stdout and android log
#include "btif/include/stack_manager_t.h"
-#include "osi/include/log.h" // android log only
+#include "os/log.h" // android log only
+#include "stack/include/acl_api.h"
#include "stack/include/btm_api.h"
#include "stack/include/btm_api_types.h"
#include "stack/include/hci_error_code.h"
@@ -37,34 +37,18 @@
#include "test/headless/get_options.h"
#include "test/headless/headless.h"
#include "test/headless/interface.h"
+#include "test/headless/messenger.h"
#include "types/raw_address.h"
+using namespace bluetooth::test;
+using namespace std::chrono_literals;
+
const stack_manager_t* stack_manager_get_interface();
-void power_mode_callback([[maybe_unused]] const RawAddress& p_bda,
- [[maybe_unused]] tBTM_PM_STATUS status,
- [[maybe_unused]] uint16_t value,
- [[maybe_unused]] tHCI_STATUS hci_status) {
- fprintf(stdout, "Got callback\n");
-};
-
-namespace connect {
-std::promise<acl_state_changed_params_t> acl_state_changed_promise;
-
-} // namespace connect
-
-void callback_interface(callback_data_t* data) {
- if (data->Name() == "acl_state_changed") {
- LOG(INFO) << "Received acl state changed discovery";
- auto params = static_cast<acl_state_changed_params_t*>(data);
- acl_state_changed_params_t p(*params);
- connect::acl_state_changed_promise.set_value(p);
- }
- LOG(ERROR) << "Received unexpected interface callback";
-}
-
namespace {
+bool f_simulate_stack_crash = false;
+
int do_connect([[maybe_unused]] unsigned int num_loops,
[[maybe_unused]] const RawAddress& bd_addr,
[[maybe_unused]] std::list<std::string> options) {
@@ -80,49 +64,91 @@
}
ASSERT_LOG(disconnect_wait_time >= 0, "Time cannot go backwards");
- headless_add_callback("acl_state_changed", callback_interface);
+ headless::messenger::Context context{
+ .stop_watch = Stopwatch("Connect_timeout"),
+ .timeout = 3s,
+ .check_point = {},
+ .callbacks = {Callback::AclStateChanged},
+ };
- connect::acl_state_changed_promise =
- std::promise<acl_state_changed_params_t>();
- auto future = connect::acl_state_changed_promise.get_future();
-
- fprintf(stdout, "Creating connection to:%s\n", bd_addr.ToString().c_str());
+ LOG_CONSOLE("Creating connection to:%s", bd_addr.ToString().c_str());
LOG(INFO) << "Creating classic connection to " << bd_addr.ToString();
acl_create_classic_connection(bd_addr, false, false);
- auto result = future.get();
- LOG_CONSOLE("Connected created %s", result.ToString().c_str());
+ std::shared_ptr<callback_params_t> acl{nullptr};
+ while (context.stop_watch.LapMs() < 10000) {
+ // If we have received callback results within this timeframe...
+ if (headless::messenger::await_callback(context)) {
+ while (!context.callback_ready_q.empty()) {
+ std::shared_ptr<callback_params_t> p = context.callback_ready_q.front();
+ context.callback_ready_q.pop_front();
+ switch (p->CallbackType()) {
+ case Callback::AclStateChanged: {
+ acl = p;
+ } break;
+ default:
+ LOG_CONSOLE("WARN Received callback for unasked:%s",
+ p->Name().c_str());
+ break;
+ }
+ }
+ }
+ if (acl != nullptr) break;
+ }
- connect::acl_state_changed_promise =
- std::promise<acl_state_changed_params_t>();
- future = connect::acl_state_changed_promise.get_future();
+ if (acl != nullptr) {
+ LOG_CONSOLE("Acl state changed:%s", acl->ToString().c_str());
+ }
uint64_t connect = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
- fprintf(stdout, "Just crushing stack\n");
- LOG(INFO) << "Just crushing stack";
- bluetoothInterface.disable();
+ if (f_simulate_stack_crash) {
+ LOG_CONSOLE("Just crushing stack");
+ LOG(INFO) << "Just crushing stack";
+ bluetoothInterface.disable();
+ }
+ std::shared_ptr<callback_params_t> acl2{nullptr};
if (disconnect_wait_time == 0) {
- fprintf(stdout, "Waiting to disconnect from supervision timeout\n");
- auto result = future.get();
+ LOG_CONSOLE("Waiting to disconnect from supervision timeout\n");
+ while (context.stop_watch.LapMs() < 10000) {
+ // If we have received callback results within this timeframe...
+ if (headless::messenger::await_callback(context)) {
+ while (!context.callback_ready_q.empty()) {
+ std::shared_ptr<callback_params_t> p =
+ context.callback_ready_q.front();
+ context.callback_ready_q.pop_front();
+ switch (p->CallbackType()) {
+ case Callback::AclStateChanged: {
+ acl2 = p;
+ } break;
+ default:
+ LOG_CONSOLE("WARN Received callback for unasked:%s",
+ p->Name().c_str());
+ break;
+ }
+ }
+ }
+ if (acl2 != nullptr) break;
+ }
uint64_t disconnect =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
- LOG_CONSOLE("Disconnected after:%" PRId64 "ms from:%s result:%s[%u]\n",
+ LOG_CONSOLE("Disconnected after:%" PRId64 "ms from:%s acl:%s",
disconnect - connect, bd_addr.ToString().c_str(),
- bt_status_text(result.status).c_str(), result.status);
- headless_remove_callback("acl_state_changed", callback_interface);
- } else {
- fprintf(stdout, "Waiting %d seconds to just shutdown\n",
- disconnect_wait_time);
- bluetoothInterface.dump(1, nullptr);
- bluetoothInterface.cleanup();
+ acl->ToString().c_str());
}
+
+ acl_disconnect_from_handle(
+ ((acl_state_changed_params_t*)(acl2.get()))->acl_handle, HCI_SUCCESS,
+ "BT headless disconnect");
+
+ sleep(3);
+
return 0;
}
diff --git a/system/test/headless/discovery/discovery.cc b/system/test/headless/discovery/discovery.cc
index 7faf81c..a974267 100644
--- a/system/test/headless/discovery/discovery.cc
+++ b/system/test/headless/discovery/discovery.cc
@@ -22,7 +22,7 @@
#include "base/logging.h" // LOG() stdout and android log
#include "btif/include/btif_api.h"
-#include "osi/include/log.h" // android log only
+#include "os/log.h" // android log only
#include "stack/include/sdp_api.h"
#include "test/headless/bt_property.h"
#include "test/headless/get_options.h"
@@ -48,113 +48,7 @@
Stopwatch acl_stopwatch("ACL_connection");
Stopwatch sdp_stopwatch("SDP_discovery");
- LOG_CONSOLE("Started service discovery");
- auto check_point = messenger::sdp::get_check_point();
- ASSERT(bluetoothInterface.get_remote_services(&bd_addr, 0) ==
- BT_STATUS_SUCCESS);
-
- if (!messenger::acl::await_connected(8s)) {
- LOG_CONSOLE("TIMEOUT waiting for connection to %s",
- raw_address.ToString().c_str());
- return -1;
- }
- LOG_CONSOLE("ACL connected to %s :%sms", STR(raw_address),
- STR(acl_stopwatch));
-
- if (!messenger::sdp::await_service_discovery(8s, check_point, 1UL)) {
- LOG_CONSOLE("TIMEOUT waiting for service discovery to %s",
- raw_address.ToString().c_str());
- return -1;
- }
- auto callback_queue = messenger::sdp::collect_from(check_point);
- ASSERT_LOG(callback_queue.size() == 1,
- "Received unexpected number of SDP queries");
-
- auto params = callback_queue.front();
- callback_queue.pop_front();
-
- LOG_CONSOLE("got remote services :%s", params.ToString().c_str());
-
- for (int i = 0; i < params.num_properties; i++) {
- process_property(params.bd_addr, params.properties + i);
- }
-
- // Run a second fetch SDP
- {
- LOG_CONSOLE("Sending second SDP request");
- auto check_point = messenger::sdp::get_check_point();
-
- ASSERT(bluetoothInterface.get_remote_services(&bd_addr, 0) ==
- BT_STATUS_SUCCESS);
-
- if (!messenger::acl::await_connected(8s)) {
- LOG_CONSOLE("TIMEOUT waiting for connection to %s",
- raw_address.ToString().c_str());
- return -1;
- }
- LOG_CONSOLE("ACL connected to %s :%sms", STR(raw_address),
- STR(acl_stopwatch));
-
- if (!messenger::sdp::await_service_discovery(8s, check_point, 1UL)) {
- LOG_CONSOLE("TIMEOUT waiting for service discovery to %s",
- raw_address.ToString().c_str());
- return -1;
- }
- auto callback_queue = messenger::sdp::collect_from(check_point);
- ASSERT_LOG(callback_queue.size() == 1,
- "Received unexpected number of SDP queries");
-
- auto params = callback_queue.front();
- callback_queue.pop_front();
-
- LOG_CONSOLE("got remote services :%s", params.ToString().c_str());
-
- for (int i = 0; i < params.num_properties; i++) {
- process_property(params.bd_addr, params.properties + i);
- }
- }
-
- // Run a third fetch SDP
- {
- LOG_CONSOLE("Sending third SDP request");
- auto check_point = messenger::sdp::get_check_point();
-
- ASSERT(bluetoothInterface.get_remote_services(&bd_addr, 0) ==
- BT_STATUS_SUCCESS);
-
- if (!messenger::acl::await_connected(8s)) {
- LOG_CONSOLE("TIMEOUT waiting for connection to %s",
- raw_address.ToString().c_str());
- return -1;
- }
- LOG_CONSOLE("ACL connected to %s :%sms", STR(raw_address),
- STR(acl_stopwatch));
-
- if (!messenger::sdp::await_service_discovery(8s, check_point, 1UL)) {
- LOG_CONSOLE("TIMEOUT waiting for service discovery to %s",
- raw_address.ToString().c_str());
- return -1;
- }
- auto callback_queue = messenger::sdp::collect_from(check_point);
- ASSERT_LOG(callback_queue.size() == 1,
- "Received unexpected number of SDP queries");
-
- auto params = callback_queue.front();
- callback_queue.pop_front();
-
- LOG_CONSOLE("got remote services :%s", params.ToString().c_str());
-
- for (int i = 0; i < params.num_properties; i++) {
- process_property(params.bd_addr, params.properties + i);
- }
- }
-
- LOG_CONSOLE("Awaiting disconnect");
- if (!messenger::acl::await_disconnected(6s)) {
- LOG_CONSOLE("TIMEOUT waiting for disconnection to %s",
- raw_address.ToString().c_str());
- return -1;
- }
+ LOG_CONSOLE("Started service discovery %s", bd_addr.ToString().c_str());
LOG_CONSOLE("Dumpsys system");
bluetoothInterface.dump(2, nullptr);
diff --git a/system/test/headless/dumpsys/dumpsys.cc b/system/test/headless/dumpsys/dumpsys.cc
index 33737ec..0de639c 100644
--- a/system/test/headless/dumpsys/dumpsys.cc
+++ b/system/test/headless/dumpsys/dumpsys.cc
@@ -16,14 +16,15 @@
#define LOG_TAG "bt_headless_sdp"
+#include "test/headless/dumpsys/dumpsys.h"
+
#include <future>
-#include "base/logging.h" // LOG() stdout and android log
-#include "osi/include/log.h" // android log only
+#include "base/logging.h" // LOG() stdout and android log
+#include "os/log.h" // android log only
#include "stack/include/btm_api.h"
#include "stack/include/btm_api_types.h"
#include "stack/include/hci_error_code.h"
-#include "test/headless/dumpsys/dumpsys.h"
#include "test/headless/get_options.h"
#include "test/headless/headless.h"
#include "types/raw_address.h"
diff --git a/system/test/headless/headless.cc b/system/test/headless/headless.cc
index c6a3e7d..e364803 100644
--- a/system/test/headless/headless.cc
+++ b/system/test/headless/headless.cc
@@ -22,17 +22,21 @@
#include <iostream>
#include <map>
+#include <memory>
#include "base/logging.h" // LOG() stdout and android log
+#include "gd/os/log.h"
#include "include/check.h"
#include "include/hardware/bluetooth.h"
-#include "internal_include/bt_trace.h"
-#include "osi/include/log.h" // android log only
-#include "test/headless/get_options.h"
+#include "test/headless/bt_stack_info.h"
#include "test/headless/interface.h"
#include "test/headless/log.h"
+#include "test/headless/messenger.h"
#include "types/raw_address.h"
+//
+// Aggregate disparate variables from callback API into unified single structure
+//
extern bt_interface_t bluetoothInterface;
using namespace bluetooth::test::headless;
@@ -56,14 +60,13 @@
interface_api_callback_map_[interface_name].push_back(function);
}
-void headless_remove_callback(const std::string interface_name,
- callback_function_t function) {
+void headless_remove_callback(const std::string interface_name) {
if (interface_api_callback_map_.find(interface_name) ==
interface_api_callback_map_.end()) {
ASSERT_LOG(false, "No callbacks registered for interface:%s",
interface_name.c_str());
}
- interface_api_callback_map_[interface_name].remove(function);
+ interface_api_callback_map_.erase(interface_name);
}
std::mutex adapter_state_mutex_;
@@ -75,10 +78,21 @@
bt_state_ = state;
adapter_state_cv_.notify_all();
}
-void adapter_properties([[maybe_unused]] bt_status_t status,
- [[maybe_unused]] int num_properties,
- [[maybe_unused]] ::bt_property_t* properties) {
- LOG_INFO("%s", __func__);
+void adapter_properties(bt_status_t status, int num_properties,
+ ::bt_property_t* properties) {
+ const size_t num_callbacks = interface_api_callback_map_.size();
+ auto callback_list = interface_api_callback_map_.find(__func__);
+ if (callback_list != interface_api_callback_map_.end()) {
+ for (auto callback : callback_list->second) {
+ adapter_properties_params_t params(status, num_properties, properties);
+ (callback)(¶ms);
+ }
+ }
+ LOG_INFO(
+ "num_callbacks:%zu status:%s num_properties:%d "
+ "properties:%p",
+ num_callbacks, bt_status_text(status).c_str(), num_properties,
+ properties);
}
void remote_device_properties(bt_status_t status, RawAddress* bd_addr,
@@ -96,15 +110,25 @@
}
}
LOG_INFO(
- "%s num_callbacks:%zu status:%s device:%s num_properties:%d "
+ "num_callbacks:%zu status:%s device:%s num_properties:%d "
"properties:%p",
- __func__, num_callbacks, bt_status_text(status).c_str(), STR(*bd_addr),
+ num_callbacks, bt_status_text(status).c_str(), STR(*bd_addr),
num_properties, properties);
}
-void device_found([[maybe_unused]] int num_properties,
- [[maybe_unused]] ::bt_property_t* properties) {
- LOG_INFO("%s", __func__);
+// Aggregate disparate variables from callback API into unified single structure
+void device_found(int num_properties, ::bt_property_t* properties) {
+ [[maybe_unused]] const size_t num_callbacks =
+ interface_api_callback_map_.size();
+ auto callback_list = interface_api_callback_map_.find(__func__);
+ if (callback_list != interface_api_callback_map_.end()) {
+ for (auto callback : callback_list->second) {
+ device_found_params_t params(num_properties, properties);
+ (callback)(¶ms);
+ }
+ }
+ LOG_INFO("Device found callback: num_properties:%d properties:%p",
+ num_properties, properties);
}
void discovery_state_changed(bt_discovery_state_t state) {
@@ -284,6 +308,8 @@
while (bt_state_ != BT_STATE_ON) adapter_state_cv_.wait(lck);
LOG_INFO("%s HeadlessStack stack is operational", __func__);
+ bt_stack_info_ = std::make_unique<BtStackInfo>();
+
bluetooth::test::headless::start_messenger();
LOG_CONSOLE("%s Headless stack has started up successfully", kHeadlessIcon);
diff --git a/system/test/headless/headless.h b/system/test/headless/headless.h
index 78e7591..37ad7c9 100644
--- a/system/test/headless/headless.h
+++ b/system/test/headless/headless.h
@@ -22,8 +22,9 @@
#include "base/logging.h" // LOG() stdout and android log
#include "include/hardware/bluetooth.h"
+#include "test/headless/bt_stack_info.h"
#include "test/headless/get_options.h"
-#include "test/headless/messenger.h"
+#include "test/headless/log.h"
extern bt_interface_t bluetoothInterface;
@@ -35,17 +36,13 @@
using ExecutionUnit = std::function<T()>;
constexpr char kHeadlessInitialSentinel[] =
- " INITIAL HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS "
- "HEADLESS";
+ " INITIAL HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS";
constexpr char kHeadlessStartSentinel[] =
- " START HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS "
- "HEADLESS";
+ " START HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS";
constexpr char kHeadlessStopSentinel[] =
- " STOP HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS "
- "HEADLESS";
+ " STOP HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS";
constexpr char kHeadlessFinalSentinel[] =
- " FINAL HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS "
- "HEADLESS";
+ " FINAL HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS HEADLESS";
class HeadlessStack {
protected:
@@ -60,6 +57,7 @@
private:
const char** stack_init_flags_;
+ std::unique_ptr<BtStackInfo> bt_stack_info_;
};
class HeadlessRun : public HeadlessStack {
diff --git a/system/test/headless/interface.h b/system/test/headless/interface.h
index 370d861..8b4c9ef 100644
--- a/system/test/headless/interface.h
+++ b/system/test/headless/interface.h
@@ -1,38 +1,118 @@
-
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
#pragma once
#include <base/strings/stringprintf.h>
-#include <list>
-#include <map>
+#include <deque>
#include <string>
+#include "gd/os/log.h"
#include "include/hardware/bluetooth.h"
+#include "macros.h"
#include "test/headless/log.h"
+#include "test/headless/property.h"
+#include "test/headless/text.h"
#include "types/raw_address.h"
+enum class Callback {
+ AclStateChanged,
+ AdapterProperties,
+ DeviceFound,
+ DiscoveryStateChanged,
+ RemoteDeviceProperties,
+};
+
+inline std::string callback_text(const Callback& callback) {
+ switch (callback) {
+ CASE_RETURN_TEXT(Callback::AclStateChanged);
+ CASE_RETURN_TEXT(Callback::AdapterProperties);
+ CASE_RETURN_TEXT(Callback::DeviceFound);
+ CASE_RETURN_TEXT(Callback::DiscoveryStateChanged);
+ CASE_RETURN_TEXT(Callback::RemoteDeviceProperties);
+ }
+}
+
struct callback_data_t {
std::string Name() const { return std::string(name_); }
+ Callback CallbackType() const { return callback_type_; }
+
uint64_t TimestampInMs() const {
return static_cast<uint64_t>(timestamp_ms_);
}
+ virtual ~callback_data_t() = default;
+
+ virtual std::string ToString() const = 0;
protected:
- callback_data_t(const char* name)
- : name_(name), timestamp_ms_(GetTimestampMs()) {}
- virtual ~callback_data_t() = default;
+ callback_data_t(const char* name, Callback callback_type_)
+ : name_(name),
+ callback_type_(callback_type_),
+ timestamp_ms_(GetTimestampMs()) {}
private:
const char* name_;
+ const Callback callback_type_;
const long long timestamp_ms_;
};
struct callback_params_t : public callback_data_t {
+ virtual std::string ToString() const override {
+ return std::string("VIRTUAL");
+ }
+
protected:
- callback_params_t(const char* name) : callback_data_t(name) {}
+ callback_params_t(const char* name, Callback callback_type)
+ : callback_data_t(name, callback_type) {}
virtual ~callback_params_t() = default;
- virtual std::string ToString() const = 0;
+};
+
+// Specializes the callback parameter
+template <typename T>
+// std::shared_ptr<T> Cast(std::shared_ptr<callback_params_t> params) { return
+// std::shared_ptr<T>(static_cast<T*>(params.get()));}
+std::shared_ptr<T> Cast(std::shared_ptr<callback_params_t> params) {
+ return std::make_shared<T>(*(static_cast<T*>(params.get())));
+}
+
+struct callback_params_with_properties_t : public callback_params_t {
+ public:
+ std::deque<bluetooth::test::headless::bt_property_t*> properties() const {
+ return property_queue_;
+ }
+ size_t num_properties() const { return property_queue_.size(); }
+
+ protected:
+ callback_params_with_properties_t(const char* name, Callback callback_type,
+ int num_properties,
+ ::bt_property_t* properties)
+ : callback_params_t(name, callback_type) {
+ for (int i = 0; i < num_properties; i++) {
+ LOG_DEBUG("Processing property %d/%d %p type:%d val:%p", i,
+ num_properties, &properties[i], properties[i].type,
+ properties[i].val);
+ property_queue_.push_back(
+ bluetooth::test::headless::property_factory(properties[i]));
+ }
+ }
+ virtual ~callback_params_with_properties_t() = default;
+
+ private:
+ std::deque<bluetooth::test::headless::bt_property_t*> property_queue_;
};
struct acl_state_changed_params_t : public callback_params_t {
@@ -40,7 +120,7 @@
bt_acl_state_t state, int transport_link_type,
bt_hci_error_code_t hci_reason,
bt_conn_direction_t direction, uint16_t acl_handle)
- : callback_params_t("acl_state_changed"),
+ : callback_params_t("acl_state_changed", Callback::AclStateChanged),
status(status),
remote_bd_addr(remote_bd_addr),
state(state),
@@ -62,20 +142,22 @@
std::string ToString() const override {
return base::StringPrintf(
- "status:%s remote_bd_addr:%s state:%s transport:%s reason:%s "
- "direction:%d handle:%d",
+ "status:%s remote_bd_addr:%s state:%s transport:%s reason:%s"
+ " direction:%s handle:%hu",
bt_status_text(status).c_str(), remote_bd_addr.ToString().c_str(),
(state == BT_ACL_STATE_CONNECTED) ? "CONNECTED" : "DISCONNECTED",
bt_transport_text(static_cast<const tBT_TRANSPORT>(transport_link_type))
.c_str(),
bt_status_text(static_cast<const bt_status_t>(hci_reason)).c_str(),
- direction, acl_handle);
+ bt_conn_direction_text(direction).c_str(), acl_handle);
}
};
struct discovery_state_changed_params_t : public callback_params_t {
discovery_state_changed_params_t(bt_discovery_state_t state)
- : callback_params_t("discovery_state_changed"), state(state) {}
+ : callback_params_t("discovery_state_changed",
+ Callback::DiscoveryStateChanged),
+ state(state) {}
discovery_state_changed_params_t(
const discovery_state_changed_params_t& params) = default;
@@ -83,33 +165,64 @@
bt_discovery_state_t state;
std::string ToString() const override {
- return base::StringPrintf(
- "state:%s", (state == BT_DISCOVERY_STOPPED) ? "STOPPED" : "STARTED");
+ return base::StringPrintf("state:%s",
+ bt_discovery_state_text(state).c_str());
}
};
-struct remote_device_properties_params_t : public callback_params_t {
+struct adapter_properties_params_t : public callback_params_with_properties_t {
+ adapter_properties_params_t(bt_status_t status, int num_properties,
+ ::bt_property_t* properties)
+ : callback_params_with_properties_t("adapter_properties",
+ Callback::AdapterProperties,
+ num_properties, properties),
+ status(status) {}
+ adapter_properties_params_t(const adapter_properties_params_t& params) =
+ default;
+
+ virtual ~adapter_properties_params_t() {}
+ bt_status_t status;
+
+ std::string ToString() const override {
+ return base::StringPrintf("status:%s num_properties:%zu",
+ bt_status_text(status).c_str(), num_properties());
+ }
+};
+
+struct remote_device_properties_params_t
+ : public callback_params_with_properties_t {
remote_device_properties_params_t(bt_status_t status, RawAddress bd_addr,
int num_properties,
- bt_property_t* properties)
- : callback_params_t("remote_device_properties"),
+ ::bt_property_t* properties)
+ : callback_params_with_properties_t("remote_device_properties",
+ Callback::RemoteDeviceProperties,
+ num_properties, properties),
status(status),
- bd_addr(bd_addr),
- num_properties(num_properties),
- properties(properties) {}
+ bd_addr(bd_addr) {}
remote_device_properties_params_t(
const remote_device_properties_params_t& params) = default;
virtual ~remote_device_properties_params_t() {}
bt_status_t status;
RawAddress bd_addr;
- int num_properties;
- bt_property_t* properties;
+
std::string ToString() const override {
- return base::StringPrintf(
- "status:%s bd_addr:%s num_properties:%d properties:%p",
- bt_status_text(status).c_str(), bd_addr.ToString().c_str(),
- num_properties, properties);
+ return base::StringPrintf("status:%s bd_addr:%s num_properties:%zu",
+ bt_status_text(status).c_str(),
+ bd_addr.ToString().c_str(), num_properties());
+ }
+};
+
+struct device_found_params_t : public callback_params_with_properties_t {
+ device_found_params_t(int num_properties, ::bt_property_t* properties)
+ : callback_params_with_properties_t("device_found", Callback::DeviceFound,
+ num_properties, properties) {}
+
+ device_found_params_t(const device_found_params_t& params) = default;
+ virtual ~device_found_params_t() {}
+
+ std::string ToString() const override {
+ return base::StringPrintf("num_properties:%zu", num_properties());
}
};
@@ -117,5 +230,4 @@
void headless_add_callback(const std::string interface_name,
callback_function_t function);
-void headless_remove_callback(const std::string interface_name,
- callback_function_t function);
+void headless_remove_callback(const std::string interface_name);
diff --git a/system/test/headless/log.cc b/system/test/headless/log.cc
index f192e0d..6105a9a 100644
--- a/system/test/headless/log.cc
+++ b/system/test/headless/log.cc
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-#include "osi/include/log.h"
+#include "os/log.h"
#include <chrono>
#include <ctime>
diff --git a/system/test/headless/log.h b/system/test/headless/log.h
index 303e220..4fb439e 100644
--- a/system/test/headless/log.h
+++ b/system/test/headless/log.h
@@ -16,14 +16,11 @@
#pragma once
-#include <assert.h>
#include <log/log.h>
-#include <stdio.h>
#include <sys/syscall.h> /* Definition of SYS_* constants */
#include <unistd.h>
#include <chrono>
-#include <ctime>
#include <string>
#include "build_timestamp.h" // generated
diff --git a/system/test/headless/main.cc b/system/test/headless/main.cc
index f40ee53..e40bf85 100644
--- a/system/test/headless/main.cc
+++ b/system/test/headless/main.cc
@@ -26,13 +26,15 @@
#include <unordered_map>
#include "base/logging.h" // LOG() stdout and android log
-#include "osi/include/log.h" // android log only
+#include "os/log.h" // android log only
+#include "test/headless/adapter/adapter.h"
#include "test/headless/connect/connect.h"
#include "test/headless/discovery/discovery.h"
#include "test/headless/dumpsys/dumpsys.h"
#include "test/headless/get_options.h"
#include "test/headless/headless.h"
#include "test/headless/log.h"
+#include "test/headless/mode/mode.h"
#include "test/headless/nop/nop.h"
#include "test/headless/pairing/pairing.h"
#include "test/headless/read/read.h"
@@ -92,12 +94,17 @@
Main(const bluetooth::test::headless::GetOpt& options)
: HeadlessTest<int>(options) {
test_nodes_.emplace(
+ "adapter",
+ std::make_unique<bluetooth::test::headless::Adapter>(options));
+ test_nodes_.emplace(
"dumpsys",
std::make_unique<bluetooth::test::headless::Dumpsys>(options));
test_nodes_.emplace(
"connect",
std::make_unique<bluetooth::test::headless::Connect>(options));
test_nodes_.emplace(
+ "mode", std::make_unique<bluetooth::test::headless::Mode>(options));
+ test_nodes_.emplace(
"nop", std::make_unique<bluetooth::test::headless::Nop>(options));
test_nodes_.emplace(
"pairing",
diff --git a/system/test/headless/messenger.cc b/system/test/headless/messenger.cc
index 6231fb6..604196b 100644
--- a/system/test/headless/messenger.cc
+++ b/system/test/headless/messenger.cc
@@ -18,178 +18,125 @@
#include "test/headless/messenger.h"
-#include <future>
+#include <condition_variable>
+#include <deque>
+#include <memory>
+#include <mutex>
#include "base/logging.h" // LOG() stdout and android log
-#include "btif/include/btif_api.h"
-#include "osi/include/log.h" // android log only
-#include "stack/include/sdp_api.h"
-#include "test/headless/bt_property.h"
-#include "test/headless/get_options.h"
-#include "test/headless/headless.h"
#include "test/headless/interface.h"
#include "test/headless/log.h"
-#include "test/headless/sdp/sdp.h"
-#include "test/headless/stopwatch.h"
-#include "test/headless/timeout.h"
-#include "types/bluetooth/uuid.h"
-#include "types/raw_address.h"
using namespace bluetooth::test::headless;
using namespace std::chrono_literals;
template <typename T>
-struct messenger_t {
- std::mutex mutex;
- std::condition_variable cv;
- std::deque<T> params_queue;
- void Notify() { cv.notify_all(); }
+struct callback_queue_t {
+ callback_queue_t(const std::string name) : name_(name) {}
+ // Must be held with lock
+ size_t size() const { return callback_queue.size(); }
+
+ private:
+ const std::string name_;
+ std::deque<T> callback_queue;
+
+ public:
+ void Push(T elem) { callback_queue.push_back(elem); }
+ // Must be held with lock
+ T Pop() {
+ T p = callback_queue.front();
+ callback_queue.pop_front();
+ return p;
+ }
+ // Must be held with lock
+ bool empty() const { return callback_queue.empty(); }
};
-namespace {
-
-namespace acl {
-messenger_t<acl_state_changed_params_t> acl_state_changed_;
-
-void acl_state_changed_cb(callback_data_t* data) {
- auto params = static_cast<acl_state_changed_params_t*>(data);
-
- acl_state_changed_.params_queue.push_back(*params);
- acl_state_changed_.Notify();
-}
-
-bool await_event(const bt_acl_state_t& state, const Timeout& timeout) {
- std::unique_lock<std::mutex> lk(acl_state_changed_.mutex);
- if (!acl_state_changed_.params_queue.empty()) {
- auto params = acl_state_changed_.params_queue.back();
- if (params.state == state) return true;
+struct messenger_t {
+ mutable std::mutex mutex;
+ std::condition_variable cv;
+ callback_queue_t<std::shared_ptr<callback_params_t>> callback_queue =
+ callback_queue_t<std::shared_ptr<callback_params_t>>("callbacks");
+ void Push(std::shared_ptr<callback_params_t> elem) {
+ std::unique_lock<std::mutex> lk(mutex);
+ callback_queue.Push(elem);
+ cv.notify_all();
}
- return acl_state_changed_.cv.wait_for(lk, timeout, [=] {
- return !acl_state_changed_.params_queue.empty() &&
- acl_state_changed_.params_queue.back().state == state;
- });
-}
+};
-} // namespace acl
+namespace bluetooth {
+namespace test {
+namespace headless {
+namespace messenger {
-namespace sdp {
-messenger_t<remote_device_properties_params_t> remote_device_properties_;
+// Called by client to await any callback for the given callbacks
+messenger_t callback_data_;
-void remote_device_properties_cb(callback_data_t* data) {
- auto params = static_cast<remote_device_properties_params_t*>(data);
- // TODO Save timestamp into queue
- remote_device_properties_.params_queue.push_back(*params);
- remote_device_properties_.Notify();
-}
-
-bool await_event(const Timeout& timeout, const CheckPoint& check_point,
- const size_t count) {
- std::unique_lock<std::mutex> lk(remote_device_properties_.mutex);
- if (!remote_device_properties_.params_queue.empty()) {
- if (remote_device_properties_.params_queue.size() - check_point > count)
- return true;
+bool await_callback(Context& context) {
+ std::unique_lock<std::mutex> lk(callback_data_.mutex);
+ while (!callback_data_.callback_queue.empty()) {
+ std::shared_ptr<callback_params_t> cb = callback_data_.callback_queue.Pop();
+ if (std::find(context.callbacks.begin(), context.callbacks.end(),
+ cb->CallbackType()) != context.callbacks.end()) {
+ context.callback_ready_q.push_back(cb);
+ }
}
- return remote_device_properties_.cv.wait_for(lk, timeout, [=] {
- return !remote_device_properties_.params_queue.empty() &&
- remote_device_properties_.params_queue.size() - check_point >= count;
- });
+ if (context.callback_ready_q.size() == 0) {
+ callback_data_.cv.wait_for(lk, context.timeout);
+ }
+ return true;
}
-} // namespace sdp
-
-namespace inquiry {} // namespace inquiry
-
-} // namespace
+} // namespace messenger
+} // namespace headless
+} // namespace test
+} // namespace bluetooth
namespace bluetooth::test::headless {
-namespace messenger {
-namespace acl {
-
-bool await_connected(const Timeout& timeout) {
- return ::acl::await_event(BT_ACL_STATE_CONNECTED, timeout);
+void messenger_stats() {
+ // LOG_CONSOLE("%30s cnt:%zu", "device_found",
+ // discovered::device_found_.size()); LOG_CONSOLE("%30s cnt:%zu",
+ // "remote_device_properties",
+ // properties::remote_device_properties_.size());
}
-bool await_disconnected(const Timeout& timeout) {
- return ::acl::await_event(BT_ACL_STATE_DISCONNECTED, timeout);
-}
-
-} // namespace acl
-
-namespace sdp {
-
-bool await_service_discovery(const Timeout& timeout,
- const CheckPoint& check_point,
- const size_t count) {
- return ::sdp::await_event(timeout, check_point, count);
-}
-
-CheckPoint get_check_point() {
- std::unique_lock<std::mutex> lk(::sdp::remote_device_properties_.mutex);
- return ::sdp::remote_device_properties_.params_queue.size();
-}
-
-std::deque<remote_device_properties_params_t> collect_from(
- CheckPoint& check_point) {
- std::unique_lock<std::mutex> lk(::sdp::remote_device_properties_.mutex);
- ASSERT_LOG(
- !(check_point > ::sdp::remote_device_properties_.params_queue.size()),
- "Checkpoint larger than size");
- std::deque<remote_device_properties_params_t> deque;
- for (size_t size = check_point;
- size < ::sdp::remote_device_properties_.params_queue.size(); ++size) {
- deque.push_back(::sdp::remote_device_properties_.params_queue[size]);
- }
- return deque;
-}
-
-} // namespace sdp
-
-namespace inquiry {
-
-CheckPoint get_check_point() {
- std::unique_lock<std::mutex> lk(::sdp::remote_device_properties_.mutex);
- return ::sdp::remote_device_properties_.params_queue.size();
-}
-
-bool await_inquiry_result(const Timeout& timeout, const CheckPoint& check_point,
- const size_t count) {
- return ::sdp::await_event(timeout, check_point, count);
-}
-
-std::deque<remote_device_properties_params_t> collect_from(
- CheckPoint& check_point) {
- std::unique_lock<std::mutex> lk(::sdp::remote_device_properties_.mutex);
- ASSERT_LOG(
- !(check_point > ::sdp::remote_device_properties_.params_queue.size()),
- "Checkpoint larger than size");
- std::deque<remote_device_properties_params_t> deque;
- for (size_t size = check_point;
- size < ::sdp::remote_device_properties_.params_queue.size(); ++size) {
- deque.push_back(::sdp::remote_device_properties_.params_queue[size]);
- }
- check_point +=
- (::sdp::remote_device_properties_.params_queue.size() - check_point);
- return deque;
-}
-
-} // namespace inquiry
-} // namespace messenger
-
+// Callbacks that the messenger will handle from the bluetooth stack
void start_messenger() {
- headless_add_callback("acl_state_changed", ::acl::acl_state_changed_cb);
- headless_add_callback("remote_device_properties",
- ::sdp::remote_device_properties_cb);
-
+ headless_add_callback("acl_state_changed", [](callback_data_t* data) {
+ ASSERT_LOG(data != nullptr, "Received nullptr callback data:%s", __func__);
+ messenger::callback_data_.Push(std::make_shared<acl_state_changed_params_t>(
+ *(static_cast<acl_state_changed_params_t*>(data))));
+ });
+ headless_add_callback("adapter_properties", [](callback_data_t* data) {
+ ASSERT_LOG(data != nullptr, "Received nullptr callback data:%s", __func__);
+ messenger::callback_data_.Push(
+ std::make_shared<adapter_properties_params_t>(
+ *(static_cast<adapter_properties_params_t*>(data))));
+ });
+ headless_add_callback("device_found", [](callback_data_t* data) {
+ ASSERT_LOG(data != nullptr, "Received nullptr callback data:%s", __func__);
+ messenger::callback_data_.Push(std::make_shared<device_found_params_t>(
+ *(static_cast<device_found_params_t*>(data))));
+ });
+ headless_add_callback("remote_device_properties", [](callback_data_t* data) {
+ ASSERT_LOG(data != nullptr, "Received nullptr callback data:%s", __func__);
+ messenger::callback_data_.Push(
+ std::make_shared<remote_device_properties_params_t>(
+ *(static_cast<remote_device_properties_params_t*>(data))));
+ });
LOG_CONSOLE("Started messenger service");
}
void stop_messenger() {
- headless_remove_callback("acl_state_changed", ::acl::acl_state_changed_cb);
- headless_remove_callback("remote_device_properties",
- ::sdp::remote_device_properties_cb);
+ headless_remove_callback("remote_device_properties");
+ headless_remove_callback("device_found");
+ headless_remove_callback("adapter_properties");
+ headless_remove_callback("acl_state_changed");
LOG_CONSOLE("Stopped messenger service");
+
+ messenger_stats();
}
} // namespace bluetooth::test::headless
diff --git a/system/test/headless/messenger.h b/system/test/headless/messenger.h
index f8c08ad..6731312 100644
--- a/system/test/headless/messenger.h
+++ b/system/test/headless/messenger.h
@@ -1,11 +1,27 @@
-
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
#pragma once
#include <cstddef>
#include <deque>
+#include <string>
#include "test/headless/interface.h"
+#include "test/headless/stopwatch.h"
#include "test/headless/timeout.h"
namespace bluetooth::test::headless {
@@ -16,12 +32,18 @@
void stop_messenger();
namespace messenger {
-namespace acl {
-bool await_connected(const Timeout& timeout);
-bool await_disconnected(const Timeout& timeout);
+struct Context {
+ Stopwatch stop_watch;
+ Timeout timeout;
+ CheckPoint check_point;
+ bool SetCallbacks(const std::vector<std::string>& callbacks);
+ std::vector<Callback> callbacks;
+ std::deque<std::shared_ptr<callback_params_t>> callback_ready_q;
+};
-} // namespace acl
+// Called by client to await any callback for the given callbacks
+bool await_callback(Context& context);
namespace sdp {
@@ -32,17 +54,6 @@
CheckPoint& check_point);
} // namespace sdp
-
-namespace inquiry {
-
-CheckPoint get_check_point();
-bool await_inquiry_result(const Timeout& timeout, const CheckPoint& check_point,
- const size_t count);
-std::deque<remote_device_properties_params_t> collect_from(
- CheckPoint& check_point);
-
-} // namespace inquiry
-
} // namespace messenger
} // namespace bluetooth::test::headless
diff --git a/system/test/headless/mode/mode.cc b/system/test/headless/mode/mode.cc
new file mode 100644
index 0000000..207b711
--- /dev/null
+++ b/system/test/headless/mode/mode.cc
@@ -0,0 +1,153 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "bt_headless_mode"
+
+#include "test/headless/mode/mode.h"
+
+#include <deque>
+#include <future>
+#include <memory>
+
+#include "base/logging.h" // LOG() stdout and android log
+#include "btm_status.h"
+#include "hci_error_code.h"
+#include "include/macros.h"
+#include "stack/include/acl_api.h"
+#include "stack/include/l2cap_acl_interface.h"
+#include "test/headless/get_options.h"
+#include "test/headless/headless.h"
+#include "test/headless/messenger.h"
+#include "test/headless/utils/power_mode_client.h"
+#include "types/raw_address.h"
+
+using namespace bluetooth::test;
+using namespace std::chrono_literals;
+
+namespace {
+int do_mode([[maybe_unused]] unsigned int num_loops,
+ [[maybe_unused]] const RawAddress& bd_addr,
+ [[maybe_unused]] std::list<std::string> options) {
+ LOG_CONSOLE("Starting mode change test");
+ // Requires a BR_EDR connection to work
+
+ headless::messenger::Context context{
+ .stop_watch = Stopwatch("Connect_timeout"),
+ .timeout = 3s,
+ .check_point = {},
+ .callbacks = {Callback::AclStateChanged},
+ };
+
+ PowerMode power_mode;
+
+ acl_create_classic_connection(bd_addr, false, false);
+
+ std::shared_ptr<acl_state_changed_params_t> acl{nullptr};
+
+ while (context.stop_watch.LapMs() < 10000) {
+ // If we have received callback results within this timeframe...
+ if (headless::messenger::await_callback(context)) {
+ while (!context.callback_ready_q.empty()) {
+ std::shared_ptr<callback_params_t> p = context.callback_ready_q.front();
+ context.callback_ready_q.pop_front();
+ switch (p->CallbackType()) {
+ case Callback::AclStateChanged: {
+ acl = Cast<acl_state_changed_params_t>(p);
+ LOG_CONSOLE("Acl state changed:%s", acl->ToString().c_str());
+ } break;
+ default:
+ LOG_CONSOLE("WARN Received callback for unasked:%s",
+ p->Name().c_str());
+ break;
+ }
+ }
+ }
+ if (acl != nullptr) break;
+ }
+
+ if (acl->state == BT_ACL_STATE_DISCONNECTED) {
+ LOG_CONSOLE("Connection failed");
+ return 1;
+ }
+
+ LOG_CONSOLE("Connection completed");
+ PowerMode::Client client = power_mode.GetClient(bd_addr);
+
+ {
+ pwr_command_t pwr_command;
+ pwr_result_t result = client.set_typical_sniff(std::move(pwr_command));
+ LOG_CONSOLE("Sniff mode command sent");
+ if (result.btm_status == BTM_CMD_STARTED) {
+ // This awaits the command status callback
+ power_mode_callback_t cmd_status = result.cmd_status_future.get();
+ LOG_CONSOLE("Sniff mode command complete:%s",
+ cmd_status.ToString().c_str());
+ if (cmd_status.status == BTM_PM_STS_PENDING) {
+ LOG_CONSOLE("Sniff mode command accepted; awaiting mode change event");
+ power_mode_callback_t mode_event = result.mode_event_future.get();
+ LOG_CONSOLE("Sniff mode command complete:%s",
+ mode_event.ToString().c_str());
+ } else {
+ client.remove_mode_event_promise();
+ LOG_CONSOLE("Command failed; no mode change event forthcoming");
+ }
+ } else {
+ LOG_CONSOLE("Smiff mode command failed:%s",
+ btm_status_text(result.btm_status).c_str());
+ }
+ }
+
+ {
+ pwr_command_t pwr_command;
+ pwr_result_t result = client.set_active(std::move(pwr_command));
+ LOG_CONSOLE("Active mode command sent");
+ if (result.btm_status == BTM_CMD_STARTED) {
+ power_mode_callback_t cmd_status = result.cmd_status_future.get();
+ LOG_CONSOLE("Active mode command complete:%s",
+ cmd_status.ToString().c_str());
+ if (cmd_status.status == BTM_PM_STS_PENDING) {
+ LOG_CONSOLE("Active mode command accepted; awaiting mode change event");
+ power_mode_callback_t mode_event = result.mode_event_future.get();
+ LOG_CONSOLE("Active mode command complete:%s",
+ mode_event.ToString().c_str());
+ } else {
+ client.remove_mode_event_promise();
+ LOG_CONSOLE("Command failed; no mode change event forthcoming");
+ }
+ } else {
+ LOG_CONSOLE("Active mode command failed:%s",
+ btm_status_text(result.btm_status).c_str());
+ }
+ }
+
+ LOG_CONSOLE("Disconnecting");
+ acl_disconnect_from_handle(acl->acl_handle, HCI_SUCCESS,
+ "BT headless disconnect");
+ LOG_CONSOLE("Waiting to disconnect");
+
+ sleep(3);
+
+ return 0;
+}
+
+} // namespace
+ //
+int bluetooth::test::headless::Mode::Run() {
+ return RunOnHeadlessStack<int>([this]() {
+ return do_mode(options_.loop_, options_.device_.front(),
+ options_.non_options_);
+ });
+}
diff --git a/system/test/headless/mode/mode.h b/system/test/headless/mode/mode.h
new file mode 100644
index 0000000..b75042c
--- /dev/null
+++ b/system/test/headless/mode/mode.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include "test/headless/get_options.h"
+#include "test/headless/headless.h"
+
+namespace bluetooth {
+namespace test {
+namespace headless {
+
+class Mode : public HeadlessTest<int> {
+ public:
+ Mode(const bluetooth::test::headless::GetOpt& options)
+ : HeadlessTest<int>(options) {}
+ int Run() override;
+};
+
+} // namespace headless
+} // namespace test
+} // namespace bluetooth
diff --git a/system/test/headless/nop/nop.cc b/system/test/headless/nop/nop.cc
index f6ac42c..9b194ba 100644
--- a/system/test/headless/nop/nop.cc
+++ b/system/test/headless/nop/nop.cc
@@ -16,14 +16,15 @@
#define LOG_TAG "bt_headless_sdp"
+#include "test/headless/nop/nop.h"
+
#include <future>
-#include "base/logging.h" // LOG() stdout and android log
-#include "osi/include/log.h" // android log only
+#include "base/logging.h" // LOG() stdout and android log
+#include "os/log.h" // android log only
#include "stack/include/sdp_api.h"
#include "test/headless/get_options.h"
#include "test/headless/headless.h"
-#include "test/headless/nop/nop.h"
#include "types/raw_address.h"
int bluetooth::test::headless::Nop::Run() {
diff --git a/system/test/headless/pairing/pairing.cc b/system/test/headless/pairing/pairing.cc
index ed5c490..1f654ed 100644
--- a/system/test/headless/pairing/pairing.cc
+++ b/system/test/headless/pairing/pairing.cc
@@ -16,14 +16,12 @@
#define LOG_TAG "bt_headless_sdp"
-#include <future>
+#include "test/headless/pairing/pairing.h"
#include "base/logging.h" // LOG() stdout and android log
#include "btif/include/btif_api.h"
-#include "osi/include/log.h" // android log only
#include "test/headless/get_options.h"
#include "test/headless/headless.h"
-#include "test/headless/pairing/pairing.h"
#include "types/raw_address.h"
int bluetooth::test::headless::Pairing::Run() {
@@ -38,7 +36,7 @@
return -1;
}
- RawAddress raw_address = options_.device_.front();
+ [[maybe_unused]] RawAddress raw_address = options_.device_.front();
return RunOnHeadlessStack<int>([raw_address]() {
btif_dm_create_bond(raw_address, BT_TRANSPORT_BR_EDR);
diff --git a/system/test/headless/property.cc b/system/test/headless/property.cc
index b0a098a..ad5485a 100644
--- a/system/test/headless/property.cc
+++ b/system/test/headless/property.cc
@@ -14,18 +14,22 @@
* limitations under the License.
*/
+#define LOG_TAG "bt_property"
+
#include "test/headless/property.h"
#include <map>
+#include "gd/os/log.h"
#include "include/hardware/bluetooth.h"
+#include "test/headless/log.h"
using namespace bluetooth::test;
namespace {
// Map the bluetooth property names to the corresponding headless property
-// structure
+// structure factor
std::map<::bt_property_type_t, std::function<headless::bt_property_t*(
const uint8_t* data, const size_t len)>>
property_map = {
@@ -33,6 +37,10 @@
[](const uint8_t* data, const size_t len) -> headless::bt_property_t* {
return new headless::property::name_t(data, len);
}},
+ {BT_PROPERTY_BDADDR,
+ [](const uint8_t* data, const size_t len) -> headless::bt_property_t* {
+ return new headless::property::bdaddr_t(data, len);
+ }},
{BT_PROPERTY_UUIDS,
[](const uint8_t* data, const size_t len) -> headless::bt_property_t* {
return new headless::property::uuid_t(data, len);
@@ -45,6 +53,66 @@
[](const uint8_t* data, const size_t len) -> headless::bt_property_t* {
return new headless::property::type_of_device_t(data, len);
}},
+ {BT_PROPERTY_SERVICE_RECORD,
+ [](const uint8_t* data, const size_t len) -> headless::bt_property_t* {
+ return new headless::property::void_t(data, len,
+ BT_PROPERTY_SERVICE_RECORD);
+ }},
+ {BT_PROPERTY_ADAPTER_SCAN_MODE,
+ [](const uint8_t* data, const size_t len) -> headless::bt_property_t* {
+ return new headless::property::void_t(data, len,
+ BT_PROPERTY_ADAPTER_SCAN_MODE);
+ }},
+ {BT_PROPERTY_ADAPTER_BONDED_DEVICES,
+ [](const uint8_t* data, const size_t len) -> headless::bt_property_t* {
+ return new headless::property::void_t(
+ data, len, BT_PROPERTY_ADAPTER_BONDED_DEVICES);
+ }},
+ {BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT,
+ [](const uint8_t* data, const size_t len) -> headless::bt_property_t* {
+ return new headless::property::void_t(
+ data, len, BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT);
+ }},
+ {BT_PROPERTY_REMOTE_FRIENDLY_NAME,
+ [](const uint8_t* data, const size_t len) -> headless::bt_property_t* {
+ return new headless::property::void_t(
+ data, len, BT_PROPERTY_REMOTE_FRIENDLY_NAME);
+ }},
+ {BT_PROPERTY_REMOTE_RSSI,
+ [](const uint8_t* data, const size_t len) -> headless::bt_property_t* {
+ return new headless::property::void_t(data, len,
+ BT_PROPERTY_REMOTE_RSSI);
+ }},
+ {BT_PROPERTY_REMOTE_VERSION_INFO,
+ [](const uint8_t* data, const size_t len) -> headless::bt_property_t* {
+ return new headless::property::void_t(
+ data, len, BT_PROPERTY_REMOTE_VERSION_INFO);
+ }},
+ {BT_PROPERTY_LOCAL_LE_FEATURES,
+ [](const uint8_t* data, const size_t len) -> headless::bt_property_t* {
+ return new headless::property::void_t(data, len,
+ BT_PROPERTY_LOCAL_LE_FEATURES);
+ }},
+ {BT_PROPERTY_LOCAL_IO_CAPS,
+ [](const uint8_t* data, const size_t len) -> headless::bt_property_t* {
+ return new headless::property::void_t(data, len,
+ BT_PROPERTY_LOCAL_IO_CAPS);
+ }},
+ {BT_PROPERTY_DYNAMIC_AUDIO_BUFFER,
+ [](const uint8_t* data, const size_t len) -> headless::bt_property_t* {
+ return new headless::property::void_t(
+ data, len, BT_PROPERTY_DYNAMIC_AUDIO_BUFFER);
+ }},
+ {BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER,
+ [](const uint8_t* data, const size_t len) -> headless::bt_property_t* {
+ return new headless::property::void_t(
+ data, len, BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER);
+ }},
+ {BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP,
+ [](const uint8_t* data, const size_t len) -> headless::bt_property_t* {
+ return new headless::property::void_t(
+ data, len, BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP);
+ }},
};
} // namespace
@@ -52,12 +120,13 @@
// Caller owns the memory
headless::bt_property_t* bluetooth::test::headless::property_factory(
const ::bt_property_t& bt_property) {
- ASSERT_LOG(bt_property.len > -1, "Property count is less than zero");
- ASSERT_LOG(bt_property.val != nullptr, "Property data value is null");
-
const uint8_t* data = static_cast<uint8_t*>(bt_property.val);
const size_t size = static_cast<size_t>(bt_property.len);
+ if (size > 0) {
+ ASSERT_LOG(data != nullptr, "Property value pointer is null");
+ }
+
const auto factory = property_map.find(bt_property.type);
if (factory != property_map.end()) {
return factory->second(data, size);
diff --git a/system/test/headless/property.h b/system/test/headless/property.h
index bbc6d5a..35d2f73 100644
--- a/system/test/headless/property.h
+++ b/system/test/headless/property.h
@@ -20,21 +20,64 @@
#include <cstdint>
#include <deque>
#include <memory>
+#include <sstream>
#include <string>
#include "include/hardware/bluetooth.h"
+#include "macros.h"
#include "test/headless/log.h"
#include "types/bluetooth/uuid.h"
+inline std::string bt_property_type_text(const ::bt_property_type_t type) {
+ switch (type) {
+ CASE_RETURN_TEXT(BT_PROPERTY_BDNAME);
+ CASE_RETURN_TEXT(BT_PROPERTY_BDADDR);
+ CASE_RETURN_TEXT(BT_PROPERTY_UUIDS);
+ CASE_RETURN_TEXT(BT_PROPERTY_CLASS_OF_DEVICE);
+ CASE_RETURN_TEXT(BT_PROPERTY_TYPE_OF_DEVICE);
+ CASE_RETURN_TEXT(BT_PROPERTY_SERVICE_RECORD);
+ CASE_RETURN_TEXT(BT_PROPERTY_ADAPTER_SCAN_MODE);
+ CASE_RETURN_TEXT(BT_PROPERTY_ADAPTER_BONDED_DEVICES);
+ CASE_RETURN_TEXT(BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT);
+ CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_FRIENDLY_NAME);
+ CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_RSSI);
+ CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_VERSION_INFO);
+ CASE_RETURN_TEXT(BT_PROPERTY_LOCAL_LE_FEATURES);
+ CASE_RETURN_TEXT(BT_PROPERTY_LOCAL_IO_CAPS);
+ CASE_RETURN_TEXT(BT_PROPERTY_RESERVED_0F);
+ CASE_RETURN_TEXT(BT_PROPERTY_DYNAMIC_AUDIO_BUFFER);
+ CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_IS_COORDINATED_SET_MEMBER);
+ CASE_RETURN_TEXT(BT_PROPERTY_APPEARANCE);
+ CASE_RETURN_TEXT(BT_PROPERTY_VENDOR_PRODUCT_INFO);
+ CASE_RETURN_TEXT(BT_PROPERTY_WL_MEDIA_PLAYERS_LIST);
+ CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_ASHA_CAPABILITY);
+ CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_ASHA_TRUNCATED_HISYNCID);
+ CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_MODEL_NUM);
+ CASE_RETURN_TEXT(BT_PROPERTY_REMOTE_DEVICE_TIMESTAMP);
+ default:
+ return base::StringPrintf("UNKNOWN[%d]", type);
+ }
+}
+
namespace bluetooth {
namespace test {
namespace headless {
struct bt_property_t {
- int Type() const { return type; }
+ ::bt_property_type_t Type() const { return type; }
virtual std::string ToString() const = 0;
+ // TODO verify this prints as expected
+ std::string ToRaw() {
+ std::ostringstream oss;
+ const uint8_t* p = data.get();
+ for (size_t i = 0; i < sizeof(bt_property_t); i++, p++) {
+ oss << "0x" << std::hex << *p << " ";
+ }
+ return oss.str();
+ }
+
protected:
bt_property_t(const uint8_t* data, const size_t len) {
this->len = len;
@@ -45,7 +88,7 @@
std::unique_ptr<uint8_t[]> data;
size_t len;
- int type;
+ ::bt_property_type_t type;
};
namespace property {
@@ -53,12 +96,13 @@
struct void_t : public bt_property_t {
void_t(const uint8_t* data, const size_t len, int type)
: bt_property_t(data, len) {
- this->type = type;
+ this->type = (::bt_property_type_t)type;
}
public:
virtual std::string ToString() const override {
- return base::StringPrintf("void property type:%d", type);
+ return base::StringPrintf("Unimplemented property type:%d name:%s", type,
+ bt_property_type_text(type).c_str());
}
};
@@ -100,6 +144,24 @@
}
};
+struct bdaddr_t : public bt_property_t {
+ bdaddr_t(const uint8_t* data, const size_t len) : bt_property_t(data, len) {
+ type = BT_PROPERTY_BDNAME;
+ }
+
+ RawAddress get_addr() const {
+ uint8_t* s = reinterpret_cast<uint8_t*>(data.get());
+ // TODO This may need to be reversed
+ RawAddress bd_addr;
+ ASSERT_LOG(6U == bd_addr.FromOctets(s), "Mac address is not 6 bytes");
+ return bd_addr;
+ }
+
+ virtual std::string ToString() const override {
+ return base::StringPrintf("bd_addr:%s", get_addr().ToString().c_str());
+ }
+};
+
struct class_of_device_t : public bt_property_t {
class_of_device_t(const uint8_t* data, const size_t len)
: bt_property_t(data, len) {
diff --git a/system/test/headless/pushme.sh b/system/test/headless/pushme.sh
new file mode 100755
index 0000000..9aa2476
--- /dev/null
+++ b/system/test/headless/pushme.sh
@@ -0,0 +1,19 @@
+#!/bin/bash
+
+## Cuttlefish 64 bit bt_headless installation
+PRODUCT=vsoc_x86_64
+
+## Ensure that the device storage has been remounted
+adb root
+adb remount -R
+adb wait-for-device
+
+## Push various shared libraries where the executable expects to find them
+adb push ${ANDROID_BUILD_TOP}/out/target/product/${PRODUCT}/symbols/system/bin/bt_headless /system/bin/bt_headless
+adb push ${ANDROID_BUILD_TOP}/out/target/product/${PRODUCT}/symbols/system/lib64/android.hardware.bluetooth.audio@2.0.so /system/lib64/android.hardware.bluetooth.audio@2.0.so
+adb push ${ANDROID_BUILD_TOP}/out/target/product/${PRODUCT}/symbols/system/lib64/android.hardware.bluetooth.audio@2.1.so /system/lib64/android.hardware.bluetooth.audio@2.1.so
+adb push ${ANDROID_BUILD_TOP}/out/target/product/${PRODUCT}/symbols/system/lib64/android.hardware.bluetooth@1.0.so /system/lib64/android.hardware.bluetooth@1.0.so
+adb push ${ANDROID_BUILD_TOP}/out/target/product/${PRODUCT}/symbols/system/lib64/android.hardware.bluetooth@1.1.so /system/lib64/android.hardware.bluetooth@1.1.so
+adb push ${ANDROID_BUILD_TOP}/out/target/product/${PRODUCT}/symbols/system/lib64/android.hardware.bluetooth.audio-V4-ndk.so /system/lib64/android.hardware.bluetooth.audio-V4-ndk.so
+adb push ${ANDROID_BUILD_TOP}/out/target/product/${PRODUCT}/symbols/system/lib64/android.hardware.audio.common-V3-ndk.so /system/lib64/android.hardware.audio.common-V3-ndk.so
+adb push ${ANDROID_BUILD_TOP}/out/target/product/${PRODUCT}/symbols/system/lib64/android.media.audio.common.types-V3-ndk.so /system/lib64/android.media.audio.common.types-V3-ndk.so
diff --git a/system/test/headless/read/name.cc b/system/test/headless/read/name.cc
index 5666d88..f7f49be 100644
--- a/system/test/headless/read/name.cc
+++ b/system/test/headless/read/name.cc
@@ -16,15 +16,16 @@
#define LOG_TAG "bt_headless_sdp"
+#include "test/headless/read/name.h"
+
#include <future>
-#include "base/logging.h" // LOG() stdout and android log
-#include "osi/include/log.h" // android log only
+#include "base/logging.h" // LOG() stdout and android log
+#include "os/log.h" // android log only
#include "stack/include/btm_api.h"
#include "stack/include/btm_api_types.h"
#include "test/headless/get_options.h"
#include "test/headless/headless.h"
-#include "test/headless/read/name.h"
#include "types/raw_address.h"
std::promise<tBTM_REMOTE_DEV_NAME> promise_;
diff --git a/system/test/headless/read/read.cc b/system/test/headless/read/read.cc
index d1a3b8d..f01f8aa 100644
--- a/system/test/headless/read/read.cc
+++ b/system/test/headless/read/read.cc
@@ -17,8 +17,9 @@
#define LOG_TAG "bt_headless"
#include "test/headless/read/read.h"
-#include "base/logging.h" // LOG() stdout and android log
-#include "osi/include/log.h" // android log only
+
+#include "base/logging.h" // LOG() stdout and android log
+#include "os/log.h" // android log only
#include "test/headless/get_options.h"
#include "test/headless/headless.h"
#include "test/headless/read/name.h"
diff --git a/system/test/headless/scan/scan.cc b/system/test/headless/scan/scan.cc
index 0c9e14f..4cc674a 100644
--- a/system/test/headless/scan/scan.cc
+++ b/system/test/headless/scan/scan.cc
@@ -18,74 +18,61 @@
#include "test/headless/scan/scan.h"
-#include <future>
-
#include "base/logging.h" // LOG() stdout and android log
-#include "btif/include/btif_api.h"
-#include "osi/include/log.h" // android log only
-#include "stack/include/sdp_api.h"
-#include "test/headless/bt_property.h"
+#include "os/log.h"
#include "test/headless/get_options.h"
#include "test/headless/headless.h"
#include "test/headless/interface.h"
#include "test/headless/log.h"
+#include "test/headless/messenger.h"
+#include "test/headless/property.h"
#include "test/headless/stopwatch.h"
-#include "types/bluetooth/uuid.h"
-#include "types/raw_address.h"
-using namespace bluetooth::test::headless;
+using namespace bluetooth::test;
using namespace std::chrono_literals;
-namespace scan {
-std::promise<acl_state_changed_params_t> acl_state_changed_promise;
-std::promise<remote_device_properties_params_t>
- remote_device_properties_promise;
-
-std::mutex mutex;
-std::condition_variable cv;
-
-std::queue<acl_state_changed_params_t> acl_state_changed_params_queue;
-std::queue<discovery_state_changed_params_t>
- discovery_state_changed_params_queue;
-;
-
-// Callback from another thread
-void callback_interface(callback_data_t* data) {
- if (data->Name() == "discovery_state_changed") {
- LOG(INFO) << "Received discovery_state_changed";
- auto params = static_cast<discovery_state_changed_params_t*>(data);
- discovery_state_changed_params_queue.push(*params);
- LOG_CONSOLE("Received discovery state change callback %s",
- params->ToString().c_str());
- cv.notify_all();
- return;
- }
- LOG(ERROR) << "Received unexpected interface callback";
-}
-
-} // namespace scan
-
namespace {
int start_scan([[maybe_unused]] unsigned int num_loops) {
LOG(INFO) << "Started Device Scan";
- Stopwatch stop_watch("Inquiry_timeout");
- auto check_point = messenger::inquiry::get_check_point();
-
ASSERT(bluetoothInterface.start_discovery() == BT_STATUS_SUCCESS);
LOG_CONSOLE("Started inquiry - device discovery");
- while (stop_watch.LapMs() < 10000) {
- if (messenger::inquiry::await_inquiry_result(1s, check_point, 1)) {
- auto callback_queue = messenger::inquiry::collect_from(check_point);
- while (!callback_queue.empty()) {
- remote_device_properties_params_t params = callback_queue.front();
- callback_queue.pop_front();
- LOG_CONSOLE("Received remote inquiry :%s", STR(params));
- bt_property_t* prop = params.properties;
- for (int i = 0; i < params.num_properties; ++i, prop++) {
- process_property(params.bd_addr, prop);
+ headless::messenger::Context context{
+ .stop_watch = Stopwatch("Inquiry_timeout"),
+ .timeout = 1s,
+ .check_point = {},
+ .callbacks = {Callback::RemoteDeviceProperties, Callback::DeviceFound},
+ };
+
+ while (context.stop_watch.LapMs() < 10000) {
+ // If we have received callback results within this timeframe...
+ if (headless::messenger::await_callback(context)) {
+ while (!context.callback_ready_q.empty()) {
+ std::shared_ptr<callback_params_t> p = context.callback_ready_q.front();
+ context.callback_ready_q.pop_front();
+ switch (p->CallbackType()) {
+ case Callback::RemoteDeviceProperties: {
+ remote_device_properties_params_t* q =
+ static_cast<remote_device_properties_params_t*>(p.get());
+ for (const auto& p2 : q->properties()) {
+ LOG_CONSOLE(" %s prop:%s", p->Name().c_str(),
+ p2->ToString().c_str());
+ }
+ } break;
+ case Callback::DeviceFound: {
+ device_found_params_t* q =
+ static_cast<device_found_params_t*>(p.get());
+ for (const auto& p2 : q->properties()) {
+ LOG_CONSOLE(" %s prop:%s", p->Name().c_str(),
+ p2->ToString().c_str());
+ }
+ } break;
+ default:
+ LOG_CONSOLE("WARN Received callback for unasked:%s",
+ p->Name().c_str());
+ break;
}
}
}
diff --git a/system/test/headless/sdp/sdp.cc b/system/test/headless/sdp/sdp.cc
index 6750f5a..b975672 100644
--- a/system/test/headless/sdp/sdp.cc
+++ b/system/test/headless/sdp/sdp.cc
@@ -21,7 +21,9 @@
#include <future>
#include "base/logging.h" // LOG() stdout and android log
-#include "osi/include/log.h" // android log only
+#include "bta/dm/bta_dm_int.h"
+#include "bta/include/bta_api.h"
+#include "os/log.h"
#include "osi/include/osi.h" // UNUSED_ATTR
#include "stack/include/sdp_api.h"
#include "test/headless/get_options.h"
@@ -43,60 +45,23 @@
namespace {
-struct sdp_error_code_s {
- const char* name;
- uint16_t error_code;
-} sdp_error_code[] = {
- {"KsdpSuccess", 0},
- {"KsdpInvalidVersion", 0x0001},
- {"KsdpInvalidServRecHdl", 0x0002},
- {"KsdpInvalidReqSyntax", 0x0003},
- {"KsdpInvalidPduSize", 0x0004},
- {"KsdpInvalidContState", 0x0005},
- {"KsdpNoResources", 0x0006},
- {"KsdpDiRegFailed", 0x0007},
- {"KsdpDiDiscFailed", 0x0008},
- {"KsdpNoDiRecordFound", 0x0009},
- {"KsdpErrAttrNotPresent", 0x000a},
- {"KsdpIllegalParameter", 0x000b},
- {"KsdpNoRecsMatch", 0xFFF0},
- {"KsdpConnFailed", 0xFFF1},
- {"KsdpCfgFailed", 0xFFF2},
- {"KsdpGenericError", 0xFFF3},
- {"KsdpDbFull", 0xFFF4},
- {"KsdpInvalidPdu", 0xFFF5},
- {"KsdpSecurityErr", 0xFFF6},
- {"KsdpConnRejected", 0xFFF7},
- {"KsdpCancel", 0xFFF8},
-};
-
-const char* kUnknownText = "Unknown";
-
-const char* SdpErrorCodeToString(uint16_t code) {
- for (size_t i = 0; i < sizeof(sdp_error_code) / sizeof(sdp_error_code_s);
- ++i) {
- if (sdp_error_code[i].error_code == code) {
- return sdp_error_code[i].name;
- }
- }
- return kUnknownText;
-}
-
-constexpr size_t kMaxDiscoveryRecords = 64;
+constexpr size_t kMaxDiscoveryRecords = 1024;
int sdp_query_uuid([[maybe_unused]] unsigned int num_loops,
- const RawAddress& raw_address, const bluetooth::Uuid& uuid) {
+ [[maybe_unused]] const RawAddress& raw_address,
+ [[maybe_unused]] const bluetooth::Uuid& uuid) {
SdpDb sdp_discovery_db(kMaxDiscoveryRecords);
if (!get_legacy_stack_sdp_api()->service.SDP_InitDiscoveryDb(
sdp_discovery_db.RawPointer(), sdp_discovery_db.Length(),
1, // num_uuid,
&uuid, 0, nullptr)) {
- fprintf(stdout, "%s Unable to initialize sdp discovery\n", __func__);
+ LOG_CONSOLE("Unable to initialize sdp discovery");
return -1;
}
+ LOG_CONSOLE("Initialized sdp discovery database");
- std::promise<uint16_t> promise;
+ std::promise<tSDP_STATUS> promise;
auto future = promise.get_future();
sdp_discovery_db.Print(stdout);
@@ -107,24 +72,26 @@
fprintf(stdout, "%s Failed to start search attribute request\n", __func__);
return -2;
}
+ LOG_CONSOLE("Started service search for uuid:%s", uuid.ToString().c_str());
- uint16_t result = future.get();
- if (result != 0) {
+ const tSDP_STATUS result = future.get();
+ if (result != SDP_SUCCESS) {
fprintf(stdout, "Failed search discovery result:%s\n",
- SdpErrorCodeToString(result));
+ sdp_status_text(result).c_str());
return result;
}
- tSDP_DISC_REC* rec = get_legacy_stack_sdp_api()->db.SDP_FindServiceInDb(
- sdp_discovery_db.RawPointer(), uuid.As16Bit(), nullptr);
- if (rec == nullptr) {
- fprintf(stdout, "discovery record is null from:%s uuid:%s\n",
- raw_address.ToString().c_str(), uuid.ToString().c_str());
- } else {
- fprintf(stdout, "result:%d attr_id:%x from:%s uuid:%s\n", result,
- rec->p_first_attr->attr_id, rec->remote_bd_addr.ToString().c_str(),
- uuid.ToString().c_str());
+ LOG_CONSOLE("Found records peer:%s uuid:%s", raw_address.ToString().c_str(),
+ uuid.ToString().c_str());
+ for (unsigned i = 0; i < BTA_MAX_SERVICE_ID; i++) {
+ uint16_t uuid_as16Bit = bta_service_id_to_uuid_lkup_tbl[i];
+ tSDP_DISC_REC* rec = SDP_FindServiceInDb(sdp_discovery_db.RawPointer(),
+ uuid_as16Bit, nullptr);
+ if (rec != nullptr) {
+ LOG_CONSOLE(" uuid:0x%x", uuid_as16Bit);
+ }
}
+
return 0;
}
diff --git a/system/test/headless/sdp/sdp_db.cc b/system/test/headless/sdp/sdp_db.cc
index 023861b..d275b88 100644
--- a/system/test/headless/sdp/sdp_db.cc
+++ b/system/test/headless/sdp/sdp_db.cc
@@ -17,11 +17,10 @@
#define LOG_TAG "bt_headless"
#include "test/headless/sdp/sdp_db.h"
-#include "base/logging.h" // LOG() stdout and android log
-#include "osi/include/log.h" // android log only
+
+#include "base/logging.h" // LOG() stdout and android log
#include "stack/include/sdp_api.h"
#include "types/bluetooth/uuid.h"
-#include "types/raw_address.h"
using namespace bluetooth::test::headless;
diff --git a/system/test/headless/text.cc b/system/test/headless/text.cc
new file mode 100644
index 0000000..5a013ce
--- /dev/null
+++ b/system/test/headless/text.cc
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "test/headless/text.h"
+
+#include <string>
+
+#include "include/hardware/bluetooth.h"
+#include "macros.h"
+#include "os/log.h"
+
+std::string bt_conn_direction_text(const bt_conn_direction_t& direction) {
+ switch (direction) {
+ CASE_RETURN_TEXT(BT_CONN_DIRECTION_UNKNOWN);
+ CASE_RETURN_TEXT(BT_CONN_DIRECTION_OUTGOING);
+ CASE_RETURN_TEXT(BT_CONN_DIRECTION_INCOMING);
+ default:
+ ASSERT_LOG(false, "Illegal bt_conn_direction:%d", direction);
+ }
+}
+
+std::string bt_discovery_state_text(const bt_discovery_state_t& state) {
+ switch (state) {
+ CASE_RETURN_TEXT(BT_DISCOVERY_STOPPED);
+ CASE_RETURN_TEXT(BT_DISCOVERY_STARTED);
+ default:
+ ASSERT_LOG(false, "Illegal bt_discovery state:%d", state);
+ }
+}
diff --git a/system/test/headless/text.h b/system/test/headless/text.h
new file mode 100644
index 0000000..dac565d
--- /dev/null
+++ b/system/test/headless/text.h
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <string>
+
+#include "include/hardware/bluetooth.h"
+
+std::string bt_conn_direction_text(const bt_conn_direction_t& direction);
+std::string bt_discovery_state_text(const bt_discovery_state_t& state);
diff --git a/system/test/headless/util.cc b/system/test/headless/util.cc
index d1231ca..df3a15f 100644
--- a/system/test/headless/util.cc
+++ b/system/test/headless/util.cc
@@ -16,6 +16,7 @@
#include <string>
+#include "include/hardware/bluetooth.h"
#include "osi/include/properties.h"
bool is_android_running() {
diff --git a/system/test/headless/utils/power_mode_client.h b/system/test/headless/utils/power_mode_client.h
new file mode 100644
index 0000000..e35d455
--- /dev/null
+++ b/system/test/headless/utils/power_mode_client.h
@@ -0,0 +1,213 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#define LOG_TAG "bt_headless_mode"
+
+#include <base/strings/stringprintf.h>
+
+#include <future>
+#include <mutex>
+
+#include "base/logging.h" // LOG() stdout and android log
+#include "bta/dm/bta_dm_int.h"
+#include "stack/include/btm_client_interface.h"
+#include "stack/include/btm_status.h"
+#include "stack/include/hci_error_code.h"
+#include "types/raw_address.h"
+
+using namespace std::chrono_literals;
+
+namespace {
+const tBTM_PM_PWR_MD default_mandatory_sniff_mode = {
+ .max = 0x0006,
+ .min = 0x0006,
+ .attempt = 0x0020,
+ .timeout = 0x7fff,
+ .mode = BTM_PM_MD_SNIFF,
+};
+
+const tBTM_PM_PWR_MD typical_sniff_mode = {
+ .max = 800, // 5 seconds
+ .min = 400, // 2.5 seconds
+ .attempt = 4,
+ .timeout = 1,
+ .mode = BTM_PM_MD_SNIFF,
+};
+
+const tBTM_PM_PWR_MD default_active_mode = {
+ .max = 0, // Unused
+ .min = 0, // Unused
+ .attempt = 0, // Unused
+ .timeout = 0, // Unused
+ .mode = BTM_PM_MD_ACTIVE,
+};
+} // namespace
+
+// tBTM_PM_STATUS_CBACK
+struct power_mode_callback_t {
+ const RawAddress bd_addr;
+ tBTM_PM_STATUS status;
+ uint16_t value;
+ tHCI_STATUS hci_status;
+
+ std::string ToString() const {
+ return base::StringPrintf("bd_addr:%s pm_status:%s value:%hu hci_status:%s",
+ bd_addr.ToString().c_str(),
+ power_mode_status_text(status).c_str(), value,
+ hci_status_code_text(hci_status).c_str());
+ }
+};
+
+struct pwr_command_t {
+ std::promise<power_mode_callback_t> cmd_status_promise;
+ std::promise<power_mode_callback_t> mode_event_promise;
+};
+
+struct pwr_result_t {
+ tBTM_STATUS btm_status;
+ std::future<power_mode_callback_t> cmd_status_future;
+ std::future<power_mode_callback_t> mode_event_future;
+};
+
+namespace {
+
+class Queue {
+ public:
+ void CallbackReceived(const power_mode_callback_t& data) {
+ LOG_INFO("Power mode callback cnt:%zu data:%s", cnt++,
+ data.ToString().c_str());
+ std::unique_lock<std::mutex> lk(mutex);
+ if (promises_map_[data.bd_addr].empty()) {
+ LOG_INFO("Received unsolicited power mode callback: %s",
+ data.ToString().c_str());
+ return;
+ }
+ promises_map_[data.bd_addr].front().set_value(data);
+ promises_map_[data.bd_addr].pop_front();
+ }
+
+ void CommandSent(const RawAddress& bd_addr, pwr_command_t&& pwr_command) {
+ std::unique_lock<std::mutex> lk(mutex);
+ promises_map_[bd_addr].push_back(std::move(pwr_command.cmd_status_promise));
+ promises_map_[bd_addr].push_back(std::move(pwr_command.mode_event_promise));
+ }
+
+ void PopFront(const RawAddress& bd_addr) {
+ std::unique_lock<std::mutex> lk(mutex);
+ ASSERT_LOG(!promises_map_[bd_addr].empty(),
+ "Unable to remove promise from empty bag of promises");
+ promises_map_[bd_addr].pop_front();
+ }
+
+ private:
+ mutable std::mutex mutex;
+ std::unordered_map<RawAddress,
+ std::deque<std::promise<power_mode_callback_t>>>
+ promises_map_;
+ size_t cnt = 0;
+
+} queue_;
+
+} // namespace
+
+class PowerMode {
+ public:
+ class Client {
+ public:
+ Client(const uint8_t pm_id, const RawAddress& bd_addr)
+ : pm_id_(pm_id), bd_addr_(bd_addr) {}
+
+ // Used when the power mode command status is unsuccessful
+ // to prevent waiting for a mode event that will never arrive.
+ // Exposed to allow testing of these conditions.
+ void remove_mode_event_promise() { queue_.PopFront(bd_addr_); }
+
+ pwr_result_t set_sniff(pwr_command_t&& pwr_command) {
+ return send_power_mode_command(
+ std::move(pwr_command),
+ get_btm_client_interface().link_policy.BTM_SetPowerMode(
+ pm_id_, bd_addr_, &default_mandatory_sniff_mode));
+ }
+ pwr_result_t set_typical_sniff(pwr_command_t&& pwr_command) {
+ return send_power_mode_command(
+ std::move(pwr_command),
+ get_btm_client_interface().link_policy.BTM_SetPowerMode(
+ pm_id_, bd_addr_, &typical_sniff_mode));
+ }
+
+ pwr_result_t set_active(pwr_command_t&& pwr_command) {
+ return send_power_mode_command(
+ std::move(pwr_command),
+ get_btm_client_interface().link_policy.BTM_SetPowerMode(
+ pm_id_, bd_addr_, &default_active_mode));
+ }
+
+ private:
+ pwr_result_t send_power_mode_command(pwr_command_t&& pwr_command,
+ const tBTM_STATUS btm_status) {
+ pwr_result_t result = {
+ .btm_status = btm_status,
+ .cmd_status_future = pwr_command.cmd_status_promise.get_future(),
+ .mode_event_future = pwr_command.mode_event_promise.get_future(),
+ };
+ queue_.CommandSent(bd_addr_, std::move(pwr_command));
+ return result;
+ }
+
+ const uint8_t pm_id_;
+ const RawAddress bd_addr_;
+ };
+
+ PowerMode() {
+ BTM_PmRegister(BTM_PM_DEREG, &bta_dm_cb.pm_id,
+ []([[maybe_unused]] const RawAddress& bd_addr,
+ [[maybe_unused]] tBTM_PM_STATUS status,
+ [[maybe_unused]] uint16_t value,
+ [[maybe_unused]] tHCI_STATUS hci_status) {});
+
+ tBTM_STATUS btm_status =
+ get_btm_client_interface().lifecycle.BTM_PmRegister(
+ BTM_PM_REG_SET, &pm_id_,
+ [](const RawAddress& bd_addr, tBTM_PM_STATUS status, uint16_t value,
+ tHCI_STATUS hci_status) {
+ queue_.CallbackReceived(power_mode_callback_t{
+ .bd_addr = bd_addr,
+ .status = status,
+ .value = value,
+ .hci_status = hci_status,
+ });
+ });
+
+ ASSERT_LOG(BTM_SUCCESS == btm_status, "Failed to register power mode:%s",
+ btm_status_text(btm_status).c_str());
+ }
+
+ ~PowerMode() {
+ ASSERT(BTM_SUCCESS == get_btm_client_interface().lifecycle.BTM_PmRegister(
+ BTM_PM_DEREG, &pm_id_,
+ []([[maybe_unused]] const RawAddress& bd_addr,
+ [[maybe_unused]] tBTM_PM_STATUS status,
+ [[maybe_unused]] uint16_t value,
+ [[maybe_unused]] tHCI_STATUS hci_status) {}));
+ }
+
+ Client GetClient(const RawAddress bd_addr) { return Client(pm_id_, bd_addr); }
+
+ private:
+ uint8_t pm_id_;
+};
diff --git a/system/test/mock/mock_bluetooth_interface.cc b/system/test/mock/mock_bluetooth_interface.cc
index f55d026..86edb3f 100644
--- a/system/test/mock/mock_bluetooth_interface.cc
+++ b/system/test/mock/mock_bluetooth_interface.cc
@@ -21,54 +21,66 @@
#include "stack/include/bt_octets.h"
#include "types/raw_address.h"
-void invoke_adapter_state_changed_cb(bt_state_t state) {}
-void invoke_adapter_properties_cb(bt_status_t status, int num_properties,
- bt_property_t* properties) {}
-void invoke_remote_device_properties_cb(bt_status_t status, RawAddress bd_addr,
- int num_properties,
- bt_property_t* properties) {}
-void invoke_device_found_cb(int num_properties, bt_property_t* properties) {}
-void invoke_discovery_state_changed_cb(bt_discovery_state_t state) {}
-void invoke_pin_request_cb(RawAddress bd_addr, bt_bdname_t bd_name,
- uint32_t cod, bool min_16_digit) {}
-void invoke_ssp_request_cb(RawAddress bd_addr, bt_bdname_t bd_name,
- uint32_t cod, bt_ssp_variant_t pairing_variant,
- uint32_t pass_key) {}
-void invoke_oob_data_request_cb(tBT_TRANSPORT t, bool valid, Octet16 c,
- Octet16 r, RawAddress raw_address,
- uint8_t address_type) {}
-void invoke_bond_state_changed_cb(bt_status_t status, RawAddress bd_addr,
- bt_bond_state_t state, int fail_reason) {}
-void invoke_address_consolidate_cb(RawAddress main_bd_addr,
- RawAddress secondary_bd_addr) {}
-void invoke_le_address_associate_cb(RawAddress main_bd_addr,
- RawAddress secondary_bd_addr) {}
-void invoke_acl_state_changed_cb(bt_status_t status, RawAddress bd_addr,
- bt_acl_state_t state, int transport_link_type,
- bt_hci_error_code_t hci_reason,
- bt_conn_direction_t direction,
- uint16_t acl_handle) {}
-void invoke_thread_evt_cb(bt_cb_thread_evt event) {}
+void invoke_adapter_state_changed_cb(bt_state_t /* state */) {}
+void invoke_adapter_properties_cb(bt_status_t /* status */,
+ int /* num_properties */,
+ bt_property_t* /* properties */) {}
+void invoke_remote_device_properties_cb(bt_status_t /* status */,
+ RawAddress /* bd_addr */,
+ int /* num_properties */,
+ bt_property_t* /* properties */) {}
+void invoke_device_found_cb(int /* num_properties */,
+ bt_property_t* /* properties */) {}
+void invoke_discovery_state_changed_cb(bt_discovery_state_t /* state */) {}
+void invoke_pin_request_cb(RawAddress /* bd_addr */, bt_bdname_t /* bd_name */,
+ uint32_t /* cod */, bool /* min_16_digit */) {}
+void invoke_ssp_request_cb(RawAddress /* bd_addr */, bt_bdname_t /* bd_name */,
+ uint32_t /* cod */,
+ bt_ssp_variant_t /* pairing_variant */,
+ uint32_t /* pass_key */) {}
+void invoke_oob_data_request_cb(tBT_TRANSPORT /* t */, bool /* valid */,
+ Octet16 /* c */, Octet16 /* r */,
+ RawAddress /* raw_address */,
+ uint8_t /* address_type */) {}
+void invoke_bond_state_changed_cb(bt_status_t /* status */,
+ RawAddress /* bd_addr */,
+ bt_bond_state_t /* state */,
+ int /* fail_reason */) {}
+void invoke_address_consolidate_cb(RawAddress /* main_bd_addr */,
+ RawAddress /* secondary_bd_addr */) {}
+void invoke_le_address_associate_cb(RawAddress /* main_bd_addr */,
+ RawAddress /* secondary_bd_addr */) {}
+void invoke_acl_state_changed_cb(bt_status_t /* status */,
+ RawAddress /* bd_addr */,
+ bt_acl_state_t /* state */,
+ int /* transport_link_type */,
+ bt_hci_error_code_t /* hci_reason */,
+ bt_conn_direction_t /* direction */,
+ uint16_t /* acl_handle */) {}
+void invoke_thread_evt_cb(bt_cb_thread_evt /* event */) {}
-void invoke_le_test_mode_cb(bt_status_t status, uint16_t count) {}
+void invoke_le_test_mode_cb(bt_status_t /* status */, uint16_t /* count */) {}
-void invoke_energy_info_cb(bt_activity_energy_info energy_info,
- bt_uid_traffic_t* uid_data) {}
-void invoke_link_quality_report_cb(uint64_t timestamp, int report_id, int rssi,
- int snr, int retransmission_count,
- int packets_not_receive_count,
- int negative_acknowledgement_count) {}
-void invoke_key_missing_cb(const RawAddress bd_addr) {}
+void invoke_energy_info_cb(bt_activity_energy_info /* energy_info */,
+ bt_uid_traffic_t* /* uid_data */) {}
+void invoke_link_quality_report_cb(uint64_t /* timestamp */,
+ int /* report_id */, int /* rssi */,
+ int /* snr */,
+ int /* retransmission_count */,
+ int /* packets_not_receive_count */,
+ int /* negative_acknowledgement_count */) {}
+void invoke_key_missing_cb(const RawAddress /* bd_addr */) {}
-static void init_stack(bluetooth::core::CoreInterface* interface) {}
+static void init_stack(bluetooth::core::CoreInterface* /* interface */) {}
-static void start_up_stack_async(bluetooth::core::CoreInterface* interface,
- ProfileStartCallback startProfiles,
- ProfileStopCallback stopProfiles) {}
+static void start_up_stack_async(
+ bluetooth::core::CoreInterface* /* interface */,
+ ProfileStartCallback /* startProfiles */,
+ ProfileStopCallback /* stopProfiles */) {}
-static void shut_down_stack_async(ProfileStopCallback stopProfiles) {}
+static void shut_down_stack_async(ProfileStopCallback /* stopProfiles */) {}
-static void clean_up_stack(ProfileStopCallback stopProfiles) {}
+static void clean_up_stack(ProfileStopCallback /* stopProfiles */) {}
static bool get_stack_is_running() { return true; }
diff --git a/system/test/mock/mock_bta_csis.cc b/system/test/mock/mock_bta_csis.cc
index 6ec2761..3280acb 100644
--- a/system/test/mock/mock_bta_csis.cc
+++ b/system/test/mock/mock_bta_csis.cc
@@ -25,8 +25,7 @@
using bluetooth::csis::CsisClientCallbacks;
void CsisClient::AddFromStorage(const RawAddress& addr,
- const std::vector<uint8_t>& in,
- bool autoconnect) {
+ const std::vector<uint8_t>& in) {
inc_func_call_count(__func__);
}
bool CsisClient::GetForStorage(const RawAddress& addr,
diff --git a/system/test/mock/mock_bta_hh_api.cc b/system/test/mock/mock_bta_hh_api.cc
index 70dd17a..ee1d1fd 100644
--- a/system/test/mock/mock_bta_hh_api.cc
+++ b/system/test/mock/mock_bta_hh_api.cc
@@ -29,7 +29,7 @@
void BTA_HhEnable(tBTA_HH_CBACK* p_cback, bool enable_hidp, bool enable_hogp) {
inc_func_call_count(__func__);
}
-void BTA_HhAddDev(const RawAddress& bda, tBTA_HH_ATTR_MASK attr_mask,
+void BTA_HhAddDev(const tAclLinkSpec& link_spec, tBTA_HH_ATTR_MASK attr_mask,
uint8_t sub_class, uint8_t app_id,
tBTA_HH_DEV_DSCP_INFO dscp_info) {
inc_func_call_count(__func__);
@@ -43,12 +43,14 @@
uint8_t rpt_id, uint16_t buf_size) {
inc_func_call_count(__func__);
}
-void BTA_HhOpen(const RawAddress& dev_bda) { inc_func_call_count(__func__); }
+void BTA_HhOpen(const tAclLinkSpec& link_spec) {
+ inc_func_call_count(__func__);
+}
void BTA_HhRemoveDev(uint8_t dev_handle) { inc_func_call_count(__func__); }
void BTA_HhSendCtrl(uint8_t dev_handle, tBTA_HH_TRANS_CTRL_TYPE c_type) {
inc_func_call_count(__func__);
}
-void BTA_HhSendData(uint8_t dev_handle, const RawAddress& dev_bda,
+void BTA_HhSendData(uint8_t dev_handle, const tAclLinkSpec& link_spec,
BT_HDR* p_data) {
inc_func_call_count(__func__);
}
diff --git a/system/test/mock/mock_bta_hh_utils.cc b/system/test/mock/mock_bta_hh_utils.cc
index bb15bd8..2d7a8bc 100644
--- a/system/test/mock/mock_bta_hh_utils.cc
+++ b/system/test/mock/mock_bta_hh_utils.cc
@@ -74,20 +74,20 @@
inc_func_call_count(__func__);
return test::mock::bta_hh_utils::bta_hh_dev_handle_to_cb_idx(dev_handle);
}
-uint8_t bta_hh_find_cb(const RawAddress& bda) {
+uint8_t bta_hh_find_cb(const tAclLinkSpec& link_spec) {
inc_func_call_count(__func__);
- return test::mock::bta_hh_utils::bta_hh_find_cb(bda);
+ return test::mock::bta_hh_utils::bta_hh_find_cb(link_spec);
}
-tBTA_HH_DEV_CB* bta_hh_get_cb(const RawAddress& bda) {
+tBTA_HH_DEV_CB* bta_hh_get_cb(const tAclLinkSpec& link_spec) {
inc_func_call_count(__func__);
- return test::mock::bta_hh_utils::bta_hh_get_cb(bda);
+ return test::mock::bta_hh_utils::bta_hh_get_cb(link_spec);
}
-tBTA_HH_STATUS bta_hh_read_ssr_param(const RawAddress& bd_addr,
+tBTA_HH_STATUS bta_hh_read_ssr_param(const tAclLinkSpec& link_spec,
uint16_t* p_max_ssr_lat,
uint16_t* p_min_ssr_tout) {
inc_func_call_count(__func__);
- return test::mock::bta_hh_utils::bta_hh_read_ssr_param(bd_addr, p_max_ssr_lat,
- p_min_ssr_tout);
+ return test::mock::bta_hh_utils::bta_hh_read_ssr_param(
+ link_spec, p_max_ssr_lat, p_min_ssr_tout);
}
bool bta_hh_tod_spt(tBTA_HH_DEV_CB* p_cb, uint8_t sub_class) {
inc_func_call_count(__func__);
diff --git a/system/test/mock/mock_bta_hh_utils.h b/system/test/mock/mock_bta_hh_utils.h
index 7ae214e..cfee660 100644
--- a/system/test/mock/mock_bta_hh_utils.h
+++ b/system/test/mock/mock_bta_hh_utils.h
@@ -88,40 +88,42 @@
extern struct bta_hh_dev_handle_to_cb_idx bta_hh_dev_handle_to_cb_idx;
// Name: bta_hh_find_cb
-// Params: const RawAddress& bda
+// Params: const tAclLinkSpec& link_spec
// Return: uint8_t
struct bta_hh_find_cb {
uint8_t return_value{0};
- std::function<uint8_t(const RawAddress& bda)> body{
- [this](const RawAddress& bda) { return return_value; }};
- uint8_t operator()(const RawAddress& bda) { return body(bda); };
+ std::function<uint8_t(const tAclLinkSpec& link_spec)> body{
+ [this](const tAclLinkSpec& link_spec) { return return_value; }};
+ uint8_t operator()(const tAclLinkSpec& link_spec) { return body(link_spec); };
};
extern struct bta_hh_find_cb bta_hh_find_cb;
// Name: bta_hh_get_cb
-// Params: const RawAddress& bda
+// Params: const tAclLinkSpec& link_spec
// Return: tBTA_HH_DEV_CB*
struct bta_hh_get_cb {
tBTA_HH_DEV_CB* return_value{0};
- std::function<tBTA_HH_DEV_CB*(const RawAddress& bda)> body{
- [this](const RawAddress& bda) { return return_value; }};
- tBTA_HH_DEV_CB* operator()(const RawAddress& bda) { return body(bda); };
+ std::function<tBTA_HH_DEV_CB*(const tAclLinkSpec& link_spec)> body{
+ [this](const tAclLinkSpec& link_spec) { return return_value; }};
+ tBTA_HH_DEV_CB* operator()(const tAclLinkSpec& link_spec) {
+ return body(link_spec);
+ };
};
extern struct bta_hh_get_cb bta_hh_get_cb;
// Name: bta_hh_read_ssr_param
-// Params: const RawAddress& bd_addr, uint16_t* p_max_ssr_lat, uint16_t*
+// Params: const tAclLinkSpec& bd_addr, uint16_t* p_max_ssr_lat, uint16_t*
// p_min_ssr_tout Return: tBTA_HH_STATUS
struct bta_hh_read_ssr_param {
tBTA_HH_STATUS return_value{0};
- std::function<tBTA_HH_STATUS(const RawAddress& bd_addr,
+ std::function<tBTA_HH_STATUS(const tAclLinkSpec& link_spec,
uint16_t* p_max_ssr_lat,
uint16_t* p_min_ssr_tout)>
- body{[this](const RawAddress& bd_addr, uint16_t* p_max_ssr_lat,
+ body{[this](const tAclLinkSpec& link_spec, uint16_t* p_max_ssr_lat,
uint16_t* p_min_ssr_tout) { return return_value; }};
- tBTA_HH_STATUS operator()(const RawAddress& bd_addr, uint16_t* p_max_ssr_lat,
- uint16_t* p_min_ssr_tout) {
- return body(bd_addr, p_max_ssr_lat, p_min_ssr_tout);
+ tBTA_HH_STATUS operator()(const tAclLinkSpec& link_spec,
+ uint16_t* p_max_ssr_lat, uint16_t* p_min_ssr_tout) {
+ return body(link_spec, p_max_ssr_lat, p_min_ssr_tout);
};
};
extern struct bta_hh_read_ssr_param bta_hh_read_ssr_param;
diff --git a/system/test/mock/mock_bta_leaudio.cc b/system/test/mock/mock_bta_leaudio.cc
index 743a10b..527ebf7 100644
--- a/system/test/mock/mock_bta_leaudio.cc
+++ b/system/test/mock/mock_bta_leaudio.cc
@@ -84,6 +84,10 @@
inc_func_call_count(__func__);
return false;
}
+bool LeAudioClient::IsLeAudioClientInStreaming(void) {
+ inc_func_call_count(__func__);
+ return false;
+}
void LeAudioClient::Initialize(
bluetooth::le_audio::LeAudioClientCallbacks* callbacks_,
base::Closure initCb, base::Callback<bool()> hal_2_1_verifier,
diff --git a/system/test/mock/mock_btif_av.h b/system/test/mock/mock_btif_av.h
index ee2fa23..519c394 100644
--- a/system/test/mock/mock_btif_av.h
+++ b/system/test/mock/mock_btif_av.h
@@ -60,7 +60,7 @@
// Return: void
struct btif_av_acl_disconnected {
std::function<void(const RawAddress& peer_address)> body{
- [](const RawAddress& peer_address) {}};
+ [](const RawAddress& /* peer_address */) {}};
void operator()(const RawAddress& peer_address) { body(peer_address); };
};
extern struct btif_av_acl_disconnected btif_av_acl_disconnected;
@@ -81,7 +81,7 @@
struct btif_av_find_by_handle {
static const RawAddress& return_value;
std::function<const RawAddress&(tBTA_AV_HNDL bta_handle)> body{
- [](tBTA_AV_HNDL bta_handle) { return return_value; }};
+ [](tBTA_AV_HNDL /* bta_handle */) { return return_value; }};
const RawAddress& operator()(tBTA_AV_HNDL bta_handle) {
return body(bta_handle);
};
@@ -166,7 +166,7 @@
struct btif_av_is_connected_addr {
static bool return_value;
std::function<bool(const RawAddress& peer_address)> body{
- [](const RawAddress& peer_address) { return return_value; }};
+ [](const RawAddress& /* peer_address */) { return return_value; }};
bool operator()(const RawAddress& peer_address) {
return body(peer_address);
};
@@ -179,7 +179,7 @@
struct btif_av_is_peer_edr {
static bool return_value;
std::function<bool(const RawAddress& peer_address)> body{
- [](const RawAddress& peer_address) { return return_value; }};
+ [](const RawAddress& /* peer_address */) { return return_value; }};
bool operator()(const RawAddress& peer_address) {
return body(peer_address);
};
@@ -192,7 +192,7 @@
struct btif_av_is_peer_silenced {
static bool return_value;
std::function<bool(const RawAddress& peer_address)> body{
- [](const RawAddress& peer_address) { return return_value; }};
+ [](const RawAddress& /* peer_address */) { return return_value; }};
bool operator()(const RawAddress& peer_address) {
return body(peer_address);
};
@@ -225,7 +225,7 @@
struct btif_av_peer_is_connected_sink {
static bool return_value;
std::function<bool(const RawAddress& peer_address)> body{
- [](const RawAddress& peer_address) { return return_value; }};
+ [](const RawAddress& /* peer_address */) { return return_value; }};
bool operator()(const RawAddress& peer_address) {
return body(peer_address);
};
@@ -238,7 +238,7 @@
struct btif_av_peer_is_connected_source {
static bool return_value;
std::function<bool(const RawAddress& peer_address)> body{
- [](const RawAddress& peer_address) { return return_value; }};
+ [](const RawAddress& /* peer_address */) { return return_value; }};
bool operator()(const RawAddress& peer_address) {
return body(peer_address);
};
@@ -251,7 +251,7 @@
struct btif_av_peer_is_sink {
static bool return_value;
std::function<bool(const RawAddress& peer_address)> body{
- [](const RawAddress& peer_address) { return return_value; }};
+ [](const RawAddress& /* peer_address */) { return return_value; }};
bool operator()(const RawAddress& peer_address) {
return body(peer_address);
};
@@ -264,7 +264,7 @@
struct btif_av_peer_is_source {
static bool return_value;
std::function<bool(const RawAddress& peer_address)> body{
- [](const RawAddress& peer_address) { return return_value; }};
+ [](const RawAddress& /* peer_address */) { return return_value; }};
bool operator()(const RawAddress& peer_address) {
return body(peer_address);
};
@@ -277,7 +277,7 @@
struct btif_av_peer_prefers_mandatory_codec {
static bool return_value;
std::function<bool(const RawAddress& peer_address)> body{
- [](const RawAddress& peer_address) { return return_value; }};
+ [](const RawAddress& /* peer_address */) { return return_value; }};
bool operator()(const RawAddress& peer_address) {
return body(peer_address);
};
@@ -291,7 +291,7 @@
struct btif_av_peer_supports_3mbps {
static bool return_value;
std::function<bool(const RawAddress& peer_address)> body{
- [](const RawAddress& peer_address) { return return_value; }};
+ [](const RawAddress& /* peer_address */) { return return_value; }};
bool operator()(const RawAddress& peer_address) {
return body(peer_address);
};
@@ -310,12 +310,12 @@
const std::vector<btav_a2dp_codec_config_t>& codecs_local_capabilities,
const std::vector<btav_a2dp_codec_config_t>&
codecs_selectable_capabilities)>
- body{[](const RawAddress& peer_address,
- const btav_a2dp_codec_config_t& codec_config,
+ body{[](const RawAddress& /* peer_address */,
+ const btav_a2dp_codec_config_t& /* codec_config */,
const std::vector<btav_a2dp_codec_config_t>&
- codecs_local_capabilities,
+ /* codecs_local_capabilities */,
const std::vector<btav_a2dp_codec_config_t>&
- codecs_selectable_capabilities) {}};
+ /* codecs_selectable_capabilities */) {}};
void operator()(
const RawAddress& peer_address,
const btav_a2dp_codec_config_t& codec_config,
@@ -343,7 +343,7 @@
// Return: void
struct btif_av_set_audio_delay {
std::function<void(const RawAddress& peer_address, uint16_t delay)> body{
- [](const RawAddress& peer_address, uint16_t delay) {}};
+ [](const RawAddress& /* peer_address */, uint16_t /* delay */) {}};
void operator()(const RawAddress& peer_address, uint16_t delay) {
body(peer_address, delay);
};
@@ -355,7 +355,7 @@
// Return: void
struct btif_av_set_dynamic_audio_buffer_size {
std::function<void(uint8_t dynamic_audio_buffer_size)> body{
- [](uint8_t dynamic_audio_buffer_size) {}};
+ [](uint8_t /* dynamic_audio_buffer_size */) {}};
void operator()(uint8_t dynamic_audio_buffer_size) {
body(dynamic_audio_buffer_size);
};
@@ -367,7 +367,8 @@
// Params: bool is_low_latency
// Return: void
struct btif_av_set_low_latency {
- std::function<void(bool is_low_latency)> body{[](bool is_low_latency) {}};
+ std::function<void(bool is_low_latency)> body{
+ [](bool /* is_low_latency */) {}};
void operator()(bool is_low_latency) { body(is_low_latency); };
};
extern struct btif_av_set_low_latency btif_av_set_low_latency;
@@ -388,7 +389,7 @@
struct btif_av_sink_execute_service {
static bt_status_t return_value;
std::function<bt_status_t(bool enable)> body{
- [](bool enable) { return return_value; }};
+ [](bool /* enable */) { return return_value; }};
bt_status_t operator()(bool enable) { return body(enable); };
};
extern struct btif_av_sink_execute_service btif_av_sink_execute_service;
@@ -409,7 +410,7 @@
struct btif_av_source_execute_service {
static bt_status_t return_value;
std::function<bt_status_t(bool enable)> body{
- [](bool enable) { return return_value; }};
+ [](bool /* enable */) { return return_value; }};
bt_status_t operator()(bool enable) { return body(enable); };
};
extern struct btif_av_source_execute_service btif_av_source_execute_service;
@@ -419,7 +420,7 @@
// Return: void
struct btif_av_src_disconnect_sink {
std::function<void(const RawAddress& peer_address)> body{
- [](const RawAddress& peer_address) {}};
+ [](const RawAddress& /* peer_address */) {}};
void operator()(const RawAddress& peer_address) { body(peer_address); };
};
extern struct btif_av_src_disconnect_sink btif_av_src_disconnect_sink;
@@ -466,7 +467,8 @@
// Params: bool use_latency_mode
// Return: void
struct btif_av_stream_start_with_latency {
- std::function<void(bool use_latency_mode)> body{[](bool use_latency_mode) {}};
+ std::function<void(bool use_latency_mode)> body{
+ [](bool /* use_latency_mode */) {}};
void operator()(bool use_latency_mode) { body(use_latency_mode); };
};
extern struct btif_av_stream_start_with_latency
@@ -487,7 +489,7 @@
// Return: void
struct btif_av_stream_stop {
std::function<void(const RawAddress& peer_address)> body{
- [](const RawAddress& peer_address) {}};
+ [](const RawAddress& /* peer_address */) {}};
void operator()(const RawAddress& peer_address) { body(peer_address); };
};
extern struct btif_av_stream_stop btif_av_stream_stop;
@@ -505,7 +507,7 @@
// Params: int fd
// Return: void
struct btif_debug_av_dump {
- std::function<void(int fd)> body{[](int fd) {}};
+ std::function<void(int fd)> body{[](int /* fd */) {}};
void operator()(int fd) { body(fd); };
};
extern struct btif_debug_av_dump btif_debug_av_dump;
@@ -516,7 +518,7 @@
struct dump_av_sm_event_name {
static const char* return_value;
std::function<const char*(int event)> body{
- [](int event) { return return_value; }};
+ [](int /* event */) { return return_value; }};
const char* operator()(int event) { return body(event); };
};
extern struct dump_av_sm_event_name dump_av_sm_event_name;
@@ -526,7 +528,7 @@
// Return: void
struct src_do_suspend_in_main_thread {
std::function<void(btif_av_sm_event_t event)> body{
- [](btif_av_sm_event_t event) {}};
+ [](btif_av_sm_event_t /* event */) {}};
void operator()(btif_av_sm_event_t event) { body(event); };
};
extern struct src_do_suspend_in_main_thread src_do_suspend_in_main_thread;
diff --git a/system/test/mock/mock_btif_avrcp_service.h b/system/test/mock/mock_btif_avrcp_service.h
index 3ba33f7..a0484d3 100644
--- a/system/test/mock/mock_btif_avrcp_service.h
+++ b/system/test/mock/mock_btif_avrcp_service.h
@@ -41,7 +41,7 @@
// Return: void
struct do_in_avrcp_jni {
std::function<void(const base::Closure& task)> body{
- [](const base::Closure& task) {}};
+ [](const base::Closure& /* task */) {}};
void operator()(const base::Closure& task) { body(task); };
};
extern struct do_in_avrcp_jni do_in_avrcp_jni;
diff --git a/system/test/mock/mock_btif_bluetooth.h b/system/test/mock/mock_btif_bluetooth.h
index 7f1fad0..fb06c56 100644
--- a/system/test/mock/mock_btif_bluetooth.h
+++ b/system/test/mock/mock_btif_bluetooth.h
@@ -62,7 +62,8 @@
// Params: uint8_t enable
// Returns: int
struct dut_mode_configure {
- std::function<int(uint8_t enable)> body{[](uint8_t enable) { return 0; }};
+ std::function<int(uint8_t enable)> body{
+ [](uint8_t /* enable */) { return 0; }};
int operator()(uint8_t enable) { return body(enable); };
};
extern struct dut_mode_configure dut_mode_configure;
@@ -70,8 +71,11 @@
// Params: uint16_t opcode, uint8_t* buf, uint8_t len
// Returns: int
struct dut_mode_send {
- std::function<int(uint16_t opcode, uint8_t* buf, uint8_t len)> body{
- [](uint16_t opcode, uint8_t* buf, uint8_t len) { return 0; }};
+ std::function<int(uint16_t /* opcode */, uint8_t* /* buf */,
+ uint8_t /* len */)>
+ body{[](uint16_t /* opcode */, uint8_t* /* buf */, uint8_t /* len */) {
+ return 0;
+ }};
int operator()(uint16_t opcode, uint8_t* buf, uint8_t len) {
return body(opcode, buf, len);
};
@@ -91,7 +95,7 @@
// Returns: int
struct get_remote_device_properties {
std::function<int(RawAddress* remote_addr)> body{
- [](RawAddress* remote_addr) { return 0; }};
+ [](RawAddress* /* remote_addr */) { return 0; }};
int operator()(RawAddress* remote_addr) { return body(remote_addr); };
};
extern struct get_remote_device_properties get_remote_device_properties;
@@ -100,7 +104,9 @@
// Returns: int
struct get_remote_device_property {
std::function<int(RawAddress* remote_addr, bt_property_type_t type)> body{
- [](RawAddress* remote_addr, bt_property_type_t type) { return 0; }};
+ [](RawAddress* /* remote_addr */, bt_property_type_t /* type */) {
+ return 0;
+ }};
int operator()(RawAddress* remote_addr, bt_property_type_t type) {
return body(remote_addr, type);
};
@@ -111,7 +117,7 @@
// Returns: int
struct get_remote_services {
std::function<int(RawAddress* remote_addr)> body{
- [](RawAddress* remote_addr) { return 0; }};
+ [](RawAddress* /* remote_addr */) { return 0; }};
int operator()(RawAddress* remote_addr) { return body(remote_addr); };
};
extern struct get_remote_services get_remote_services;
@@ -120,7 +126,9 @@
// Returns: int
struct le_test_mode {
std::function<int(uint16_t opcode, uint8_t* buf, uint8_t len)> body{
- [](uint16_t opcode, uint8_t* buf, uint8_t len) { return 0; }};
+ [](uint16_t /* opcode */, uint8_t* /* buf */, uint8_t /* len */) {
+ return 0;
+ }};
int operator()(uint16_t opcode, uint8_t* buf, uint8_t len) {
return body(opcode, buf, len);
};
@@ -131,9 +139,8 @@
// Returns: int
struct set_remote_device_property {
std::function<int(RawAddress* remote_addr, const bt_property_t* property)>
- body{[](RawAddress* remote_addr, const bt_property_t* property) {
- return 0;
- }};
+ body{[](RawAddress* /* remote_addr */,
+ const bt_property_t* /* property */) { return 0; }};
int operator()(RawAddress* remote_addr, const bt_property_t* property) {
return body(remote_addr, property);
};
@@ -144,7 +151,7 @@
// Returns: void
struct set_hal_cbacks {
std::function<void(bt_callbacks_t* callbacks)> body{
- [](bt_callbacks_t* callbacks) { ; }};
+ [](bt_callbacks_t* /* callbacks */) { ; }};
void operator()(bt_callbacks_t* callbacks) { body(callbacks); };
};
extern struct set_hal_cbacks set_hal_cbacks;
diff --git a/system/test/mock/mock_btif_bqr.cc b/system/test/mock/mock_btif_bqr.cc
index 8e2ffb3..b634704 100644
--- a/system/test/mock/mock_btif_bqr.cc
+++ b/system/test/mock/mock_btif_bqr.cc
@@ -26,11 +26,11 @@
namespace bluetooth {
namespace bqr {
-void DumpLmpLlMessage(uint8_t length, const uint8_t* p_event) {
+void DumpLmpLlMessage(uint8_t /* length */, const uint8_t* /* p_event */) {
inc_func_call_count(__func__);
}
-void DumpBtScheduling(uint8_t length, const uint8_t* p_event) {
+void DumpBtScheduling(uint8_t /* length */, const uint8_t* /* p_event */) {
inc_func_call_count(__func__);
}
diff --git a/system/test/mock/mock_btif_bta_pan_co_rx.h b/system/test/mock/mock_btif_bta_pan_co_rx.h
index 9f5e90e..d9059c5 100644
--- a/system/test/mock/mock_btif_bta_pan_co_rx.h
+++ b/system/test/mock/mock_btif_bta_pan_co_rx.h
@@ -37,7 +37,7 @@
// Returns: uint8_t
struct bta_pan_co_init {
std::function<uint8_t(uint8_t* q_level)> body{
- [](uint8_t* q_level) { return 0; }};
+ [](uint8_t* /* q_level */) { return 0; }};
uint8_t operator()(uint8_t* q_level) { return body(q_level); };
};
extern struct bta_pan_co_init bta_pan_co_init;
@@ -46,7 +46,7 @@
// Returns: void
struct bta_pan_co_close {
std::function<void(uint16_t handle, uint8_t app_id)> body{
- [](uint16_t handle, uint8_t app_id) { ; }};
+ [](uint16_t /* handle */, uint8_t /* app_id */) { ; }};
void operator()(uint16_t handle, uint8_t app_id) { body(handle, app_id); };
};
extern struct bta_pan_co_close bta_pan_co_close;
@@ -57,8 +57,9 @@
struct bta_pan_co_mfilt_ind {
std::function<void(uint16_t handle, bool indication, tBTA_PAN_STATUS result,
uint16_t len, uint8_t* p_filters)>
- body{[](uint16_t handle, bool indication, tBTA_PAN_STATUS result,
- uint16_t len, uint8_t* p_filters) { ; }};
+ body{[](uint16_t /* handle */, bool /* indication */,
+ tBTA_PAN_STATUS /* result */, uint16_t /* len */,
+ uint8_t* /* p_filters */) { ; }};
void operator()(uint16_t handle, bool indication, tBTA_PAN_STATUS result,
uint16_t len, uint8_t* p_filters) {
body(handle, indication, result, len, p_filters);
@@ -72,8 +73,9 @@
struct bta_pan_co_pfilt_ind {
std::function<void(uint16_t handle, bool indication, tBTA_PAN_STATUS result,
uint16_t len, uint8_t* p_filters)>
- body{[](uint16_t handle, bool indication, tBTA_PAN_STATUS result,
- uint16_t len, uint8_t* p_filters) { ; }};
+ body{[](uint16_t /* handle */, bool /* indication */,
+ tBTA_PAN_STATUS /* result */, uint16_t /* len */,
+ uint8_t* /* p_filters */) { ; }};
void operator()(uint16_t handle, bool indication, tBTA_PAN_STATUS result,
uint16_t len, uint8_t* p_filters) {
body(handle, indication, result, len, p_filters);
@@ -85,7 +87,7 @@
// bool enable Returns: void
struct bta_pan_co_rx_flow {
std::function<void(uint16_t handle, uint8_t app_id, bool enable)> body{
- [](uint16_t handle, uint8_t app_id, bool enable) { ; }};
+ [](uint16_t /* handle */, uint8_t /* app_id */, bool /* enable */) { ; }};
void operator()(uint16_t handle, uint8_t app_id, bool enable) {
body(handle, app_id, enable);
};
@@ -96,7 +98,7 @@
// Returns: void
struct bta_pan_co_rx_path {
std::function<void(uint16_t handle, uint8_t app_id)> body{
- [](uint16_t handle, uint8_t app_id) { ; }};
+ [](uint16_t /* handle */, uint8_t /* app_id */) { ; }};
void operator()(uint16_t handle, uint8_t app_id) { body(handle, app_id); };
};
extern struct bta_pan_co_rx_path bta_pan_co_rx_path;
@@ -105,7 +107,7 @@
// Returns: void
struct bta_pan_co_tx_path {
std::function<void(uint16_t handle, uint8_t app_id)> body{
- [](uint16_t handle, uint8_t app_id) { ; }};
+ [](uint16_t /* handle */, uint8_t /* app_id */) { ; }};
void operator()(uint16_t handle, uint8_t app_id) { body(handle, app_id); };
};
extern struct bta_pan_co_tx_path bta_pan_co_tx_path;
diff --git a/system/test/mock/mock_btif_co_bta_av_co.h b/system/test/mock/mock_btif_co_bta_av_co.h
index e463e61..69de9c7 100644
--- a/system/test/mock/mock_btif_co_bta_av_co.h
+++ b/system/test/mock/mock_btif_co_bta_av_co.h
@@ -51,7 +51,8 @@
struct bta_av_co_audio_close {
std::function<void(tBTA_AV_HNDL bta_av_handle,
const RawAddress& peer_address)>
- body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) {}};
+ body{[](tBTA_AV_HNDL /* bta_av_handle */,
+ const RawAddress& /* peer_address */) {}};
void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) {
body(bta_av_handle, peer_address);
};
@@ -64,8 +65,8 @@
struct bta_av_co_audio_delay {
std::function<void(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address,
uint16_t delay)>
- body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address,
- uint16_t delay) {}};
+ body{[](tBTA_AV_HNDL /* bta_av_handle */,
+ const RawAddress& /* peer_address */, uint16_t /* delay */) {}};
void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address,
uint16_t delay) {
body(bta_av_handle, peer_address, delay);
@@ -81,9 +82,10 @@
std::function<void(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address,
uint8_t num_seps, uint8_t num_sinks, uint8_t num_sources,
uint16_t uuid_local)>
- body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address,
- uint8_t num_seps, uint8_t num_sinks, uint8_t num_sources,
- uint16_t uuid_local) {}};
+ body{[](tBTA_AV_HNDL /* bta_av_handle */,
+ const RawAddress& /* peer_address */, uint8_t /* num_seps */,
+ uint8_t /* num_sinks */, uint8_t /* num_sources */,
+ uint16_t /* uuid_local */) {}};
void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address,
uint8_t num_seps, uint8_t num_sinks, uint8_t num_sources,
uint16_t uuid_local) {
@@ -99,7 +101,8 @@
struct bta_av_co_audio_drop {
std::function<void(tBTA_AV_HNDL bta_av_handle,
const RawAddress& peer_address)>
- body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) {}};
+ body{[](tBTA_AV_HNDL /* bta_av_handle */,
+ const RawAddress& /* peer_address */) {}};
void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) {
body(bta_av_handle, peer_address);
};
@@ -116,10 +119,11 @@
tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address,
uint8_t* p_codec_info, uint8_t* p_sep_info_idx, uint8_t seid,
uint8_t* p_num_protect, uint8_t* p_protect_info)>
- body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address,
- uint8_t* p_codec_info, uint8_t* p_sep_info_idx, uint8_t seid,
- uint8_t* p_num_protect,
- uint8_t* p_protect_info) { return return_value; }};
+ body{[](tBTA_AV_HNDL /* bta_av_handle */,
+ const RawAddress& /* peer_address */, uint8_t* /* p_codec_info */,
+ uint8_t* /* p_sep_info_idx */, uint8_t /* seid */,
+ uint8_t* /* p_num_protect */,
+ uint8_t* /* p_protect_info */) { return return_value; }};
tA2DP_STATUS operator()(tBTA_AV_HNDL bta_av_handle,
const RawAddress& peer_address, uint8_t* p_codec_info,
uint8_t* p_sep_info_idx, uint8_t seid,
@@ -137,9 +141,8 @@
static bool return_value;
std::function<bool(btav_a2dp_codec_index_t codec_index,
AvdtpSepConfig* p_cfg)>
- body{[](btav_a2dp_codec_index_t codec_index, AvdtpSepConfig* p_cfg) {
- return return_value;
- }};
+ body{[](btav_a2dp_codec_index_t /* codec_index */,
+ AvdtpSepConfig* /* p_cfg */) { return return_value; }};
bool operator()(btav_a2dp_codec_index_t codec_index, AvdtpSepConfig* p_cfg) {
return body(codec_index, p_cfg);
};
@@ -152,8 +155,8 @@
struct bta_av_co_audio_open {
std::function<void(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address,
uint16_t mtu)>
- body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address,
- uint16_t mtu) {}};
+ body{[](tBTA_AV_HNDL /* bta_av_handle */,
+ const RawAddress& /* peer_address */, uint16_t /* mtu */) {}};
void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address,
uint16_t mtu) {
body(bta_av_handle, peer_address, mtu);
@@ -170,10 +173,11 @@
const uint8_t* p_codec_info, uint8_t seid,
uint8_t num_protect, const uint8_t* p_protect_info,
uint8_t t_local_sep, uint8_t avdt_handle)>
- body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address,
- const uint8_t* p_codec_info, uint8_t seid, uint8_t num_protect,
- const uint8_t* p_protect_info, uint8_t t_local_sep,
- uint8_t avdt_handle) {}};
+ body{[](tBTA_AV_HNDL /* bta_av_handle */,
+ const RawAddress& /* peer_address */,
+ const uint8_t* /* p_codec_info */, uint8_t /* seid */,
+ uint8_t /* num_protect */, const uint8_t* /* p_protect_info */,
+ uint8_t /* t_local_sep */, uint8_t /* avdt_handle */) {}};
void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address,
const uint8_t* p_codec_info, uint8_t seid,
uint8_t num_protect, const uint8_t* p_protect_info,
@@ -190,7 +194,7 @@
struct bta_av_co_audio_source_data_path {
static BT_HDR* return_value;
std::function<BT_HDR*(const uint8_t* p_codec_info, uint32_t* p_timestamp)>
- body{[](const uint8_t* p_codec_info, uint32_t* p_timestamp) {
+ body{[](const uint8_t* /* p_codec_info */, uint32_t* /* p_timestamp */) {
return return_value;
}};
BT_HDR* operator()(const uint8_t* p_codec_info, uint32_t* p_timestamp) {
@@ -205,8 +209,10 @@
struct bta_av_co_audio_start {
std::function<void(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address,
const uint8_t* p_codec_info, bool* p_no_rtp_header)>
- body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address,
- const uint8_t* p_codec_info, bool* p_no_rtp_header) {}};
+ body{[](tBTA_AV_HNDL /* bta_av_handle */,
+ const RawAddress& /* peer_address */,
+ const uint8_t* /* p_codec_info */,
+ bool* /* p_no_rtp_header */) {}};
void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address,
const uint8_t* p_codec_info, bool* p_no_rtp_header) {
body(bta_av_handle, peer_address, p_codec_info, p_no_rtp_header);
@@ -220,7 +226,8 @@
struct bta_av_co_audio_stop {
std::function<void(tBTA_AV_HNDL bta_av_handle,
const RawAddress& peer_address)>
- body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) {}};
+ body{[](tBTA_AV_HNDL /* bta_av_handle */,
+ const RawAddress& /* peer_address */) {}};
void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address) {
body(bta_av_handle, peer_address);
};
@@ -233,8 +240,8 @@
struct bta_av_co_audio_update_mtu {
std::function<void(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address,
uint16_t mtu)>
- body{[](tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address,
- uint16_t mtu) {}};
+ body{[](tBTA_AV_HNDL /* bta_av_handle */,
+ const RawAddress& /* peer_address */, uint16_t /* mtu */) {}};
void operator()(tBTA_AV_HNDL bta_av_handle, const RawAddress& peer_address,
uint16_t mtu) {
body(bta_av_handle, peer_address, mtu);
@@ -270,8 +277,8 @@
struct bta_av_co_get_peer_params {
std::function<void(const RawAddress& peer_address,
tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params)>
- body{[](const RawAddress& peer_address,
- tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params) {}};
+ body{[](const RawAddress& /* peer_address */,
+ tA2DP_ENCODER_INIT_PEER_PARAMS* /* p_peer_params */) {}};
void operator()(const RawAddress& peer_address,
tA2DP_ENCODER_INIT_PEER_PARAMS* p_peer_params) {
body(peer_address, p_peer_params);
@@ -285,7 +292,7 @@
struct bta_av_co_get_scmst_info {
static btav_a2dp_scmst_info_t return_value;
std::function<btav_a2dp_scmst_info_t(const RawAddress& peer_address)> body{
- [](const RawAddress& peer_address) { return return_value; }};
+ [](const RawAddress& /* peer_address */) { return return_value; }};
btav_a2dp_scmst_info_t operator()(const RawAddress& peer_address) {
return body(peer_address);
};
@@ -299,8 +306,9 @@
std::function<void(
const std::vector<btav_a2dp_codec_config_t>& codec_priorities,
std::vector<btav_a2dp_codec_info_t>* supported_codecs)>
- body{[](const std::vector<btav_a2dp_codec_config_t>& codec_priorities,
- std::vector<btav_a2dp_codec_info_t>* supported_codecs) {}};
+ body{[](const std::vector<
+ btav_a2dp_codec_config_t>& /* codec_priorities */,
+ std::vector<btav_a2dp_codec_info_t>* /* supported_codecs */) {}};
void operator()(const std::vector<btav_a2dp_codec_config_t>& codec_priorities,
std::vector<btav_a2dp_codec_info_t>* supported_codecs) {
body(codec_priorities, supported_codecs);
@@ -314,7 +322,7 @@
struct bta_av_co_is_supported_codec {
static bool return_value;
std::function<bool(btav_a2dp_codec_index_t codec_index)> body{
- [](btav_a2dp_codec_index_t codec_index) { return return_value; }};
+ [](btav_a2dp_codec_index_t /* codec_index */) { return return_value; }};
bool operator()(btav_a2dp_codec_index_t codec_index) {
return body(codec_index);
};
@@ -327,7 +335,7 @@
struct bta_av_co_set_active_peer {
static bool return_value;
std::function<bool(const RawAddress& peer_address)> body{
- [](const RawAddress& peer_address) { return return_value; }};
+ [](const RawAddress& /* peer_address */) { return return_value; }};
bool operator()(const RawAddress& peer_address) {
return body(peer_address);
};
@@ -340,7 +348,7 @@
struct bta_av_co_set_codec_audio_config {
static bool return_value;
std::function<bool(const btav_a2dp_codec_config_t& codec_audio_config)> body{
- [](const btav_a2dp_codec_config_t& codec_audio_config) {
+ [](const btav_a2dp_codec_config_t& /* codec_audio_config */) {
return return_value;
}};
bool operator()(const btav_a2dp_codec_config_t& codec_audio_config) {
@@ -357,9 +365,9 @@
std::function<bool(const RawAddress& peer_address,
const btav_a2dp_codec_config_t& codec_user_config,
bool* p_restart_output)>
- body{[](const RawAddress& peer_address,
- const btav_a2dp_codec_config_t& codec_user_config,
- bool* p_restart_output) { return return_value; }};
+ body{[](const RawAddress& /* peer_address */,
+ const btav_a2dp_codec_config_t& /* codec_user_config */,
+ bool* /* p_restart_output */) { return return_value; }};
bool operator()(const RawAddress& peer_address,
const btav_a2dp_codec_config_t& codec_user_config,
bool* p_restart_output) {
@@ -384,7 +392,7 @@
struct bta_av_get_a2dp_peer_current_codec {
static A2dpCodecConfig* return_value;
std::function<A2dpCodecConfig*(const RawAddress& peer_address)> body{
- [](const RawAddress& peer_address) { return return_value; }};
+ [](const RawAddress& /* peer_address */) { return return_value; }};
A2dpCodecConfig* operator()(const RawAddress& peer_address) {
return body(peer_address);
};
@@ -396,7 +404,7 @@
// Params: int fd
// Return: void
struct btif_a2dp_codec_debug_dump {
- std::function<void(int fd)> body{[](int fd) {}};
+ std::function<void(int fd)> body{[](int /* fd */) {}};
void operator()(int fd) { body(fd); };
};
extern struct btif_a2dp_codec_debug_dump btif_a2dp_codec_debug_dump;
diff --git a/system/test/mock/mock_btif_co_bta_dm_co.cc b/system/test/mock/mock_btif_co_bta_dm_co.cc
index 0437f45..d7ccf69 100644
--- a/system/test/mock/mock_btif_co_bta_dm_co.cc
+++ b/system/test/mock/mock_btif_co_bta_dm_co.cc
@@ -29,7 +29,8 @@
BTM_IO_CAP_UNKNOWN, BTM_BLE_INITIATOR_KEY_SIZE, BTM_BLE_RESPONDER_KEY_SIZE,
BTM_BLE_MAX_KEY_SIZE};
-bool bta_dm_co_get_compress_memory(tBTA_SYS_ID id, uint8_t** memory_p,
- uint32_t* memory_size) {
+bool bta_dm_co_get_compress_memory(tBTA_SYS_ID /* id */,
+ uint8_t** /* memory_p */,
+ uint32_t* /* memory_size */) {
return true;
}
diff --git a/system/test/mock/mock_btif_co_bta_hh_co.cc b/system/test/mock/mock_btif_co_bta_hh_co.cc
index 35c20ae..0fd0bc1 100644
--- a/system/test/mock/mock_btif_co_bta_hh_co.cc
+++ b/system/test/mock/mock_btif_co_bta_hh_co.cc
@@ -27,47 +27,52 @@
#include "test/common/mock_functions.h"
#include "types/raw_address.h"
-int bta_hh_co_write(int fd, uint8_t* rpt, uint16_t len) {
+int bta_hh_co_write(int /* fd */, uint8_t* /* rpt */, uint16_t /* len */) {
inc_func_call_count(__func__);
return 0;
}
-tBTA_HH_RPT_CACHE_ENTRY* bta_hh_le_co_cache_load(const RawAddress& remote_bda,
- uint8_t* p_num_rpt,
- uint8_t app_id) {
+tBTA_HH_RPT_CACHE_ENTRY* bta_hh_le_co_cache_load(
+ const tAclLinkSpec& /* link_spec */, uint8_t* /* p_num_rpt */,
+ uint8_t /* app_id */) {
inc_func_call_count(__func__);
return nullptr;
}
-void bta_hh_co_close(btif_hh_device_t* p_dev) { inc_func_call_count(__func__); }
-void bta_hh_co_data(uint8_t dev_handle, uint8_t* p_rpt, uint16_t len,
- tBTA_HH_PROTO_MODE mode, uint8_t sub_class,
- uint8_t ctry_code, const RawAddress& peer_addr,
- uint8_t app_id) {
+void bta_hh_co_close(btif_hh_device_t* /* p_dev */) {
inc_func_call_count(__func__);
}
-void bta_hh_co_get_rpt_rsp(uint8_t dev_handle, uint8_t status,
- const uint8_t* p_rpt, uint16_t len) {
+void bta_hh_co_data(uint8_t /* dev_handle */, uint8_t* /* p_rpt */,
+ uint16_t /* len */, tBTA_HH_PROTO_MODE /* mode */,
+ uint8_t /* sub_class */, uint8_t /* ctry_code */,
+ const tAclLinkSpec& /* link_spec */, uint8_t /* app_id */) {
inc_func_call_count(__func__);
}
-bool bta_hh_co_open(uint8_t dev_handle, uint8_t sub_class,
- tBTA_HH_ATTR_MASK attr_mask, uint8_t app_id) {
+void bta_hh_co_get_rpt_rsp(uint8_t /* dev_handle */, uint8_t /* status */,
+ const uint8_t* /* p_rpt */, uint16_t /* len */) {
+ inc_func_call_count(__func__);
+}
+bool bta_hh_co_open(uint8_t /* dev_handle */, uint8_t /* sub_class */,
+ tBTA_HH_ATTR_MASK /* attr_mask */, uint8_t /* app_id */) {
inc_func_call_count(__func__);
return true;
}
-void bta_hh_co_send_hid_info(btif_hh_device_t* p_dev, const char* dev_name,
- uint16_t vendor_id, uint16_t product_id,
- uint16_t version, uint8_t ctry_code, int dscp_len,
- uint8_t* p_dscp) {
+void bta_hh_co_send_hid_info(btif_hh_device_t* /* p_dev */,
+ const char* /* dev_name */,
+ uint16_t /* vendor_id */,
+ uint16_t /* product_id */, uint16_t /* version */,
+ uint8_t /* ctry_code */, int /* dscp_len */,
+ uint8_t* /* p_dscp */) {
inc_func_call_count(__func__);
}
-void bta_hh_co_set_rpt_rsp(uint8_t dev_handle, uint8_t status) {
+void bta_hh_co_set_rpt_rsp(uint8_t /* dev_handle */, uint8_t /* status */) {
inc_func_call_count(__func__);
}
-void bta_hh_le_co_reset_rpt_cache(const RawAddress& remote_bda,
- uint8_t app_id) {
+void bta_hh_le_co_reset_rpt_cache(const tAclLinkSpec& /* link_spec */,
+ uint8_t /* app_id */) {
inc_func_call_count(__func__);
}
-void bta_hh_le_co_rpt_info(const RawAddress& remote_bda,
- tBTA_HH_RPT_CACHE_ENTRY* p_entry, uint8_t app_id) {
+void bta_hh_le_co_rpt_info(const tAclLinkSpec& /* link_spec */,
+ tBTA_HH_RPT_CACHE_ENTRY* /* p_entry */,
+ uint8_t /* app_id */) {
inc_func_call_count(__func__);
}
-void uhid_set_non_blocking(int fd) { inc_func_call_count(__func__); }
+void uhid_set_non_blocking(int /* fd */) { inc_func_call_count(__func__); }
diff --git a/system/test/mock/mock_btif_config.h b/system/test/mock/mock_btif_config.h
index 78c1b21..68466fa 100644
--- a/system/test/mock/mock_btif_config.h
+++ b/system/test/mock/mock_btif_config.h
@@ -42,7 +42,9 @@
// Returns: bool
struct btif_get_device_clockoffset {
std::function<bool(const RawAddress& bda, int* p_clock_offset)> body{
- [](const RawAddress& bda, int* p_clock_offset) { return false; }};
+ [](const RawAddress& /* bda */, int* /* p_clock_offset */) {
+ return false;
+ }};
bool operator()(const RawAddress& bda, int* p_clock_offset) {
return body(bda, p_clock_offset);
};
@@ -52,7 +54,9 @@
// Returns: bool
struct btif_set_device_clockoffset {
std::function<bool(const RawAddress& bda, int clock_offset)> body{
- [](const RawAddress& bda, int clock_offset) { return false; }};
+ [](const RawAddress& /* bda */, int /* clock_offset */) {
+ return false;
+ }};
bool operator()(const RawAddress& bda, int clock_offset) {
return body(bda, clock_offset);
};
@@ -62,7 +66,9 @@
// Returns: bool
struct btif_config_exist {
std::function<bool(const std::string& section, const std::string& key)> body{
- [](const std::string& section, const std::string& key) { return false; }};
+ [](const std::string& /* section */, const std::string& /* key */) {
+ return false;
+ }};
bool operator()(const std::string& section, const std::string& key) {
return body(section, key);
};
@@ -74,9 +80,8 @@
struct btif_config_get_int {
std::function<bool(const std::string& section, const std::string& key,
int* value)>
- body{[](const std::string& section, const std::string& key, int* value) {
- return false;
- }};
+ body{[](const std::string& /* section */, const std::string& /* key */,
+ int* /* value */) { return false; }};
bool operator()(const std::string& section, const std::string& key,
int* value) {
return body(section, key, value);
@@ -89,9 +94,8 @@
struct btif_config_set_int {
std::function<bool(const std::string& section, const std::string& key,
int value)>
- body{[](const std::string& section, const std::string& key, int value) {
- return false;
- }};
+ body{[](const std::string& /* section */, const std::string& /* key */,
+ int /* value */) { return false; }};
bool operator()(const std::string& section, const std::string& key,
int value) {
return body(section, key, value);
@@ -104,8 +108,8 @@
struct btif_config_get_uint64 {
std::function<bool(const std::string& section, const std::string& key,
uint64_t* value)>
- body{[](const std::string& section, const std::string& key,
- uint64_t* value) { return false; }};
+ body{[](const std::string& /* section */, const std::string& /* key */,
+ uint64_t* /* value */) { return false; }};
bool operator()(const std::string& section, const std::string& key,
uint64_t* value) {
return body(section, key, value);
@@ -118,8 +122,8 @@
struct btif_config_set_uint64 {
std::function<bool(const std::string& section, const std::string& key,
uint64_t value)>
- body{[](const std::string& section, const std::string& key,
- uint64_t value) { return false; }};
+ body{[](const std::string& /* section */, const std::string& /* key */,
+ uint64_t /* value */) { return false; }};
bool operator()(const std::string& section, const std::string& key,
uint64_t value) {
return body(section, key, value);
@@ -132,8 +136,8 @@
struct btif_config_get_str {
std::function<bool(const std::string& section, const std::string& key,
char* value, int* size_bytes)>
- body{[](const std::string& section, const std::string& key, char* value,
- int* size_bytes) { return false; }};
+ body{[](const std::string& /* section */, const std::string& /* key */,
+ char* /* value */, int* /* size_bytes */) { return false; }};
bool operator()(const std::string& section, const std::string& key,
char* value, int* size_bytes) {
return body(section, key, value, size_bytes);
@@ -146,8 +150,8 @@
struct btif_config_set_str {
std::function<bool(const std::string& section, const std::string& key,
const std::string& value)>
- body{[](const std::string& section, const std::string& key,
- const std::string& value) { return false; }};
+ body{[](const std::string& /* section */, const std::string& /* key */,
+ const std::string& /* value */) { return false; }};
bool operator()(const std::string& section, const std::string& key,
const std::string& value) {
return body(section, key, value);
@@ -160,8 +164,8 @@
struct btif_config_get_bin {
std::function<bool(const std::string& section, const std::string& key,
uint8_t* value, size_t* length)>
- body{[](const std::string& section, const std::string& key,
- uint8_t* value, size_t* length) { return false; }};
+ body{[](const std::string& /* section */, const std::string& /* key */,
+ uint8_t* /* value */, size_t* /* length */) { return false; }};
bool operator()(const std::string& section, const std::string& key,
uint8_t* value, size_t* length) {
return body(section, key, value, length);
@@ -173,8 +177,9 @@
// Returns: size_t
struct btif_config_get_bin_length {
std::function<size_t(const std::string& section, const std::string& key)>
- body{
- [](const std::string& section, const std::string& key) { return 0; }};
+ body{[](const std::string& /* section */, const std::string& /* key */) {
+ return 0;
+ }};
size_t operator()(const std::string& section, const std::string& key) {
return body(section, key);
};
@@ -186,8 +191,9 @@
struct btif_config_set_bin {
std::function<bool(const std::string& section, const std::string& key,
const uint8_t* value, size_t length)>
- body{[](const std::string& section, const std::string& key,
- const uint8_t* value, size_t length) { return false; }};
+ body{[](const std::string& /* section */, const std::string& /* key */,
+ const uint8_t* /* value */,
+ size_t /* length */) { return false; }};
bool operator()(const std::string& section, const std::string& key,
const uint8_t* value, size_t length) {
return body(section, key, value, length);
@@ -209,7 +215,9 @@
// Returns: bool
struct btif_config_remove {
std::function<bool(const std::string& section, const std::string& key)> body{
- [](const std::string& section, const std::string& key) { return false; }};
+ [](const std::string& /* section */, const std::string& /* key */) {
+ return false;
+ }};
bool operator()(const std::string& section, const std::string& key) {
return body(section, key);
};
@@ -220,10 +228,8 @@
// Returns: void
struct btif_config_remove_device {
std::function<void(const std::string& section)> body{
- [](const std::string& section) { return; }};
- void operator()(const std::string& section) {
- return;
- };
+ [](const std::string& /* section */) { return; }};
+ void operator()(const std::string& /* section */) { return; };
};
extern struct btif_config_remove_device btif_config_remove_device;
// Name: btif_config_clear
@@ -238,7 +244,7 @@
// Params: int fd
// Returns: void
struct btif_debug_config_dump {
- std::function<void(int fd)> body{[](int fd) {}};
+ std::function<void(int fd)> body{[](int /* fd */) {}};
void operator()(int fd) { body(fd); };
};
extern struct btif_debug_config_dump btif_debug_config_dump;
diff --git a/system/test/mock/mock_btif_core.cc b/system/test/mock/mock_btif_core.cc
index bb625e3..7c90eab 100644
--- a/system/test/mock/mock_btif_core.cc
+++ b/system/test/mock/mock_btif_core.cc
@@ -26,7 +26,6 @@
#include "bta/include/bta_api.h"
#include "btif/include/btif_common.h"
#include "include/hardware/bluetooth.h"
-#include "test/common/jni_thread.h"
#include "test/common/mock_functions.h"
#include "types/raw_address.h"
@@ -34,11 +33,7 @@
inc_func_call_count(__func__);
return false;
}
-bool is_on_jni_thread() {
- inc_func_call_count(__func__);
- return false;
-}
-bt_property_t* property_deep_copy(const bt_property_t* prop) {
+bt_property_t* property_deep_copy(const bt_property_t* /* prop */) {
inc_func_call_count(__func__);
return nullptr;
}
@@ -50,27 +45,11 @@
inc_func_call_count(__func__);
return BT_STATUS_SUCCESS;
}
-bt_status_t btif_set_dynamic_audio_buffer_size(int codec, int size) {
+bt_status_t btif_set_dynamic_audio_buffer_size(int /* codec */,
+ int /* size */) {
inc_func_call_count(__func__);
return BT_STATUS_SUCCESS;
}
-bt_status_t btif_transfer_context(tBTIF_CBACK* p_cback, uint16_t event,
- char* p_params, int param_len,
- tBTIF_COPY_CBACK* p_copy_cback) {
- inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
-}
-bt_status_t do_in_jni_thread(base::OnceClosure task) {
- inc_func_call_count(__func__);
- do_in_jni_thread_task_queue.push(std::move(task));
- return BT_STATUS_SUCCESS;
-}
-bt_status_t do_in_jni_thread(const base::Location& from_here,
- base::OnceClosure task) {
- inc_func_call_count(__func__);
- do_in_jni_thread_task_queue.push(std::move(task));
- return BT_STATUS_SUCCESS;
-}
int btif_is_enabled(void) {
inc_func_call_count(__func__);
return 0;
@@ -79,41 +58,47 @@
inc_func_call_count(__func__);
return 0;
}
-void btif_adapter_properties_evt(bt_status_t status, uint32_t num_props,
- bt_property_t* p_props) {
+void btif_adapter_properties_evt(bt_status_t /* status */,
+ uint32_t /* num_props */,
+ bt_property_t* /* p_props */) {
inc_func_call_count(__func__);
}
-void btif_disable_service(tBTA_SERVICE_ID service_id) {
+void btif_disable_service(tBTA_SERVICE_ID /* service_id */) {
inc_func_call_count(__func__);
}
-void btif_dut_mode_configure(uint8_t enable) { inc_func_call_count(__func__); }
-void btif_dut_mode_send(uint16_t opcode, uint8_t* buf, uint8_t len) {
+void btif_dut_mode_configure(uint8_t /* enable */) {
+ inc_func_call_count(__func__);
+}
+void btif_dut_mode_send(uint16_t /* opcode */, uint8_t* /* buf */,
+ uint8_t /* len */) {
inc_func_call_count(__func__);
}
void btif_enable_bluetooth_evt() { inc_func_call_count(__func__); }
-void btif_enable_service(tBTA_SERVICE_ID service_id) {
+void btif_enable_service(tBTA_SERVICE_ID /* service_id */) {
inc_func_call_count(__func__);
}
void btif_get_adapter_properties(void) { inc_func_call_count(__func__); }
-void btif_get_adapter_property(bt_property_type_t type) {
+void btif_get_adapter_property(bt_property_type_t /* type */) {
inc_func_call_count(__func__);
}
-void btif_get_remote_device_properties(RawAddress remote_addr) {
+void btif_get_remote_device_properties(RawAddress /* remote_addr */) {
inc_func_call_count(__func__);
}
-void btif_get_remote_device_property(RawAddress remote_addr,
- bt_property_type_t type) {
+void btif_get_remote_device_property(RawAddress /* remote_addr */,
+ bt_property_type_t /* type */) {
inc_func_call_count(__func__);
}
void btif_init_ok() { inc_func_call_count(__func__); }
-void btif_remote_properties_evt(bt_status_t status, RawAddress* remote_addr,
- uint32_t num_props, bt_property_t* p_props) {
+void btif_remote_properties_evt(bt_status_t /* status */,
+ RawAddress* /* remote_addr */,
+ uint32_t /* num_props */,
+ bt_property_t* /* p_props */) {
inc_func_call_count(__func__);
}
-void btif_set_adapter_property(bt_property_t* property) {
+void btif_set_adapter_property(bt_property_t* /* property */) {
inc_func_call_count(__func__);
}
-void btif_set_remote_device_property(RawAddress* remote_addr,
- bt_property_t* property) {
+void btif_set_remote_device_property(RawAddress* /* remote_addr */,
+ bt_property_t* /* property */) {
inc_func_call_count(__func__);
}
diff --git a/system/test/mock/mock_btif_debug_conn.cc b/system/test/mock/mock_btif_debug_conn.cc
index 1427ffd..666e8a8 100644
--- a/system/test/mock/mock_btif_debug_conn.cc
+++ b/system/test/mock/mock_btif_debug_conn.cc
@@ -24,9 +24,9 @@
#include "test/common/mock_functions.h"
#include "types/raw_address.h"
-void btif_debug_conn_dump(int fd) { inc_func_call_count(__func__); }
-void btif_debug_conn_state(const RawAddress& bda,
- const btif_debug_conn_state_t state,
- const tGATT_DISCONN_REASON disconnect_reason) {
+void btif_debug_conn_dump(int /* fd */) { inc_func_call_count(__func__); }
+void btif_debug_conn_state(const RawAddress& /* bda */,
+ const btif_debug_conn_state_t /* state */,
+ const tGATT_DISCONN_REASON /* disconnect_reason */) {
inc_func_call_count(__func__);
}
diff --git a/system/test/mock/mock_btif_dm.cc b/system/test/mock/mock_btif_dm.cc
index 079da25..26bca64 100644
--- a/system/test/mock/mock_btif_dm.cc
+++ b/system/test/mock/mock_btif_dm.cc
@@ -36,136 +36,147 @@
inc_func_call_count(__func__);
return false;
}
-bool check_cod(const RawAddress* remote_bdaddr, uint32_t cod) {
+bool check_cod(const RawAddress* /* remote_bdaddr */, uint32_t /* cod */) {
inc_func_call_count(__func__);
return false;
}
-bool check_cod_hid(const RawAddress* remote_bdaddr) {
+bool check_cod_hid(const RawAddress* /* remote_bdaddr */) {
inc_func_call_count(__func__);
return false;
}
-bool check_cod_hid(const RawAddress& remote_bdaddr) {
+bool check_cod_hid(const RawAddress& /* remote_bdaddr */) {
inc_func_call_count(__func__);
return false;
}
-bool is_device_le_audio_capable(const RawAddress bd_addr) {
+bool is_device_le_audio_capable(const RawAddress /* bd_addr */) {
inc_func_call_count(__func__);
return false;
}
-uint16_t btif_dm_get_connection_state(const RawAddress& bd_addr) {
+uint16_t btif_dm_get_connection_state(const RawAddress& /* bd_addr */) {
inc_func_call_count(__func__);
return 0;
}
void BTIF_dm_disable() { inc_func_call_count(__func__); }
void BTIF_dm_enable() { inc_func_call_count(__func__); }
-void BTIF_dm_report_inquiry_status_change(tBTM_INQUIRY_STATE state) {
+void BTIF_dm_report_inquiry_status_change(tBTM_INQUIRY_STATE /* state */) {
inc_func_call_count(__func__);
}
-void btif_dm_sec_evt(tBTA_DM_SEC_EVT event, tBTA_DM_SEC* p_data) {
+void btif_dm_sec_evt(tBTA_DM_SEC_EVT /* event */, tBTA_DM_SEC* /* p_data */) {
inc_func_call_count(__func__);
}
-void btif_ble_receiver_test(uint8_t rx_freq) { inc_func_call_count(__func__); }
+void btif_ble_receiver_test(uint8_t /* rx_freq */) {
+ inc_func_call_count(__func__);
+}
void btif_ble_test_end() { inc_func_call_count(__func__); }
-void btif_ble_transmitter_test(uint8_t tx_freq, uint8_t test_data_len,
- uint8_t packet_payload) {
+void btif_ble_transmitter_test(uint8_t /* tx_freq */,
+ uint8_t /* test_data_len */,
+ uint8_t /* packet_payload */) {
inc_func_call_count(__func__);
}
-void btif_debug_bond_event_dump(int fd) { inc_func_call_count(__func__); }
-void btif_dm_ble_sec_req_evt(tBTA_DM_BLE_SEC_REQ* p_ble_req, bool is_consent) {
+void btif_debug_bond_event_dump(int /* fd */) { inc_func_call_count(__func__); }
+void btif_dm_ble_sec_req_evt(tBTA_DM_BLE_SEC_REQ* /* p_ble_req */,
+ bool /* is_consent */) {
inc_func_call_count(__func__);
}
-void btif_dm_cancel_bond(const RawAddress bd_addr) {
+void btif_dm_cancel_bond(const RawAddress /* bd_addr */) {
inc_func_call_count(__func__);
}
void btif_dm_cancel_discovery(void) { inc_func_call_count(__func__); }
void btif_dm_cleanup(void) { inc_func_call_count(__func__); }
-void btif_dm_create_bond(const RawAddress bd_addr, int transport) {
+void btif_dm_create_bond(const RawAddress /* bd_addr */, int /* transport */) {
inc_func_call_count(__func__);
}
-void btif_dm_create_bond_le(const RawAddress bd_addr,
- tBLE_ADDR_TYPE addr_type) {
+void btif_dm_create_bond_le(const RawAddress /* bd_addr */,
+ tBLE_ADDR_TYPE /* addr_type */) {
inc_func_call_count(__func__);
}
-void btif_dm_create_bond_out_of_band(const RawAddress bd_addr, int transport,
- const bt_oob_data_t p192_data,
- const bt_oob_data_t p256_data) {
+void btif_dm_create_bond_out_of_band(const RawAddress /* bd_addr */,
+ int /* transport */,
+ const bt_oob_data_t /* p192_data */,
+ const bt_oob_data_t /* p256_data */) {
inc_func_call_count(__func__);
}
-void btif_dm_enable_service(tBTA_SERVICE_ID service_id, bool enable) {
+void btif_dm_enable_service(tBTA_SERVICE_ID /* service_id */,
+ bool /* enable */) {
inc_func_call_count(__func__);
}
-void btif_dm_get_ble_local_keys(tBTA_DM_BLE_LOCAL_KEY_MASK* p_key_mask,
- Octet16* p_er,
- tBTA_BLE_LOCAL_ID_KEYS* p_id_keys) {
+void btif_dm_get_ble_local_keys(tBTA_DM_BLE_LOCAL_KEY_MASK* /* p_key_mask */,
+ Octet16* /* p_er */,
+ tBTA_BLE_LOCAL_ID_KEYS* /* p_id_keys */) {
inc_func_call_count(__func__);
}
-void btif_dm_get_remote_services(RawAddress remote_addr, const int transport) {
+void btif_dm_get_remote_services(RawAddress /* remote_addr */,
+ const int /* transport */) {
inc_func_call_count(__func__);
}
-void btif_dm_hh_open_failed(RawAddress* bdaddr) {
+void btif_dm_hh_open_failed(RawAddress* /* bdaddr */) {
inc_func_call_count(__func__);
}
-void btif_dm_init(uid_set_t* set) { inc_func_call_count(__func__); }
-void btif_dm_get_local_class_of_device(DEV_CLASS device_class) {
+void btif_dm_init(uid_set_t* /* set */) { inc_func_call_count(__func__); }
+void btif_dm_get_local_class_of_device(DEV_CLASS /* device_class */) {
inc_func_call_count(__func__);
}
void btif_dm_load_ble_local_keys(void) { inc_func_call_count(__func__); }
void btif_dm_on_disable() { inc_func_call_count(__func__); }
-void btif_dm_pin_reply(const RawAddress bd_addr, uint8_t accept,
- uint8_t pin_len, bt_pin_code_t pin_code) {
+void btif_dm_pin_reply(const RawAddress /* bd_addr */, uint8_t /* accept */,
+ uint8_t /* pin_len */, bt_pin_code_t /* pin_code */) {
inc_func_call_count(__func__);
}
-void btif_dm_proc_io_req(tBTM_AUTH_REQ* p_auth_req, bool is_orig) {
+void btif_dm_proc_io_req(tBTM_AUTH_REQ* /* p_auth_req */, bool /* is_orig */) {
inc_func_call_count(__func__);
}
-void btif_dm_proc_io_rsp(const RawAddress& bd_addr, tBTM_IO_CAP io_cap,
- tBTM_OOB_DATA oob_data, tBTM_AUTH_REQ auth_req) {
+void btif_dm_proc_io_rsp(const RawAddress& /* bd_addr */,
+ tBTM_IO_CAP /* io_cap */, tBTM_OOB_DATA /* oob_data */,
+ tBTM_AUTH_REQ /* auth_req */) {
inc_func_call_count(__func__);
}
void btif_dm_read_energy_info() { inc_func_call_count(__func__); }
void btif_dm_remove_ble_bonding_keys(void) { inc_func_call_count(__func__); }
-void btif_dm_remove_bond(const RawAddress bd_addr) {
+void btif_dm_remove_bond(const RawAddress /* bd_addr */) {
inc_func_call_count(__func__);
}
-void btif_dm_set_oob_for_io_req(tBTM_OOB_DATA* p_has_oob_data) {
+void btif_dm_set_oob_for_io_req(tBTM_OOB_DATA* /* p_has_oob_data */) {
inc_func_call_count(__func__);
}
-void btif_dm_set_oob_for_le_io_req(const RawAddress& bd_addr,
- tBTM_OOB_DATA* p_has_oob_data,
- tBTM_LE_AUTH_REQ* p_auth_req) {
+void btif_dm_set_oob_for_le_io_req(const RawAddress& /* bd_addr */,
+ tBTM_OOB_DATA* /* p_has_oob_data */,
+ tBTM_LE_AUTH_REQ* /* p_auth_req */) {
inc_func_call_count(__func__);
}
-void btif_dm_ssp_reply(const RawAddress bd_addr, bt_ssp_variant_t variant,
- uint8_t accept) {
+void btif_dm_ssp_reply(const RawAddress /* bd_addr */,
+ bt_ssp_variant_t /* variant */, uint8_t /* accept */) {
inc_func_call_count(__func__);
}
void btif_dm_start_discovery(void) { inc_func_call_count(__func__); }
-void btif_dm_update_ble_remote_properties(const RawAddress& bd_addr,
- BD_NAME bd_name, DEV_CLASS dev_class,
- tBT_DEVICE_TYPE dev_type) {
+void btif_dm_update_ble_remote_properties(const RawAddress& /* bd_addr */,
+ BD_NAME /* bd_name */,
+ DEV_CLASS /* dev_class */,
+ tBT_DEVICE_TYPE /* dev_type */) {
inc_func_call_count(__func__);
}
-bool btif_dm_get_smp_config(tBTE_APPL_CFG* p_cfg) {
+bool btif_dm_get_smp_config(tBTE_APPL_CFG* /* p_cfg */) {
inc_func_call_count(__func__);
return true;
}
-bool btif_dm_proc_rmt_oob(const RawAddress& bd_addr, Octet16* p_c,
- Octet16* p_r) {
+bool btif_dm_proc_rmt_oob(const RawAddress& /* bd_addr */, Octet16* /* p_c */,
+ Octet16* /* p_r */) {
inc_func_call_count(__func__);
return false;
}
-void btif_dm_proc_loc_oob(tBT_TRANSPORT transport, bool is_valid,
- const Octet16& c, const Octet16& r) {
+void btif_dm_proc_loc_oob(tBT_TRANSPORT /* transport */, bool /* is_valid */,
+ const Octet16& /* c */, const Octet16& /* r */) {
inc_func_call_count(__func__);
}
-bool btif_get_device_type(const RawAddress& bda, int* p_device_type) {
+bool btif_get_device_type(const RawAddress& /* bda */,
+ int* /* p_device_type */) {
inc_func_call_count(__func__);
return false;
}
-bool btif_get_address_type(const RawAddress& bda, tBLE_ADDR_TYPE* p_addr_type) {
+bool btif_get_address_type(const RawAddress& /* bda */,
+ tBLE_ADDR_TYPE* /* p_addr_type */) {
inc_func_call_count(__func__);
return false;
}
diff --git a/system/test/mock/mock_btif_hf.cc b/system/test/mock/mock_btif_hf.cc
index 1bc7efb..e49f8f0 100644
--- a/system/test/mock/mock_btif_hf.cc
+++ b/system/test/mock/mock_btif_hf.cc
@@ -23,8 +23,6 @@
// Mock include file to share data between tests and mock
#include "test/mock/mock_btif_hf.h"
-#include <cstdint>
-
#include "test/common/mock_functions.h"
// Original usings
diff --git a/system/test/mock/mock_btif_hf.h b/system/test/mock/mock_btif_hf.h
index 1921f42..92c8bff 100644
--- a/system/test/mock/mock_btif_hf.h
+++ b/system/test/mock/mock_btif_hf.h
@@ -22,7 +22,6 @@
* mockcify.pl ver 0.7.0
*/
-#include <cstdint>
#include <functional>
#include "include/hardware/bluetooth_headset_interface.h"
@@ -59,4 +58,4 @@
} // namespace mock
} // namespace test
-// END mockcify generation
\ No newline at end of file
+// END mockcify generation
diff --git a/system/test/mock/mock_btif_profile_queue.h b/system/test/mock/mock_btif_profile_queue.h
index 7576690..fd1635d 100644
--- a/system/test/mock/mock_btif_profile_queue.h
+++ b/system/test/mock/mock_btif_profile_queue.h
@@ -51,7 +51,7 @@
// Params: uint16_t uuid
// Return: void
struct btif_queue_cleanup {
- std::function<void(uint16_t uuid)> body{[](uint16_t uuid) {}};
+ std::function<void(uint16_t uuid)> body{[](uint16_t /* uuid */) {}};
void operator()(uint16_t uuid) { body(uuid); };
};
extern struct btif_queue_cleanup btif_queue_cleanup;
@@ -63,8 +63,8 @@
static bt_status_t return_value;
std::function<bt_status_t(uint16_t uuid, const RawAddress* bda,
btif_connect_cb_t connect_cb)>
- body{[](uint16_t uuid, const RawAddress* bda,
- btif_connect_cb_t connect_cb) { return return_value; }};
+ body{[](uint16_t /* uuid */, const RawAddress* /* bda */,
+ btif_connect_cb_t /* connect_cb */) { return return_value; }};
bt_status_t operator()(uint16_t uuid, const RawAddress* bda,
btif_connect_cb_t connect_cb) {
return body(uuid, bda, connect_cb);
diff --git a/system/test/mock/mock_btif_profile_storage.cc b/system/test/mock/mock_btif_profile_storage.cc
new file mode 100644
index 0000000..1390f39
--- /dev/null
+++ b/system/test/mock/mock_btif_profile_storage.cc
@@ -0,0 +1,341 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/*
+ * Generated mock file from original source file
+ * Functions generated:40
+ *
+ * mockcify.pl ver 0.7.0
+ */
+
+// Mock include file to share data between tests and mock
+#include "test/mock/mock_btif_profile_storage.h"
+
+#include <cstdint>
+
+#include "test/common/mock_functions.h"
+
+// Original usings
+using bluetooth::Uuid;
+
+// Mocked internal structures, if any
+
+namespace test {
+namespace mock {
+namespace btif_profile_storage {
+
+// Function state capture and return values, if needed
+struct btif_storage_add_groups btif_storage_add_groups;
+struct btif_storage_add_hearing_aid btif_storage_add_hearing_aid;
+struct btif_storage_add_hid_device_info btif_storage_add_hid_device_info;
+struct btif_storage_add_leaudio_has_device btif_storage_add_leaudio_has_device;
+struct btif_storage_get_hearing_aid_prop btif_storage_get_hearing_aid_prop;
+struct btif_storage_get_le_hid_devices btif_storage_get_le_hid_devices;
+struct btif_storage_get_leaudio_has_features
+ btif_storage_get_leaudio_has_features;
+struct btif_storage_get_leaudio_has_presets
+ btif_storage_get_leaudio_has_presets;
+struct btif_storage_get_wake_capable_classic_hid_devices
+ btif_storage_get_wake_capable_classic_hid_devices;
+struct btif_storage_is_pce_version_102 btif_storage_is_pce_version_102;
+struct btif_storage_leaudio_clear_service_data
+ btif_storage_leaudio_clear_service_data;
+struct btif_storage_leaudio_update_ase_bin btif_storage_leaudio_update_ase_bin;
+struct btif_storage_leaudio_update_handles_bin
+ btif_storage_leaudio_update_handles_bin;
+struct btif_storage_leaudio_update_pacs_bin
+ btif_storage_leaudio_update_pacs_bin;
+struct btif_storage_load_bonded_csis_devices
+ btif_storage_load_bonded_csis_devices;
+struct btif_storage_load_bonded_groups btif_storage_load_bonded_groups;
+struct btif_storage_load_bonded_hearing_aids
+ btif_storage_load_bonded_hearing_aids;
+struct btif_storage_load_bonded_hid_info btif_storage_load_bonded_hid_info;
+struct btif_storage_load_bonded_leaudio btif_storage_load_bonded_leaudio;
+struct btif_storage_load_bonded_leaudio_has_devices
+ btif_storage_load_bonded_leaudio_has_devices;
+struct btif_storage_load_bonded_volume_control_devices
+ btif_storage_load_bonded_volume_control_devices;
+struct btif_storage_load_hidd btif_storage_load_hidd;
+struct btif_storage_remove_csis_device btif_storage_remove_csis_device;
+struct btif_storage_remove_groups btif_storage_remove_groups;
+struct btif_storage_remove_hearing_aid btif_storage_remove_hearing_aid;
+struct btif_storage_remove_hid_info btif_storage_remove_hid_info;
+struct btif_storage_remove_hidd btif_storage_remove_hidd;
+struct btif_storage_remove_leaudio btif_storage_remove_leaudio;
+struct btif_storage_remove_leaudio_has btif_storage_remove_leaudio_has;
+struct btif_storage_set_hearing_aid_acceptlist
+ btif_storage_set_hearing_aid_acceptlist;
+struct btif_storage_set_hidd btif_storage_set_hidd;
+struct btif_storage_set_leaudio_audio_location
+ btif_storage_set_leaudio_audio_location;
+struct btif_storage_set_leaudio_autoconnect
+ btif_storage_set_leaudio_autoconnect;
+struct btif_storage_set_leaudio_has_acceptlist
+ btif_storage_set_leaudio_has_acceptlist;
+struct btif_storage_set_leaudio_has_active_preset
+ btif_storage_set_leaudio_has_active_preset;
+struct btif_storage_set_leaudio_has_features
+ btif_storage_set_leaudio_has_features;
+struct btif_storage_set_leaudio_has_presets
+ btif_storage_set_leaudio_has_presets;
+struct btif_storage_set_leaudio_supported_context_types
+ btif_storage_set_leaudio_supported_context_types;
+struct btif_storage_set_pce_profile_version
+ btif_storage_set_pce_profile_version;
+struct btif_storage_update_csis_info btif_storage_update_csis_info;
+
+} // namespace btif_profile_storage
+} // namespace mock
+} // namespace test
+
+// Mocked function return values, if any
+namespace test {
+namespace mock {
+namespace btif_profile_storage {
+
+bt_status_t btif_storage_add_hid_device_info::return_value = BT_STATUS_SUCCESS;
+bool btif_storage_get_hearing_aid_prop::return_value = false;
+std::vector<std::pair<RawAddress, uint8_t>>
+ btif_storage_get_le_hid_devices::return_value = {};
+bool btif_storage_get_leaudio_has_features::return_value = false;
+bool btif_storage_get_leaudio_has_presets::return_value = false;
+std::vector<RawAddress>
+ btif_storage_get_wake_capable_classic_hid_devices::return_value = {};
+bool btif_storage_is_pce_version_102::return_value = false;
+bt_status_t btif_storage_load_bonded_hid_info::return_value = BT_STATUS_SUCCESS;
+bt_status_t btif_storage_load_hidd::return_value = BT_STATUS_SUCCESS;
+bt_status_t btif_storage_remove_hid_info::return_value = BT_STATUS_SUCCESS;
+bt_status_t btif_storage_remove_hidd::return_value = BT_STATUS_SUCCESS;
+bt_status_t btif_storage_set_hidd::return_value = BT_STATUS_SUCCESS;
+
+} // namespace btif_profile_storage
+} // namespace mock
+} // namespace test
+
+// Mocked functions, if any
+void btif_storage_add_groups(const RawAddress& addr) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_add_groups(addr);
+}
+void btif_storage_add_hearing_aid(const HearingDevice& dev_info) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_add_hearing_aid(dev_info);
+}
+bt_status_t btif_storage_add_hid_device_info(
+ RawAddress* remote_bd_addr, uint16_t attr_mask, uint8_t sub_class,
+ uint8_t app_id, uint16_t vendor_id, uint16_t product_id, uint16_t version,
+ uint8_t ctry_code, uint16_t ssr_max_latency, uint16_t ssr_min_tout,
+ uint16_t dl_len, uint8_t* dsc_list) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_profile_storage::btif_storage_add_hid_device_info(
+ remote_bd_addr, attr_mask, sub_class, app_id, vendor_id, product_id,
+ version, ctry_code, ssr_max_latency, ssr_min_tout, dl_len, dsc_list);
+}
+void btif_storage_add_leaudio_has_device(const RawAddress& address,
+ std::vector<uint8_t> presets_bin,
+ uint8_t features,
+ uint8_t active_preset) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_add_leaudio_has_device(
+ address, presets_bin, features, active_preset);
+}
+bool btif_storage_get_hearing_aid_prop(
+ const RawAddress& address, uint8_t* capabilities, uint64_t* hi_sync_id,
+ uint16_t* render_delay, uint16_t* preparation_delay, uint16_t* codecs) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_profile_storage::btif_storage_get_hearing_aid_prop(
+ address, capabilities, hi_sync_id, render_delay, preparation_delay,
+ codecs);
+}
+std::vector<std::pair<RawAddress, uint8_t>> btif_storage_get_le_hid_devices(
+ void) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_profile_storage::btif_storage_get_le_hid_devices();
+}
+bool btif_storage_get_leaudio_has_features(const RawAddress& address,
+ uint8_t& features) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_profile_storage::
+ btif_storage_get_leaudio_has_features(address, features);
+}
+bool btif_storage_get_leaudio_has_presets(const RawAddress& address,
+ std::vector<uint8_t>& presets_bin,
+ uint8_t& active_preset) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_profile_storage::btif_storage_get_leaudio_has_presets(
+ address, presets_bin, active_preset);
+}
+std::vector<RawAddress> btif_storage_get_wake_capable_classic_hid_devices(
+ void) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_profile_storage::
+ btif_storage_get_wake_capable_classic_hid_devices();
+}
+bool btif_storage_is_pce_version_102(const RawAddress& remote_bd_addr) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_profile_storage::btif_storage_is_pce_version_102(
+ remote_bd_addr);
+}
+void btif_storage_leaudio_clear_service_data(const RawAddress& address) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_leaudio_clear_service_data(
+ address);
+}
+void btif_storage_leaudio_update_ase_bin(const RawAddress& addr) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_leaudio_update_ase_bin(addr);
+}
+void btif_storage_leaudio_update_handles_bin(const RawAddress& addr) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_leaudio_update_handles_bin(
+ addr);
+}
+void btif_storage_leaudio_update_pacs_bin(const RawAddress& addr) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_leaudio_update_pacs_bin(addr);
+}
+void btif_storage_load_bonded_csis_devices(void) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_load_bonded_csis_devices();
+}
+void btif_storage_load_bonded_groups(void) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_load_bonded_groups();
+}
+void btif_storage_load_bonded_hearing_aids() {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_load_bonded_hearing_aids();
+}
+bt_status_t btif_storage_load_bonded_hid_info(void) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_profile_storage::btif_storage_load_bonded_hid_info();
+}
+void btif_storage_load_bonded_leaudio() {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_load_bonded_leaudio();
+}
+void btif_storage_load_bonded_leaudio_has_devices() {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::
+ btif_storage_load_bonded_leaudio_has_devices();
+}
+void btif_storage_load_bonded_volume_control_devices(void) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::
+ btif_storage_load_bonded_volume_control_devices();
+}
+bt_status_t btif_storage_load_hidd(void) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_profile_storage::btif_storage_load_hidd();
+}
+void btif_storage_remove_csis_device(const RawAddress& address) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_remove_csis_device(address);
+}
+void btif_storage_remove_groups(const RawAddress& address) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_remove_groups(address);
+}
+void btif_storage_remove_hearing_aid(const RawAddress& address) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_remove_hearing_aid(address);
+}
+bt_status_t btif_storage_remove_hid_info(const RawAddress& remote_bd_addr) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_profile_storage::btif_storage_remove_hid_info(
+ remote_bd_addr);
+}
+bt_status_t btif_storage_remove_hidd(RawAddress* remote_bd_addr) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_profile_storage::btif_storage_remove_hidd(
+ remote_bd_addr);
+}
+void btif_storage_remove_leaudio(const RawAddress& address) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_remove_leaudio(address);
+}
+void btif_storage_remove_leaudio_has(const RawAddress& address) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_remove_leaudio_has(address);
+}
+void btif_storage_set_hearing_aid_acceptlist(const RawAddress& address,
+ bool add_to_acceptlist) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_set_hearing_aid_acceptlist(
+ address, add_to_acceptlist);
+}
+bt_status_t btif_storage_set_hidd(const RawAddress& remote_bd_addr) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_profile_storage::btif_storage_set_hidd(
+ remote_bd_addr);
+}
+void btif_storage_set_leaudio_audio_location(const RawAddress& addr,
+ uint32_t sink_location,
+ uint32_t source_location) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_set_leaudio_audio_location(
+ addr, sink_location, source_location);
+}
+void btif_storage_set_leaudio_autoconnect(const RawAddress& addr,
+ bool autoconnect) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_set_leaudio_autoconnect(
+ addr, autoconnect);
+}
+void btif_storage_set_leaudio_has_acceptlist(const RawAddress& address,
+ bool add_to_acceptlist) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_set_leaudio_has_acceptlist(
+ address, add_to_acceptlist);
+}
+void btif_storage_set_leaudio_has_active_preset(const RawAddress& address,
+ uint8_t active_preset) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_set_leaudio_has_active_preset(
+ address, active_preset);
+}
+void btif_storage_set_leaudio_has_features(const RawAddress& address,
+ uint8_t features) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_set_leaudio_has_features(
+ address, features);
+}
+void btif_storage_set_leaudio_has_presets(const RawAddress& address,
+ std::vector<uint8_t> presets_bin) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_set_leaudio_has_presets(
+ address, presets_bin);
+}
+void btif_storage_set_leaudio_supported_context_types(
+ const RawAddress& addr, uint16_t sink_supported_context_type,
+ uint16_t source_supported_context_type) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::
+ btif_storage_set_leaudio_supported_context_types(
+ addr, sink_supported_context_type, source_supported_context_type);
+}
+void btif_storage_set_pce_profile_version(const RawAddress& remote_bd_addr,
+ uint16_t peer_pce_version) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_set_pce_profile_version(
+ remote_bd_addr, peer_pce_version);
+}
+void btif_storage_update_csis_info(const RawAddress& addr) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_update_csis_info(addr);
+}
+// Mocked functions complete
+// END mockcify generation
diff --git a/system/test/mock/mock_btif_profile_storage.h b/system/test/mock/mock_btif_profile_storage.h
new file mode 100644
index 0000000..66e61ae
--- /dev/null
+++ b/system/test/mock/mock_btif_profile_storage.h
@@ -0,0 +1,574 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+/*
+ * Generated mock file from original source file
+ * Functions generated:40
+ *
+ * mockcify.pl ver 0.7.0
+ */
+
+#include <cstdint>
+#include <functional>
+
+// Original included files, if any
+// NOTE: Since this is a mock file with mock definitions some number of
+// include files may not be required. The include-what-you-use
+// still applies, but crafting proper inclusion is out of scope
+// for this effort. This compilation unit may compile as-is, or
+// may need attention to prune from (or add to ) the inclusion set.
+#include <alloca.h>
+#include <base/logging.h>
+#include <stdlib.h>
+
+#include <vector>
+
+#include "bta/include/bta_hearing_aid_api.h"
+#include "types/bluetooth/uuid.h"
+#include "types/raw_address.h"
+
+// Original usings
+using bluetooth::Uuid;
+
+// Mocked compile conditionals, if any
+
+namespace test {
+namespace mock {
+namespace btif_profile_storage {
+
+// Shared state between mocked functions and tests
+// Name: btif_storage_add_groups
+// Params: const RawAddress& addr
+// Return: void
+struct btif_storage_add_groups {
+ std::function<void(const RawAddress& addr)> body{
+ [](const RawAddress& /* addr */) {}};
+ void operator()(const RawAddress& addr) { body(addr); };
+};
+extern struct btif_storage_add_groups btif_storage_add_groups;
+
+// Name: btif_storage_add_hearing_aid
+// Params: const HearingDevice& dev_info
+// Return: void
+struct btif_storage_add_hearing_aid {
+ std::function<void(const HearingDevice& dev_info)> body{
+ [](const HearingDevice& /* dev_info */) {}};
+ void operator()(const HearingDevice& dev_info) { body(dev_info); };
+};
+extern struct btif_storage_add_hearing_aid btif_storage_add_hearing_aid;
+
+// Name: btif_storage_add_hid_device_info
+// Params: RawAddress* remote_bd_addr, uint16_t attr_mask, uint8_t sub_class,
+// uint8_t app_id, uint16_t vendor_id, uint16_t product_id, uint16_t version,
+// uint8_t ctry_code, uint16_t ssr_max_latency, uint16_t ssr_min_tout, uint16_t
+// dl_len, uint8_t* dsc_list Return: bt_status_t
+struct btif_storage_add_hid_device_info {
+ static bt_status_t return_value;
+ std::function<bt_status_t(
+ RawAddress* remote_bd_addr, uint16_t attr_mask, uint8_t sub_class,
+ uint8_t app_id, uint16_t vendor_id, uint16_t product_id, uint16_t version,
+ uint8_t ctry_code, uint16_t ssr_max_latency, uint16_t ssr_min_tout,
+ uint16_t dl_len, uint8_t* dsc_list)>
+ body{[](RawAddress* /* remote_bd_addr */, uint16_t /* attr_mask */,
+ uint8_t /* sub_class */, uint8_t /* app_id */,
+ uint16_t /* vendor_id */, uint16_t /* product_id */,
+ uint16_t /* version */, uint8_t /* ctry_code */,
+ uint16_t /* ssr_max_latency */, uint16_t /* ssr_min_tout */,
+ uint16_t /* dl_len */,
+ uint8_t* /* dsc_list */) { return return_value; }};
+ bt_status_t operator()(RawAddress* remote_bd_addr, uint16_t attr_mask,
+ uint8_t sub_class, uint8_t app_id, uint16_t vendor_id,
+ uint16_t product_id, uint16_t version,
+ uint8_t ctry_code, uint16_t ssr_max_latency,
+ uint16_t ssr_min_tout, uint16_t dl_len,
+ uint8_t* dsc_list) {
+ return body(remote_bd_addr, attr_mask, sub_class, app_id, vendor_id,
+ product_id, version, ctry_code, ssr_max_latency, ssr_min_tout,
+ dl_len, dsc_list);
+ };
+};
+extern struct btif_storage_add_hid_device_info btif_storage_add_hid_device_info;
+
+// Name: btif_storage_add_leaudio_has_device
+// Params: const RawAddress& address, std::vector<uint8_t> presets_bin, uint8_t
+// features, uint8_t active_preset Return: void
+struct btif_storage_add_leaudio_has_device {
+ std::function<void(const RawAddress& address,
+ std::vector<uint8_t> presets_bin, uint8_t features,
+ uint8_t active_preset)>
+ body{[](const RawAddress& /* address */,
+ std::vector<uint8_t> /* presets_bin */, uint8_t /* features */,
+ uint8_t /* active_preset */) {}};
+ void operator()(const RawAddress& address, std::vector<uint8_t> presets_bin,
+ uint8_t features, uint8_t active_preset) {
+ body(address, presets_bin, features, active_preset);
+ };
+};
+extern struct btif_storage_add_leaudio_has_device
+ btif_storage_add_leaudio_has_device;
+
+// Name: btif_storage_get_hearing_aid_prop
+// Params: const RawAddress& address, uint8_t* capabilities, uint64_t*
+// hi_sync_id, uint16_t* render_delay, uint16_t* preparation_delay, uint16_t*
+// codecs Return: bool
+struct btif_storage_get_hearing_aid_prop {
+ static bool return_value;
+ std::function<bool(const RawAddress& address, uint8_t* capabilities,
+ uint64_t* hi_sync_id, uint16_t* render_delay,
+ uint16_t* preparation_delay, uint16_t* codecs)>
+ body{[](const RawAddress& /* address */, uint8_t* /* capabilities */,
+ uint64_t* /* hi_sync_id */, uint16_t* /* render_delay */,
+ uint16_t* /* preparation_delay */,
+ uint16_t* /* codecs */) { return return_value; }};
+ bool operator()(const RawAddress& address, uint8_t* capabilities,
+ uint64_t* hi_sync_id, uint16_t* render_delay,
+ uint16_t* preparation_delay, uint16_t* codecs) {
+ return body(address, capabilities, hi_sync_id, render_delay,
+ preparation_delay, codecs);
+ };
+};
+extern struct btif_storage_get_hearing_aid_prop
+ btif_storage_get_hearing_aid_prop;
+
+// Name: btif_storage_get_le_hid_devices
+// Params: void
+// Return: std::vector<std::pair<RawAddress, uint8_t>>
+struct btif_storage_get_le_hid_devices {
+ static std::vector<std::pair<RawAddress, uint8_t>> return_value;
+ std::function<std::vector<std::pair<RawAddress, uint8_t>>(void)> body{
+ [](void) { return return_value; }};
+ std::vector<std::pair<RawAddress, uint8_t>> operator()(void) {
+ return body();
+ };
+};
+extern struct btif_storage_get_le_hid_devices btif_storage_get_le_hid_devices;
+
+// Name: btif_storage_get_leaudio_has_features
+// Params: const RawAddress& address, uint8_t& features
+// Return: bool
+struct btif_storage_get_leaudio_has_features {
+ static bool return_value;
+ std::function<bool(const RawAddress& address, uint8_t& features)> body{
+ [](const RawAddress& /* address */, uint8_t& /* features */) {
+ return return_value;
+ }};
+ bool operator()(const RawAddress& address, uint8_t& features) {
+ return body(address, features);
+ };
+};
+extern struct btif_storage_get_leaudio_has_features
+ btif_storage_get_leaudio_has_features;
+
+// Name: btif_storage_get_leaudio_has_presets
+// Params: const RawAddress& address, std::vector<uint8_t>& presets_bin,
+// uint8_t& active_preset Return: bool
+struct btif_storage_get_leaudio_has_presets {
+ static bool return_value;
+ std::function<bool(const RawAddress& address,
+ std::vector<uint8_t>& presets_bin, uint8_t& active_preset)>
+ body{[](const RawAddress& /* address */,
+ std::vector<uint8_t>& /* presets_bin */,
+ uint8_t& /* active_preset */) { return return_value; }};
+ bool operator()(const RawAddress& address, std::vector<uint8_t>& presets_bin,
+ uint8_t& active_preset) {
+ return body(address, presets_bin, active_preset);
+ };
+};
+extern struct btif_storage_get_leaudio_has_presets
+ btif_storage_get_leaudio_has_presets;
+
+// Name: btif_storage_get_wake_capable_classic_hid_devices
+// Params: void
+// Return: std::vector<RawAddress>
+struct btif_storage_get_wake_capable_classic_hid_devices {
+ static std::vector<RawAddress> return_value;
+ std::function<std::vector<RawAddress>(void)> body{
+ [](void) { return return_value; }};
+ std::vector<RawAddress> operator()(void) { return body(); };
+};
+extern struct btif_storage_get_wake_capable_classic_hid_devices
+ btif_storage_get_wake_capable_classic_hid_devices;
+
+// Name: btif_storage_is_pce_version_102
+// Params: const RawAddress& remote_bd_addr
+// Return: bool
+struct btif_storage_is_pce_version_102 {
+ static bool return_value;
+ std::function<bool(const RawAddress& remote_bd_addr)> body{
+ [](const RawAddress& /* remote_bd_addr */) { return return_value; }};
+ bool operator()(const RawAddress& remote_bd_addr) {
+ return body(remote_bd_addr);
+ };
+};
+extern struct btif_storage_is_pce_version_102 btif_storage_is_pce_version_102;
+
+// Name: btif_storage_leaudio_clear_service_data
+// Params: const RawAddress& address
+// Return: void
+struct btif_storage_leaudio_clear_service_data {
+ std::function<void(const RawAddress& address)> body{
+ [](const RawAddress& /* address */) {}};
+ void operator()(const RawAddress& address) { body(address); };
+};
+extern struct btif_storage_leaudio_clear_service_data
+ btif_storage_leaudio_clear_service_data;
+
+// Name: btif_storage_leaudio_update_ase_bin
+// Params: const RawAddress& addr
+// Return: void
+struct btif_storage_leaudio_update_ase_bin {
+ std::function<void(const RawAddress& addr)> body{
+ [](const RawAddress& /* addr */) {}};
+ void operator()(const RawAddress& addr) { body(addr); };
+};
+extern struct btif_storage_leaudio_update_ase_bin
+ btif_storage_leaudio_update_ase_bin;
+
+// Name: btif_storage_leaudio_update_handles_bin
+// Params: const RawAddress& addr
+// Return: void
+struct btif_storage_leaudio_update_handles_bin {
+ std::function<void(const RawAddress& addr)> body{
+ [](const RawAddress& /* addr */) {}};
+ void operator()(const RawAddress& addr) { body(addr); };
+};
+extern struct btif_storage_leaudio_update_handles_bin
+ btif_storage_leaudio_update_handles_bin;
+
+// Name: btif_storage_leaudio_update_pacs_bin
+// Params: const RawAddress& addr
+// Return: void
+struct btif_storage_leaudio_update_pacs_bin {
+ std::function<void(const RawAddress& addr)> body{
+ [](const RawAddress& /* addr */) {}};
+ void operator()(const RawAddress& addr) { body(addr); };
+};
+extern struct btif_storage_leaudio_update_pacs_bin
+ btif_storage_leaudio_update_pacs_bin;
+
+// Name: btif_storage_load_bonded_csis_devices
+// Params: void
+// Return: void
+struct btif_storage_load_bonded_csis_devices {
+ std::function<void(void)> body{[](void) {}};
+ void operator()(void) { body(); };
+};
+extern struct btif_storage_load_bonded_csis_devices
+ btif_storage_load_bonded_csis_devices;
+
+// Name: btif_storage_load_bonded_groups
+// Params: void
+// Return: void
+struct btif_storage_load_bonded_groups {
+ std::function<void(void)> body{[](void) {}};
+ void operator()(void) { body(); };
+};
+extern struct btif_storage_load_bonded_groups btif_storage_load_bonded_groups;
+
+// Name: btif_storage_load_bonded_hearing_aids
+// Params:
+// Return: void
+struct btif_storage_load_bonded_hearing_aids {
+ std::function<void()> body{[]() {}};
+ void operator()() { body(); };
+};
+extern struct btif_storage_load_bonded_hearing_aids
+ btif_storage_load_bonded_hearing_aids;
+
+// Name: btif_storage_load_bonded_hid_info
+// Params: void
+// Return: bt_status_t
+struct btif_storage_load_bonded_hid_info {
+ static bt_status_t return_value;
+ std::function<bt_status_t(void)> body{[](void) { return return_value; }};
+ bt_status_t operator()(void) { return body(); };
+};
+extern struct btif_storage_load_bonded_hid_info
+ btif_storage_load_bonded_hid_info;
+
+// Name: btif_storage_load_bonded_leaudio
+// Params:
+// Return: void
+struct btif_storage_load_bonded_leaudio {
+ std::function<void()> body{[]() {}};
+ void operator()() { body(); };
+};
+extern struct btif_storage_load_bonded_leaudio btif_storage_load_bonded_leaudio;
+
+// Name: btif_storage_load_bonded_leaudio_has_devices
+// Params:
+// Return: void
+struct btif_storage_load_bonded_leaudio_has_devices {
+ std::function<void()> body{[]() {}};
+ void operator()() { body(); };
+};
+extern struct btif_storage_load_bonded_leaudio_has_devices
+ btif_storage_load_bonded_leaudio_has_devices;
+
+// Name: btif_storage_load_bonded_volume_control_devices
+// Params: void
+// Return: void
+struct btif_storage_load_bonded_volume_control_devices {
+ std::function<void(void)> body{[](void) {}};
+ void operator()(void) { body(); };
+};
+extern struct btif_storage_load_bonded_volume_control_devices
+ btif_storage_load_bonded_volume_control_devices;
+
+// Name: btif_storage_load_hidd
+// Params: void
+// Return: bt_status_t
+struct btif_storage_load_hidd {
+ static bt_status_t return_value;
+ std::function<bt_status_t(void)> body{[](void) { return return_value; }};
+ bt_status_t operator()(void) { return body(); };
+};
+extern struct btif_storage_load_hidd btif_storage_load_hidd;
+
+// Name: btif_storage_remove_csis_device
+// Params: const RawAddress& address
+// Return: void
+struct btif_storage_remove_csis_device {
+ std::function<void(const RawAddress& address)> body{
+ [](const RawAddress& /* address */) {}};
+ void operator()(const RawAddress& address) { body(address); };
+};
+extern struct btif_storage_remove_csis_device btif_storage_remove_csis_device;
+
+// Name: btif_storage_remove_groups
+// Params: const RawAddress& address
+// Return: void
+struct btif_storage_remove_groups {
+ std::function<void(const RawAddress& address)> body{
+ [](const RawAddress& /* address */) {}};
+ void operator()(const RawAddress& address) { body(address); };
+};
+extern struct btif_storage_remove_groups btif_storage_remove_groups;
+
+// Name: btif_storage_remove_hearing_aid
+// Params: const RawAddress& address
+// Return: void
+struct btif_storage_remove_hearing_aid {
+ std::function<void(const RawAddress& address)> body{
+ [](const RawAddress& /* address */) {}};
+ void operator()(const RawAddress& address) { body(address); };
+};
+extern struct btif_storage_remove_hearing_aid btif_storage_remove_hearing_aid;
+
+// Name: btif_storage_remove_hid_info
+// Params: const RawAddress& remote_bd_addr
+// Return: bt_status_t
+struct btif_storage_remove_hid_info {
+ static bt_status_t return_value;
+ std::function<bt_status_t(const RawAddress& remote_bd_addr)> body{
+ [](const RawAddress& /* remote_bd_addr */) { return return_value; }};
+ bt_status_t operator()(const RawAddress& remote_bd_addr) {
+ return body(remote_bd_addr);
+ };
+};
+extern struct btif_storage_remove_hid_info btif_storage_remove_hid_info;
+
+// Name: btif_storage_remove_hidd
+// Params: RawAddress* remote_bd_addr
+// Return: bt_status_t
+struct btif_storage_remove_hidd {
+ static bt_status_t return_value;
+ std::function<bt_status_t(RawAddress* remote_bd_addr)> body{
+ [](RawAddress* /* remote_bd_addr */) { return return_value; }};
+ bt_status_t operator()(RawAddress* remote_bd_addr) {
+ return body(remote_bd_addr);
+ };
+};
+extern struct btif_storage_remove_hidd btif_storage_remove_hidd;
+
+// Name: btif_storage_remove_leaudio
+// Params: const RawAddress& address
+// Return: void
+struct btif_storage_remove_leaudio {
+ std::function<void(const RawAddress& address)> body{
+ [](const RawAddress& /* address */) {}};
+ void operator()(const RawAddress& address) { body(address); };
+};
+extern struct btif_storage_remove_leaudio btif_storage_remove_leaudio;
+
+// Name: btif_storage_remove_leaudio_has
+// Params: const RawAddress& address
+// Return: void
+struct btif_storage_remove_leaudio_has {
+ std::function<void(const RawAddress& address)> body{
+ [](const RawAddress& /* address */) {}};
+ void operator()(const RawAddress& address) { body(address); };
+};
+extern struct btif_storage_remove_leaudio_has btif_storage_remove_leaudio_has;
+
+// Name: btif_storage_set_hearing_aid_acceptlist
+// Params: const RawAddress& address, bool add_to_acceptlist
+// Return: void
+struct btif_storage_set_hearing_aid_acceptlist {
+ std::function<void(const RawAddress& address, bool add_to_acceptlist)> body{
+ [](const RawAddress& /* address */, bool /* add_to_acceptlist */) {}};
+ void operator()(const RawAddress& address, bool add_to_acceptlist) {
+ body(address, add_to_acceptlist);
+ };
+};
+extern struct btif_storage_set_hearing_aid_acceptlist
+ btif_storage_set_hearing_aid_acceptlist;
+
+// Name: btif_storage_set_hidd
+// Params: const RawAddress& remote_bd_addr
+// Return: bt_status_t
+struct btif_storage_set_hidd {
+ static bt_status_t return_value;
+ std::function<bt_status_t(const RawAddress& remote_bd_addr)> body{
+ [](const RawAddress& /* remote_bd_addr */) { return return_value; }};
+ bt_status_t operator()(const RawAddress& remote_bd_addr) {
+ return body(remote_bd_addr);
+ };
+};
+extern struct btif_storage_set_hidd btif_storage_set_hidd;
+
+// Name: btif_storage_set_leaudio_audio_location
+// Params: const RawAddress& addr, uint32_t sink_location, uint32_t
+// source_location Return: void
+struct btif_storage_set_leaudio_audio_location {
+ std::function<void(const RawAddress& addr, uint32_t sink_location,
+ uint32_t source_location)>
+ body{[](const RawAddress& /* addr */, uint32_t /* sink_location */,
+ uint32_t /* source_location */) {}};
+ void operator()(const RawAddress& addr, uint32_t sink_location,
+ uint32_t source_location) {
+ body(addr, sink_location, source_location);
+ };
+};
+extern struct btif_storage_set_leaudio_audio_location
+ btif_storage_set_leaudio_audio_location;
+
+// Name: btif_storage_set_leaudio_autoconnect
+// Params: const RawAddress& addr, bool autoconnect
+// Return: void
+struct btif_storage_set_leaudio_autoconnect {
+ std::function<void(const RawAddress& addr, bool autoconnect)> body{
+ [](const RawAddress& /* addr */, bool /* autoconnect */) {}};
+ void operator()(const RawAddress& addr, bool autoconnect) {
+ body(addr, autoconnect);
+ };
+};
+extern struct btif_storage_set_leaudio_autoconnect
+ btif_storage_set_leaudio_autoconnect;
+
+// Name: btif_storage_set_leaudio_has_acceptlist
+// Params: const RawAddress& address, bool add_to_acceptlist
+// Return: void
+struct btif_storage_set_leaudio_has_acceptlist {
+ std::function<void(const RawAddress& address, bool add_to_acceptlist)> body{
+ [](const RawAddress& /* address */, bool /* add_to_acceptlist */) {}};
+ void operator()(const RawAddress& address, bool add_to_acceptlist) {
+ body(address, add_to_acceptlist);
+ };
+};
+extern struct btif_storage_set_leaudio_has_acceptlist
+ btif_storage_set_leaudio_has_acceptlist;
+
+// Name: btif_storage_set_leaudio_has_active_preset
+// Params: const RawAddress& address, uint8_t active_preset
+// Return: void
+struct btif_storage_set_leaudio_has_active_preset {
+ std::function<void(const RawAddress& address, uint8_t active_preset)> body{
+ [](const RawAddress& /* address */, uint8_t /* active_preset */) {}};
+ void operator()(const RawAddress& address, uint8_t active_preset) {
+ body(address, active_preset);
+ };
+};
+extern struct btif_storage_set_leaudio_has_active_preset
+ btif_storage_set_leaudio_has_active_preset;
+
+// Name: btif_storage_set_leaudio_has_features
+// Params: const RawAddress& address, uint8_t features
+// Return: void
+struct btif_storage_set_leaudio_has_features {
+ std::function<void(const RawAddress& address, uint8_t features)> body{
+ [](const RawAddress& /* address */, uint8_t /* features */) {}};
+ void operator()(const RawAddress& address, uint8_t features) {
+ body(address, features);
+ };
+};
+extern struct btif_storage_set_leaudio_has_features
+ btif_storage_set_leaudio_has_features;
+
+// Name: btif_storage_set_leaudio_has_presets
+// Params: const RawAddress& address, std::vector<uint8_t> presets_bin
+// Return: void
+struct btif_storage_set_leaudio_has_presets {
+ std::function<void(const RawAddress& address,
+ std::vector<uint8_t> presets_bin)>
+ body{[](const RawAddress& /* address */,
+ std::vector<uint8_t> /* presets_bin */) {}};
+ void operator()(const RawAddress& address, std::vector<uint8_t> presets_bin) {
+ body(address, presets_bin);
+ };
+};
+extern struct btif_storage_set_leaudio_has_presets
+ btif_storage_set_leaudio_has_presets;
+
+// Name: btif_storage_set_leaudio_supported_context_types
+// Params: const RawAddress& addr, uint16_t sink_supported_context_type,
+// uint16_t source_supported_context_type Return: void
+struct btif_storage_set_leaudio_supported_context_types {
+ std::function<void(const RawAddress& addr,
+ uint16_t sink_supported_context_type,
+ uint16_t source_supported_context_type)>
+ body{[](const RawAddress& /* addr */,
+ uint16_t /* sink_supported_context_type */,
+ uint16_t /* source_supported_context_type */) {}};
+ void operator()(const RawAddress& addr, uint16_t sink_supported_context_type,
+ uint16_t source_supported_context_type) {
+ body(addr, sink_supported_context_type, source_supported_context_type);
+ };
+};
+extern struct btif_storage_set_leaudio_supported_context_types
+ btif_storage_set_leaudio_supported_context_types;
+
+// Name: btif_storage_set_pce_profile_version
+// Params: const RawAddress& remote_bd_addr, uint16_t peer_pce_version
+// Return: void
+struct btif_storage_set_pce_profile_version {
+ std::function<void(const RawAddress& remote_bd_addr,
+ uint16_t peer_pce_version)>
+ body{[](const RawAddress& /* remote_bd_addr */,
+ uint16_t /* peer_pce_version */) {}};
+ void operator()(const RawAddress& remote_bd_addr, uint16_t peer_pce_version) {
+ body(remote_bd_addr, peer_pce_version);
+ };
+};
+extern struct btif_storage_set_pce_profile_version
+ btif_storage_set_pce_profile_version;
+
+// Name: btif_storage_update_csis_info
+// Params: const RawAddress& addr
+// Return: void
+struct btif_storage_update_csis_info {
+ std::function<void(const RawAddress& addr)> body{
+ [](const RawAddress& /* addr */) {}};
+ void operator()(const RawAddress& addr) { body(addr); };
+};
+extern struct btif_storage_update_csis_info btif_storage_update_csis_info;
+
+} // namespace btif_profile_storage
+} // namespace mock
+} // namespace test
+
+// END mockcify generation
diff --git a/system/test/mock/mock_btif_sock_rfc.h b/system/test/mock/mock_btif_sock_rfc.h
index be8be5d..eadf438 100644
--- a/system/test/mock/mock_btif_sock_rfc.h
+++ b/system/test/mock/mock_btif_sock_rfc.h
@@ -50,7 +50,7 @@
struct bta_co_rfc_data_incoming {
static int return_value;
std::function<int(uint32_t id, BT_HDR* p_buf)> body{
- [](uint32_t id, BT_HDR* p_buf) { return return_value; }};
+ [](uint32_t /* id */, BT_HDR* /* p_buf */) { return return_value; }};
int operator()(uint32_t id, BT_HDR* p_buf) { return body(id, p_buf); };
};
extern struct bta_co_rfc_data_incoming bta_co_rfc_data_incoming;
@@ -61,7 +61,9 @@
struct bta_co_rfc_data_outgoing {
static int return_value;
std::function<int(uint32_t id, uint8_t* buf, uint16_t size)> body{
- [](uint32_t id, uint8_t* buf, uint16_t size) { return return_value; }};
+ [](uint32_t /* id */, uint8_t* /* buf */, uint16_t /* size */) {
+ return return_value;
+ }};
int operator()(uint32_t id, uint8_t* buf, uint16_t size) {
return body(id, buf, size);
};
@@ -74,7 +76,7 @@
struct bta_co_rfc_data_outgoing_size {
static int return_value;
std::function<int(uint32_t id, int* size)> body{
- [](uint32_t id, int* size) { return return_value; }};
+ [](uint32_t /* id */, int* /* size */) { return return_value; }};
int operator()(uint32_t id, int* size) { return body(id, size); };
};
extern struct bta_co_rfc_data_outgoing_size bta_co_rfc_data_outgoing_size;
@@ -95,8 +97,9 @@
static bt_status_t return_value;
std::function<bt_status_t(const RawAddress* bd_addr, const Uuid* service_uuid,
int channel, int* sock_fd, int flags, int app_uid)>
- body{[](const RawAddress* bd_addr, const Uuid* service_uuid, int channel,
- int* sock_fd, int flags, int app_uid) { return return_value; }};
+ body{[](const RawAddress* /* bd_addr */, const Uuid* /* service_uuid */,
+ int /* channel */, int* /* sock_fd */, int /* flags */,
+ int /* app_uid */) { return return_value; }};
bt_status_t operator()(const RawAddress* bd_addr, const Uuid* service_uuid,
int channel, int* sock_fd, int flags, int app_uid) {
return body(bd_addr, service_uuid, channel, sock_fd, flags, app_uid);
@@ -114,9 +117,10 @@
uint8_t modem_signal, uint8_t break_signal,
uint8_t discard_buffers, uint8_t break_signal_seq,
bool fc)>
- body{[](uint8_t dlci, const RawAddress& bd_addr, uint8_t modem_signal,
- uint8_t break_signal, uint8_t discard_buffers,
- uint8_t break_signal_seq, bool fc) { return return_value; }};
+ body{[](uint8_t /* dlci */, const RawAddress& /* bd_addr */,
+ uint8_t /* modem_signal */, uint8_t /* break_signal */,
+ uint8_t /* discard_buffers */, uint8_t /* break_signal_seq */,
+ bool /* fc */) { return return_value; }};
bt_status_t operator()(uint8_t dlci, const RawAddress& bd_addr,
uint8_t modem_signal, uint8_t break_signal,
uint8_t discard_buffers, uint8_t break_signal_seq,
@@ -133,7 +137,7 @@
struct btsock_rfc_disconnect {
static bt_status_t return_value;
std::function<bt_status_t(const RawAddress* bd_addr)> body{
- [](const RawAddress* bd_addr) { return return_value; }};
+ [](const RawAddress* /* bd_addr */) { return return_value; }};
bt_status_t operator()(const RawAddress* bd_addr) { return body(bd_addr); };
};
extern struct btsock_rfc_disconnect btsock_rfc_disconnect;
@@ -144,7 +148,9 @@
struct btsock_rfc_init {
static bt_status_t return_value;
std::function<bt_status_t(int poll_thread_handle, uid_set_t* set)> body{
- [](int poll_thread_handle, uid_set_t* set) { return return_value; }};
+ [](int /* poll_thread_handle */, uid_set_t* /* set */) {
+ return return_value;
+ }};
bt_status_t operator()(int poll_thread_handle, uid_set_t* set) {
return body(poll_thread_handle, set);
};
@@ -158,8 +164,9 @@
static bt_status_t return_value;
std::function<bt_status_t(const char* service_name, const Uuid* service_uuid,
int channel, int* sock_fd, int flags, int app_uid)>
- body{[](const char* service_name, const Uuid* service_uuid, int channel,
- int* sock_fd, int flags, int app_uid) { return return_value; }};
+ body{[](const char* /* service_name */, const Uuid* /* service_uuid */,
+ int /* channel */, int* /* sock_fd */, int /* flags */,
+ int /* app_uid */) { return return_value; }};
bt_status_t operator()(const char* service_name, const Uuid* service_uuid,
int channel, int* sock_fd, int flags, int app_uid) {
return body(service_name, service_uuid, channel, sock_fd, flags, app_uid);
@@ -172,7 +179,7 @@
// Return: void
struct btsock_rfc_signaled {
std::function<void(int fd, int flags, uint32_t id)> body{
- [](int fd, int flags, uint32_t id) {}};
+ [](int /* fd */, int /* flags */, uint32_t /* id */) {}};
void operator()(int fd, int flags, uint32_t id) { body(fd, flags, id); };
};
extern struct btsock_rfc_signaled btsock_rfc_signaled;
@@ -181,4 +188,4 @@
} // namespace mock
} // namespace test
-// END mockcify generation
\ No newline at end of file
+// END mockcify generation
diff --git a/system/test/mock/mock_btif_storage.cc b/system/test/mock/mock_btif_storage.cc
index 2d52867..c529258 100644
--- a/system/test/mock/mock_btif_storage.cc
+++ b/system/test/mock/mock_btif_storage.cc
@@ -1,5 +1,5 @@
/*
- * Copyright 2021 The Android Open Source Project
+ * Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,232 +13,343 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
/*
* Generated mock file from original source file
- * Functions generated:44
+ * Functions generated:41
+ *
+ * mockcify.pl ver 0.7.0
*/
+// Mock include file to share data between tests and mock
+#include "test/mock/mock_btif_storage.h"
+
#include <cstdint>
-#include <string>
-#include "bta/include/bta_hearing_aid_api.h"
-#include "stack/include/bt_octets.h"
-#include "stack/include/btm_sec_api_types.h"
#include "test/common/mock_functions.h"
-#include "types/ble_address_with_type.h"
-#include "types/bluetooth/uuid.h"
-#include "types/raw_address.h"
-Octet16 btif_storage_get_gatt_cl_db_hash(const RawAddress& bd_addr) {
+// Original usings
+using bluetooth::Uuid;
+
+// Mocked internal structures, if any
+
+namespace test {
+namespace mock {
+namespace btif_storage {
+
+// Function state capture and return values, if needed
+struct btif_debug_linkkey_type_dump btif_debug_linkkey_type_dump;
+struct btif_has_ble_keys btif_has_ble_keys;
+struct btif_in_fetch_bonded_ble_device btif_in_fetch_bonded_ble_device;
+struct btif_in_fetch_bonded_device btif_in_fetch_bonded_device;
+struct btif_split_uuids_string btif_split_uuids_string;
+struct btif_storage_add_ble_bonding_key btif_storage_add_ble_bonding_key;
+struct btif_storage_add_ble_local_key btif_storage_add_ble_local_key;
+struct btif_storage_add_bonded_device btif_storage_add_bonded_device;
+struct btif_storage_add_remote_device btif_storage_add_remote_device;
+struct btif_storage_get_adapter_prop btif_storage_get_adapter_prop;
+struct btif_storage_get_adapter_property btif_storage_get_adapter_property;
+struct btif_storage_get_ble_bonding_key btif_storage_get_ble_bonding_key;
+struct btif_storage_get_ble_local_key btif_storage_get_ble_local_key;
+struct btif_storage_get_gatt_cl_db_hash btif_storage_get_gatt_cl_db_hash;
+struct btif_storage_get_gatt_cl_supp_feat btif_storage_get_gatt_cl_supp_feat;
+struct btif_storage_get_local_io_caps btif_storage_get_local_io_caps;
+struct btif_storage_get_num_bonded_devices btif_storage_get_num_bonded_devices;
+struct btif_storage_get_remote_addr_type btif_storage_get_remote_addr_type;
+struct btif_storage_get_remote_addr_type2 btif_storage_get_remote_addr_type2;
+struct btif_storage_get_remote_device_property
+ btif_storage_get_remote_device_property;
+struct btif_storage_get_remote_device_type btif_storage_get_remote_device_type;
+struct btif_storage_get_remote_prop btif_storage_get_remote_prop;
+struct btif_storage_get_sr_supp_feat btif_storage_get_sr_supp_feat;
+struct btif_storage_get_stored_remote_name btif_storage_get_stored_remote_name;
+struct btif_storage_invoke_addr_type_update
+ btif_storage_invoke_addr_type_update;
+struct btif_storage_is_restricted_device btif_storage_is_restricted_device;
+struct btif_storage_load_bonded_devices btif_storage_load_bonded_devices;
+struct btif_storage_load_le_devices btif_storage_load_le_devices;
+struct btif_storage_remove_ble_bonding_keys
+ btif_storage_remove_ble_bonding_keys;
+struct btif_storage_remove_ble_local_keys btif_storage_remove_ble_local_keys;
+struct btif_storage_remove_bonded_device btif_storage_remove_bonded_device;
+struct btif_storage_remove_gatt_cl_db_hash btif_storage_remove_gatt_cl_db_hash;
+struct btif_storage_remove_gatt_cl_supp_feat
+ btif_storage_remove_gatt_cl_supp_feat;
+struct btif_storage_set_adapter_property btif_storage_set_adapter_property;
+struct btif_storage_set_gatt_cl_db_hash btif_storage_set_gatt_cl_db_hash;
+struct btif_storage_set_gatt_cl_supp_feat btif_storage_set_gatt_cl_supp_feat;
+struct btif_storage_set_gatt_sr_supp_feat btif_storage_set_gatt_sr_supp_feat;
+struct btif_storage_set_remote_addr_type btif_storage_set_remote_addr_type;
+struct btif_storage_set_remote_addr_type2 btif_storage_set_remote_addr_type2;
+struct btif_storage_set_remote_device_property
+ btif_storage_set_remote_device_property;
+struct btif_storage_set_remote_device_type btif_storage_set_remote_device_type;
+
+} // namespace btif_storage
+} // namespace mock
+} // namespace test
+
+// Mocked function return values, if any
+namespace test {
+namespace mock {
+namespace btif_storage {
+
+bool btif_has_ble_keys::return_value = false;
+bt_status_t btif_in_fetch_bonded_ble_device::return_value = BT_STATUS_SUCCESS;
+bt_status_t btif_in_fetch_bonded_device::return_value = BT_STATUS_SUCCESS;
+size_t btif_split_uuids_string::return_value = 0;
+bt_status_t btif_storage_add_ble_bonding_key::return_value = BT_STATUS_SUCCESS;
+bt_status_t btif_storage_add_ble_local_key::return_value = BT_STATUS_SUCCESS;
+bt_status_t btif_storage_add_bonded_device::return_value = BT_STATUS_SUCCESS;
+bt_status_t btif_storage_add_remote_device::return_value = BT_STATUS_SUCCESS;
+bt_status_t btif_storage_get_adapter_prop::return_value = BT_STATUS_SUCCESS;
+bt_status_t btif_storage_get_adapter_property::return_value = BT_STATUS_SUCCESS;
+bt_status_t btif_storage_get_ble_bonding_key::return_value = BT_STATUS_SUCCESS;
+bt_status_t btif_storage_get_ble_local_key::return_value = BT_STATUS_SUCCESS;
+Octet16 btif_storage_get_gatt_cl_db_hash::return_value = {};
+uint8_t btif_storage_get_gatt_cl_supp_feat::return_value = 0;
+tBTM_IO_CAP btif_storage_get_local_io_caps::return_value = 0;
+int btif_storage_get_num_bonded_devices::return_value = 0;
+bt_status_t btif_storage_get_remote_addr_type::return_value = BT_STATUS_SUCCESS;
+bool btif_storage_get_remote_addr_type2::return_value = false;
+bt_status_t btif_storage_get_remote_device_property::return_value =
+ BT_STATUS_SUCCESS;
+bool btif_storage_get_remote_device_type::return_value = false;
+bt_status_t btif_storage_get_remote_prop::return_value = BT_STATUS_SUCCESS;
+uint8_t btif_storage_get_sr_supp_feat::return_value = 0;
+bool btif_storage_get_stored_remote_name::return_value = false;
+bool btif_storage_is_restricted_device::return_value = false;
+bt_status_t btif_storage_load_bonded_devices::return_value = BT_STATUS_SUCCESS;
+bt_status_t btif_storage_remove_ble_bonding_keys::return_value =
+ BT_STATUS_SUCCESS;
+bt_status_t btif_storage_remove_ble_local_keys::return_value =
+ BT_STATUS_SUCCESS;
+bt_status_t btif_storage_remove_bonded_device::return_value = BT_STATUS_SUCCESS;
+bt_status_t btif_storage_set_adapter_property::return_value = BT_STATUS_SUCCESS;
+bt_status_t btif_storage_set_remote_device_property::return_value =
+ BT_STATUS_SUCCESS;
+
+} // namespace btif_storage
+} // namespace mock
+} // namespace test
+
+// Mocked functions, if any
+void btif_debug_linkkey_type_dump(int fd) {
inc_func_call_count(__func__);
- Octet16 octet;
- return octet;
+ test::mock::btif_storage::btif_debug_linkkey_type_dump(fd);
}
bool btif_has_ble_keys(const std::string& bdstr) {
inc_func_call_count(__func__);
- return false;
+ return test::mock::btif_storage::btif_has_ble_keys(bdstr);
}
-bool btif_storage_get_hearing_aid_prop(
- const RawAddress& address, uint8_t* capabilities, uint64_t* hi_sync_id,
- uint16_t* render_delay, uint16_t* preparation_delay, uint16_t* codecs) {
+bt_status_t btif_in_fetch_bonded_ble_device(
+ const std::string& remote_bd_addr, int add,
+ btif_bonded_devices_t* p_bonded_devices) {
inc_func_call_count(__func__);
- return false;
+ return test::mock::btif_storage::btif_in_fetch_bonded_ble_device(
+ remote_bd_addr, add, p_bonded_devices);
}
-bool btif_storage_get_stored_remote_name(const RawAddress& bd_addr,
- char* name) {
+bt_status_t btif_in_fetch_bonded_device(const std::string& bdstr) {
inc_func_call_count(__func__);
- return false;
+ return test::mock::btif_storage::btif_in_fetch_bonded_device(bdstr);
}
-bool btif_storage_is_restricted_device(const RawAddress* remote_bd_addr) {
+size_t btif_split_uuids_string(const char* str, bluetooth::Uuid* p_uuid,
+ size_t max_uuids) {
inc_func_call_count(__func__);
- return false;
+ return test::mock::btif_storage::btif_split_uuids_string(str, p_uuid,
+ max_uuids);
}
bt_status_t btif_storage_add_ble_bonding_key(RawAddress* remote_bd_addr,
- const uint8_t* key,
+ const uint8_t* key_value,
uint8_t key_type,
uint8_t key_length) {
inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
+ return test::mock::btif_storage::btif_storage_add_ble_bonding_key(
+ remote_bd_addr, key_value, key_type, key_length);
}
-bt_status_t btif_storage_add_ble_local_key(const Octet16& key,
+bt_status_t btif_storage_add_ble_local_key(const Octet16& key_value,
uint8_t key_type) {
inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
+ return test::mock::btif_storage::btif_storage_add_ble_local_key(key_value,
+ key_type);
}
bt_status_t btif_storage_add_bonded_device(RawAddress* remote_bd_addr,
LinkKey link_key, uint8_t key_type,
uint8_t pin_length) {
inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
-}
-bt_status_t btif_storage_add_hid_device_info(
- RawAddress* remote_bd_addr, uint16_t attr_mask, uint8_t sub_class,
- uint8_t app_id, uint16_t vendor_id, uint16_t product_id, uint16_t version,
- uint8_t ctry_code, uint16_t ssr_max_latency, uint16_t ssr_min_tout,
- uint16_t dl_len, uint8_t* dsc_list) {
- inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
+ return test::mock::btif_storage::btif_storage_add_bonded_device(
+ remote_bd_addr, link_key, key_type, pin_length);
}
bt_status_t btif_storage_add_remote_device(const RawAddress* remote_bd_addr,
uint32_t num_properties,
bt_property_t* properties) {
inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
+ return test::mock::btif_storage::btif_storage_add_remote_device(
+ remote_bd_addr, num_properties, properties);
+}
+bt_status_t btif_storage_get_adapter_prop(bt_property_type_t type, void* buf,
+ int size, bt_property_t* property) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_storage::btif_storage_get_adapter_prop(
+ type, buf, size, property);
}
bt_status_t btif_storage_get_adapter_property(bt_property_t* property) {
inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
+ return test::mock::btif_storage::btif_storage_get_adapter_property(property);
}
bt_status_t btif_storage_get_ble_bonding_key(const RawAddress& remote_bd_addr,
uint8_t key_type,
uint8_t* key_value,
int key_length) {
inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
+ return test::mock::btif_storage::btif_storage_get_ble_bonding_key(
+ remote_bd_addr, key_type, key_value, key_length);
}
bt_status_t btif_storage_get_ble_local_key(uint8_t key_type,
Octet16* key_value) {
inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
+ return test::mock::btif_storage::btif_storage_get_ble_local_key(key_type,
+ key_value);
+}
+Octet16 btif_storage_get_gatt_cl_db_hash(const RawAddress& bd_addr) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_storage::btif_storage_get_gatt_cl_db_hash(bd_addr);
+}
+uint8_t btif_storage_get_gatt_cl_supp_feat(const RawAddress& bd_addr) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_storage::btif_storage_get_gatt_cl_supp_feat(bd_addr);
+}
+tBTM_IO_CAP btif_storage_get_local_io_caps() {
+ inc_func_call_count(__func__);
+ return test::mock::btif_storage::btif_storage_get_local_io_caps();
+}
+int btif_storage_get_num_bonded_devices(void) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_storage::btif_storage_get_num_bonded_devices();
}
bt_status_t btif_storage_get_remote_addr_type(const RawAddress* remote_bd_addr,
tBLE_ADDR_TYPE* addr_type) {
inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
+ return test::mock::btif_storage::btif_storage_get_remote_addr_type(
+ remote_bd_addr, addr_type);
+}
+bool btif_storage_get_remote_addr_type(const RawAddress& remote_bd_addr,
+ tBLE_ADDR_TYPE& addr_type) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_storage::btif_storage_get_remote_addr_type2(
+ remote_bd_addr, addr_type);
}
bt_status_t btif_storage_get_remote_device_property(
const RawAddress* remote_bd_addr, bt_property_t* property) {
inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
+ return test::mock::btif_storage::btif_storage_get_remote_device_property(
+ remote_bd_addr, property);
+}
+bool btif_storage_get_remote_device_type(const RawAddress& remote_bd_addr,
+ tBT_DEVICE_TYPE& device_type) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_storage::btif_storage_get_remote_device_type(
+ remote_bd_addr, device_type);
+}
+bt_status_t btif_storage_get_remote_prop(RawAddress* remote_addr,
+ bt_property_type_t type, void* buf,
+ int size, bt_property_t* property) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_storage::btif_storage_get_remote_prop(
+ remote_addr, type, buf, size, property);
+}
+uint8_t btif_storage_get_sr_supp_feat(const RawAddress& bd_addr) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_storage::btif_storage_get_sr_supp_feat(bd_addr);
+}
+bool btif_storage_get_stored_remote_name(const RawAddress& bd_addr,
+ char* name) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_storage::btif_storage_get_stored_remote_name(bd_addr,
+ name);
+}
+void btif_storage_invoke_addr_type_update(const RawAddress& remote_bd_addr,
+ const tBLE_ADDR_TYPE& addr_type) {
+ inc_func_call_count(__func__);
+ test::mock::btif_storage::btif_storage_invoke_addr_type_update(remote_bd_addr,
+ addr_type);
+}
+bool btif_storage_is_restricted_device(const RawAddress* remote_bd_addr) {
+ inc_func_call_count(__func__);
+ return test::mock::btif_storage::btif_storage_is_restricted_device(
+ remote_bd_addr);
}
bt_status_t btif_storage_load_bonded_devices(void) {
inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
+ return test::mock::btif_storage::btif_storage_load_bonded_devices();
}
-bt_status_t btif_storage_load_bonded_hid_info(void) {
+void btif_storage_load_le_devices(void) {
inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
-}
-bt_status_t btif_storage_load_hidd(void) {
- inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
+ test::mock::btif_storage::btif_storage_load_le_devices();
}
bt_status_t btif_storage_remove_ble_bonding_keys(
const RawAddress* remote_bd_addr) {
inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
+ return test::mock::btif_storage::btif_storage_remove_ble_bonding_keys(
+ remote_bd_addr);
}
bt_status_t btif_storage_remove_ble_local_keys(void) {
inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
+ return test::mock::btif_storage::btif_storage_remove_ble_local_keys();
}
bt_status_t btif_storage_remove_bonded_device(
const RawAddress* remote_bd_addr) {
inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
+ return test::mock::btif_storage::btif_storage_remove_bonded_device(
+ remote_bd_addr);
}
-bt_status_t btif_storage_remove_hid_info(const RawAddress& remote_bd_addr) {
- inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
-}
-bt_status_t btif_storage_remove_hidd(RawAddress* remote_bd_addr) {
- inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
-}
-bt_status_t btif_storage_set_adapter_property(bt_property_t* property) {
- inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
-}
-bt_status_t btif_storage_set_hidd(const RawAddress& remote_bd_addr) {
- inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
-}
-bt_status_t btif_storage_set_remote_addr_type(const RawAddress* remote_bd_addr,
- tBLE_ADDR_TYPE addr_type) {
- inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
-}
-bt_status_t btif_storage_set_remote_device_property(
- const RawAddress* remote_bd_addr, bt_property_t* property) {
- inc_func_call_count(__func__);
- return BT_STATUS_SUCCESS;
-}
-void btif_storage_add_hearing_aid(const HearingDevice& dev_info) {
- inc_func_call_count(__func__);
-}
-int btif_storage_get_num_bonded_devices(void) {
- inc_func_call_count(__func__);
- return 0;
-}
-size_t btif_split_uuids_string(const char* str, bluetooth::Uuid* p_uuid,
- size_t max_uuids) {
- inc_func_call_count(__func__);
- return 0;
-}
-uint8_t btif_storage_get_gatt_cl_supp_feat(const RawAddress& bd_addr) {
- inc_func_call_count(__func__);
- return 0;
-}
-tBTM_IO_CAP btif_storage_get_local_io_caps() {
- inc_func_call_count(__func__);
- return BTM_IO_CAP_UNKNOWN;
-}
-tBTM_IO_CAP btif_storage_get_local_io_caps_ble() {
- inc_func_call_count(__func__);
- return BTM_IO_CAP_UNKNOWN;
-}
-void btif_storage_load_bonded_hearing_aids() { inc_func_call_count(__func__); }
void btif_storage_remove_gatt_cl_db_hash(const RawAddress& bd_addr) {
inc_func_call_count(__func__);
+ test::mock::btif_storage::btif_storage_remove_gatt_cl_db_hash(bd_addr);
}
void btif_storage_remove_gatt_cl_supp_feat(const RawAddress& bd_addr) {
inc_func_call_count(__func__);
+ test::mock::btif_storage::btif_storage_remove_gatt_cl_supp_feat(bd_addr);
}
-void btif_storage_remove_hearing_aid(const RawAddress& address) {
+bt_status_t btif_storage_set_adapter_property(bt_property_t* property) {
inc_func_call_count(__func__);
+ return test::mock::btif_storage::btif_storage_set_adapter_property(property);
}
void btif_storage_set_gatt_cl_db_hash(const RawAddress& bd_addr, Octet16 hash) {
inc_func_call_count(__func__);
+ test::mock::btif_storage::btif_storage_set_gatt_cl_db_hash(bd_addr, hash);
}
void btif_storage_set_gatt_cl_supp_feat(const RawAddress& bd_addr,
uint8_t feat) {
inc_func_call_count(__func__);
-}
-void btif_storage_set_hearing_aid_acceptlist(const RawAddress& address,
- bool add_to_acceptlist) {
- inc_func_call_count(__func__);
+ test::mock::btif_storage::btif_storage_set_gatt_cl_supp_feat(bd_addr, feat);
}
void btif_storage_set_gatt_sr_supp_feat(const RawAddress& addr, uint8_t feat) {
inc_func_call_count(__func__);
+ test::mock::btif_storage::btif_storage_set_gatt_sr_supp_feat(addr, feat);
}
-uint8_t btif_storage_get_sr_supp_feat(const RawAddress& bd_addr) {
+bt_status_t btif_storage_set_remote_addr_type(const RawAddress* remote_bd_addr,
+ const tBLE_ADDR_TYPE addr_type) {
inc_func_call_count(__func__);
- return 0;
+ return test::mock::btif_storage::btif_storage_set_remote_addr_type(
+ remote_bd_addr, addr_type);
}
-void btif_storage_add_groups(RawAddress const&) {
+void btif_storage_set_remote_addr_type(const RawAddress& remote_bd_addr,
+ const tBLE_ADDR_TYPE& addr_type) {
inc_func_call_count(__func__);
+ test::mock::btif_storage::btif_storage_set_remote_addr_type2(remote_bd_addr,
+ addr_type);
}
-void btif_storage_remove_groups(RawAddress const&) {
+bt_status_t btif_storage_set_remote_device_property(
+ const RawAddress* remote_bd_addr, bt_property_t* property) {
inc_func_call_count(__func__);
+ return test::mock::btif_storage::btif_storage_set_remote_device_property(
+ remote_bd_addr, property);
}
-void btif_storage_load_bonded_groups() { inc_func_call_count(__func__); }
-void btif_storage_set_csis_autoconnect(const RawAddress& addr,
- bool autoconnect) {
+void btif_storage_set_remote_device_type(const RawAddress& remote_bd_addr,
+ const tBT_DEVICE_TYPE& device_type) {
inc_func_call_count(__func__);
+ test::mock::btif_storage::btif_storage_set_remote_device_type(remote_bd_addr,
+ device_type);
}
-void btif_storage_update_csis_info(const RawAddress& addr) {
- inc_func_call_count(__func__);
-}
-void btif_storage_load_bonded_csis_devices() { inc_func_call_count(__func__); }
-void btif_storage_remove_csis_device(const RawAddress& address) {
- inc_func_call_count(__func__);
-}
-void btif_storage_set_pce_profile_version(const RawAddress& remote_bd_addr,
- uint16_t peer_pce_version) {
- inc_func_call_count(__func__);
-}
-bool btif_storage_is_pce_version_102(const RawAddress& remote_bd_addr) {
- inc_func_call_count(__func__);
- return false;
-}
+// Mocked functions complete
+// END mockcify generation
diff --git a/system/test/mock/mock_btif_storage.h b/system/test/mock/mock_btif_storage.h
new file mode 100644
index 0000000..e38a1bb
--- /dev/null
+++ b/system/test/mock/mock_btif_storage.h
@@ -0,0 +1,627 @@
+/*
+ * Copyright 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+/*
+ * Generated mock file from original source file
+ * Functions generated:41
+ *
+ * mockcify.pl ver 0.7.0
+ */
+
+#include <cstdint>
+#include <functional>
+
+// Original included files, if any
+// NOTE: Since this is a mock file with mock definitions some number of
+// include files may not be required. The include-what-you-use
+// still applies, but crafting proper inclusion is out of scope
+// for this effort. This compilation unit may compile as-is, or
+// may need attention to prune from (or add to ) the inclusion set.
+
+#include "btif/include/btif_storage.h"
+#include "stack/include/bt_octets.h"
+#include "types/bluetooth/uuid.h"
+#include "types/raw_address.h"
+
+// Original usings
+
+// Mocked compile conditionals, if any
+
+namespace test {
+namespace mock {
+namespace btif_storage {
+
+// Shared state between mocked functions and tests
+// Name: btif_debug_linkkey_type_dump
+// Params: int fd
+// Return: void
+struct btif_debug_linkkey_type_dump {
+ std::function<void(int fd)> body{[](int /* fd */) {}};
+ void operator()(int fd) { body(fd); };
+};
+extern struct btif_debug_linkkey_type_dump btif_debug_linkkey_type_dump;
+
+// Name: btif_has_ble_keys
+// Params: const std::string& bdstr
+// Return: bool
+struct btif_has_ble_keys {
+ static bool return_value;
+ std::function<bool(const std::string& bdstr)> body{
+ [](const std::string& /* bdstr */) { return return_value; }};
+ bool operator()(const std::string& bdstr) { return body(bdstr); };
+};
+extern struct btif_has_ble_keys btif_has_ble_keys;
+
+// Name: btif_in_fetch_bonded_ble_device
+// Params: const std::string& remote_bd_addr, int add, btif_bonded_devices_t*
+// p_bonded_devices Return: bt_status_t
+struct btif_in_fetch_bonded_ble_device {
+ static bt_status_t return_value;
+ std::function<bt_status_t(const std::string& remote_bd_addr, int add,
+ btif_bonded_devices_t* p_bonded_devices)>
+ body{[](const std::string& /* remote_bd_addr */, int /* add */,
+ btif_bonded_devices_t* /* p_bonded_devices */) {
+ return return_value;
+ }};
+ bt_status_t operator()(const std::string& remote_bd_addr, int add,
+ btif_bonded_devices_t* p_bonded_devices) {
+ return body(remote_bd_addr, add, p_bonded_devices);
+ };
+};
+extern struct btif_in_fetch_bonded_ble_device btif_in_fetch_bonded_ble_device;
+
+// Name: btif_in_fetch_bonded_device
+// Params: const std::string& bdstr
+// Return: bt_status_t
+struct btif_in_fetch_bonded_device {
+ static bt_status_t return_value;
+ std::function<bt_status_t(const std::string& bdstr)> body{
+ [](const std::string& /* bdstr */) { return return_value; }};
+ bt_status_t operator()(const std::string& bdstr) { return body(bdstr); };
+};
+extern struct btif_in_fetch_bonded_device btif_in_fetch_bonded_device;
+
+// Name: btif_split_uuids_string
+// Params: const char* str, bluetooth::Uuid* p_uuid, size_t max_uuids
+// Return: size_t
+struct btif_split_uuids_string {
+ static size_t return_value;
+ std::function<size_t(const char* str, bluetooth::Uuid* p_uuid,
+ size_t max_uuids)>
+ body{[](const char* /* str */, bluetooth::Uuid* /* p_uuid */,
+ size_t /* max_uuids */) { return return_value; }};
+ size_t operator()(const char* str, bluetooth::Uuid* p_uuid,
+ size_t max_uuids) {
+ return body(str, p_uuid, max_uuids);
+ };
+};
+extern struct btif_split_uuids_string btif_split_uuids_string;
+
+// Name: btif_storage_add_ble_bonding_key
+// Params: RawAddress* remote_bd_addr, const uint8_t* key_value, uint8_t
+// key_type, uint8_t key_length Return: bt_status_t
+struct btif_storage_add_ble_bonding_key {
+ static bt_status_t return_value;
+ std::function<bt_status_t(RawAddress* remote_bd_addr,
+ const uint8_t* key_value, uint8_t key_type,
+ uint8_t key_length)>
+ body{[](RawAddress* /* remote_bd_addr */, const uint8_t* /* key_value */,
+ uint8_t /* key_type */,
+ uint8_t /* key_length */) { return return_value; }};
+ bt_status_t operator()(RawAddress* remote_bd_addr, const uint8_t* key_value,
+ uint8_t key_type, uint8_t key_length) {
+ return body(remote_bd_addr, key_value, key_type, key_length);
+ };
+};
+extern struct btif_storage_add_ble_bonding_key btif_storage_add_ble_bonding_key;
+
+// Name: btif_storage_add_ble_local_key
+// Params: const Octet16& key_value, uint8_t key_type
+// Return: bt_status_t
+struct btif_storage_add_ble_local_key {
+ static bt_status_t return_value;
+ std::function<bt_status_t(const Octet16& key_value, uint8_t key_type)> body{
+ [](const Octet16& /* key_value */, uint8_t /* key_type */) {
+ return return_value;
+ }};
+ bt_status_t operator()(const Octet16& key_value, uint8_t key_type) {
+ return body(key_value, key_type);
+ };
+};
+extern struct btif_storage_add_ble_local_key btif_storage_add_ble_local_key;
+
+// Name: btif_storage_add_bonded_device
+// Params: RawAddress* remote_bd_addr, LinkKey link_key, uint8_t key_type,
+// uint8_t pin_length Return: bt_status_t
+struct btif_storage_add_bonded_device {
+ static bt_status_t return_value;
+ std::function<bt_status_t(RawAddress* remote_bd_addr, LinkKey link_key,
+ uint8_t key_type, uint8_t pin_length)>
+ body{[](RawAddress* /* remote_bd_addr */, LinkKey /* link_key */,
+ uint8_t /* key_type */,
+ uint8_t /* pin_length */) { return return_value; }};
+ bt_status_t operator()(RawAddress* remote_bd_addr, LinkKey link_key,
+ uint8_t key_type, uint8_t pin_length) {
+ return body(remote_bd_addr, link_key, key_type, pin_length);
+ };
+};
+extern struct btif_storage_add_bonded_device btif_storage_add_bonded_device;
+
+// Name: btif_storage_add_remote_device
+// Params: const RawAddress* remote_bd_addr, uint32_t num_properties,
+// bt_property_t* properties Return: bt_status_t
+struct btif_storage_add_remote_device {
+ static bt_status_t return_value;
+ std::function<bt_status_t(const RawAddress* remote_bd_addr,
+ uint32_t num_properties, bt_property_t* properties)>
+ body{[](const RawAddress* /* remote_bd_addr */,
+ uint32_t /* num_properties */,
+ bt_property_t* /* properties */) { return return_value; }};
+ bt_status_t operator()(const RawAddress* remote_bd_addr,
+ uint32_t num_properties, bt_property_t* properties) {
+ return body(remote_bd_addr, num_properties, properties);
+ };
+};
+extern struct btif_storage_add_remote_device btif_storage_add_remote_device;
+
+// Name: btif_storage_get_adapter_prop
+// Params: bt_property_type_t type, void* buf, int size, bt_property_t* property
+// Return: bt_status_t
+struct btif_storage_get_adapter_prop {
+ static bt_status_t return_value;
+ std::function<bt_status_t(bt_property_type_t type, void* buf, int size,
+ bt_property_t* property)>
+ body{[](bt_property_type_t /* type */, void* /* buf */, int /* size */,
+ bt_property_t* /* property */) { return return_value; }};
+ bt_status_t operator()(bt_property_type_t type, void* buf, int size,
+ bt_property_t* property) {
+ return body(type, buf, size, property);
+ };
+};
+extern struct btif_storage_get_adapter_prop btif_storage_get_adapter_prop;
+
+// Name: btif_storage_get_adapter_property
+// Params: bt_property_t* property
+// Return: bt_status_t
+struct btif_storage_get_adapter_property {
+ static bt_status_t return_value;
+ std::function<bt_status_t(bt_property_t* property)> body{
+ [](bt_property_t* /* property */) { return return_value; }};
+ bt_status_t operator()(bt_property_t* property) { return body(property); };
+};
+extern struct btif_storage_get_adapter_property
+ btif_storage_get_adapter_property;
+
+// Name: btif_storage_get_ble_bonding_key
+// Params: const RawAddress& remote_bd_addr, uint8_t key_type, uint8_t*
+// key_value, int key_length Return: bt_status_t
+struct btif_storage_get_ble_bonding_key {
+ static bt_status_t return_value;
+ std::function<bt_status_t(const RawAddress& remote_bd_addr, uint8_t key_type,
+ uint8_t* key_value, int key_length)>
+ body{[](const RawAddress& /* remote_bd_addr */, uint8_t /* key_type */,
+ uint8_t* /* key_value */,
+ int /* key_length */) { return return_value; }};
+ bt_status_t operator()(const RawAddress& remote_bd_addr, uint8_t key_type,
+ uint8_t* key_value, int key_length) {
+ return body(remote_bd_addr, key_type, key_value, key_length);
+ };
+};
+extern struct btif_storage_get_ble_bonding_key btif_storage_get_ble_bonding_key;
+
+// Name: btif_storage_get_ble_local_key
+// Params: uint8_t key_type, Octet16* key_value
+// Return: bt_status_t
+struct btif_storage_get_ble_local_key {
+ static bt_status_t return_value;
+ std::function<bt_status_t(uint8_t key_type, Octet16* key_value)> body{
+ [](uint8_t /* key_type */, Octet16* /* key_value */) {
+ return return_value;
+ }};
+ bt_status_t operator()(uint8_t key_type, Octet16* key_value) {
+ return body(key_type, key_value);
+ };
+};
+extern struct btif_storage_get_ble_local_key btif_storage_get_ble_local_key;
+
+// Name: btif_storage_get_gatt_cl_db_hash
+// Params: const RawAddress& bd_addr
+// Return: Octet16
+struct btif_storage_get_gatt_cl_db_hash {
+ static Octet16 return_value;
+ std::function<Octet16(const RawAddress& bd_addr)> body{
+ [](const RawAddress& /* bd_addr */) { return return_value; }};
+ Octet16 operator()(const RawAddress& bd_addr) { return body(bd_addr); };
+};
+extern struct btif_storage_get_gatt_cl_db_hash btif_storage_get_gatt_cl_db_hash;
+
+// Name: btif_storage_get_gatt_cl_supp_feat
+// Params: const RawAddress& bd_addr
+// Return: uint8_t
+struct btif_storage_get_gatt_cl_supp_feat {
+ static uint8_t return_value;
+ std::function<uint8_t(const RawAddress& bd_addr)> body{
+ [](const RawAddress& /* bd_addr */) { return return_value; }};
+ uint8_t operator()(const RawAddress& bd_addr) { return body(bd_addr); };
+};
+extern struct btif_storage_get_gatt_cl_supp_feat
+ btif_storage_get_gatt_cl_supp_feat;
+
+// Name: btif_storage_get_local_io_caps
+// Params:
+// Return: tBTM_IO_CAP
+struct btif_storage_get_local_io_caps {
+ static tBTM_IO_CAP return_value;
+ std::function<tBTM_IO_CAP()> body{[]() { return return_value; }};
+ tBTM_IO_CAP operator()() { return body(); };
+};
+extern struct btif_storage_get_local_io_caps btif_storage_get_local_io_caps;
+
+// Name: btif_storage_get_num_bonded_devices
+// Params: void
+// Return: int
+struct btif_storage_get_num_bonded_devices {
+ static int return_value;
+ std::function<int(void)> body{[](void) { return return_value; }};
+ int operator()(void) { return body(); };
+};
+extern struct btif_storage_get_num_bonded_devices
+ btif_storage_get_num_bonded_devices;
+
+// Name: btif_storage_get_remote_addr_type
+// Params: const RawAddress* remote_bd_addr, tBLE_ADDR_TYPE addr_type
+// Return: bt_status_t
+struct btif_storage_get_remote_addr_type {
+ static bt_status_t return_value;
+ std::function<bt_status_t(const RawAddress* remote_bd_addr,
+ tBLE_ADDR_TYPE* addr_type)>
+ body{[](const RawAddress* /* remote_bd_addr */,
+ tBLE_ADDR_TYPE* /* addr_type */) -> bt_status_t {
+ return return_value;
+ }};
+ bt_status_t operator()(const RawAddress* remote_bd_addr,
+ tBLE_ADDR_TYPE* addr_type) {
+ return body(remote_bd_addr, addr_type);
+ };
+};
+extern struct btif_storage_get_remote_addr_type
+ btif_storage_get_remote_addr_type;
+
+// Name: btif_storage_get_remote_addr_type2
+// Params: const RawAddress& remote_bd_addr, tBLE_ADDR_TYPE& addr_type
+// Return: bool
+struct btif_storage_get_remote_addr_type2 {
+ static bool return_value;
+ std::function<bool(const RawAddress& remote_bd_addr,
+ tBLE_ADDR_TYPE& addr_type)>
+ body{[](const RawAddress& /* remote_bd_addr */,
+ tBLE_ADDR_TYPE& /* addr_type */) { return return_value; }};
+ bool operator()(const RawAddress& remote_bd_addr, tBLE_ADDR_TYPE& addr_type) {
+ return body(remote_bd_addr, addr_type);
+ };
+};
+extern struct btif_storage_get_remote_addr_type2
+ btif_storage_get_remote_addr_type2;
+
+// Name: btif_storage_get_remote_device_property
+// Params: const RawAddress* remote_bd_addr, bt_property_t* property
+// Return: bt_status_t
+struct btif_storage_get_remote_device_property {
+ static bt_status_t return_value;
+ std::function<bt_status_t(const RawAddress* remote_bd_addr,
+ bt_property_t* property)>
+ body{[](const RawAddress* /* remote_bd_addr */,
+ bt_property_t* /* property */) { return return_value; }};
+ bt_status_t operator()(const RawAddress* remote_bd_addr,
+ bt_property_t* property) {
+ return body(remote_bd_addr, property);
+ };
+};
+extern struct btif_storage_get_remote_device_property
+ btif_storage_get_remote_device_property;
+
+// Name: btif_storage_get_remote_device_type
+// Params: const RawAddress& remote_bd_addr, tBT_DEVICE_TYPE& device_type
+// Return: bool
+struct btif_storage_get_remote_device_type {
+ static bool return_value;
+ std::function<bool(const RawAddress& remote_bd_addr,
+ tBT_DEVICE_TYPE& device_type)>
+ body{[](const RawAddress& /* remote_bd_addr */,
+ tBT_DEVICE_TYPE& /* device_type */) { return return_value; }};
+ bool operator()(const RawAddress& remote_bd_addr,
+ tBT_DEVICE_TYPE& device_type) {
+ return body(remote_bd_addr, device_type);
+ };
+};
+extern struct btif_storage_get_remote_device_type
+ btif_storage_get_remote_device_type;
+
+// Name: btif_storage_get_remote_prop
+// Params: RawAddress* remote_addr, bt_property_type_t type, void* buf, int
+// size, bt_property_t* property Return: bt_status_t
+struct btif_storage_get_remote_prop {
+ static bt_status_t return_value;
+ std::function<bt_status_t(RawAddress* remote_addr, bt_property_type_t type,
+ void* buf, int size, bt_property_t* property)>
+ body{[](RawAddress* /* remote_addr */, bt_property_type_t /* type */,
+ void* /* buf */, int /* size */,
+ bt_property_t* /* property */) { return return_value; }};
+ bt_status_t operator()(RawAddress* remote_addr, bt_property_type_t type,
+ void* buf, int size, bt_property_t* property) {
+ return body(remote_addr, type, buf, size, property);
+ };
+};
+extern struct btif_storage_get_remote_prop btif_storage_get_remote_prop;
+
+// Name: btif_storage_get_sr_supp_feat
+// Params: const RawAddress& bd_addr
+// Return: uint8_t
+struct btif_storage_get_sr_supp_feat {
+ static uint8_t return_value;
+ std::function<uint8_t(const RawAddress& bd_addr)> body{
+ [](const RawAddress& /* bd_addr */) { return return_value; }};
+ uint8_t operator()(const RawAddress& bd_addr) { return body(bd_addr); };
+};
+extern struct btif_storage_get_sr_supp_feat btif_storage_get_sr_supp_feat;
+
+// Name: btif_storage_get_stored_remote_name
+// Params: const RawAddress& bd_addr, char* name
+// Return: bool
+struct btif_storage_get_stored_remote_name {
+ static bool return_value;
+ std::function<bool(const RawAddress& bd_addr, char* name)> body{
+ [](const RawAddress& /* bd_addr */, char* /* name */) {
+ return return_value;
+ }};
+ bool operator()(const RawAddress& bd_addr, char* name) {
+ return body(bd_addr, name);
+ };
+};
+extern struct btif_storage_get_stored_remote_name
+ btif_storage_get_stored_remote_name;
+
+// Name: btif_storage_invoke_addr_type_update
+// Params: const RawAddress& remote_bd_addr, const tBLE_ADDR_TYPE& addr_type
+// Return: void
+struct btif_storage_invoke_addr_type_update {
+ std::function<void(const RawAddress& remote_bd_addr,
+ const tBLE_ADDR_TYPE& addr_type)>
+ body{[](const RawAddress& /* remote_bd_addr */,
+ const tBLE_ADDR_TYPE& /* addr_type */) {}};
+ void operator()(const RawAddress& remote_bd_addr,
+ const tBLE_ADDR_TYPE& addr_type) {
+ body(remote_bd_addr, addr_type);
+ };
+};
+extern struct btif_storage_invoke_addr_type_update
+ btif_storage_invoke_addr_type_update;
+
+// Name: btif_storage_is_restricted_device
+// Params: const RawAddress* remote_bd_addr
+// Return: bool
+struct btif_storage_is_restricted_device {
+ static bool return_value;
+ std::function<bool(const RawAddress* remote_bd_addr)> body{
+ [](const RawAddress* /* remote_bd_addr */) { return return_value; }};
+ bool operator()(const RawAddress* remote_bd_addr) {
+ return body(remote_bd_addr);
+ };
+};
+extern struct btif_storage_is_restricted_device
+ btif_storage_is_restricted_device;
+
+// Name: btif_storage_load_bonded_devices
+// Params: void
+// Return: bt_status_t
+struct btif_storage_load_bonded_devices {
+ static bt_status_t return_value;
+ std::function<bt_status_t(void)> body{[](void) { return return_value; }};
+ bt_status_t operator()(void) { return body(); };
+};
+extern struct btif_storage_load_bonded_devices btif_storage_load_bonded_devices;
+
+// Name: btif_storage_load_le_devices
+// Params: void
+// Return: void
+struct btif_storage_load_le_devices {
+ std::function<void(void)> body{[](void) {}};
+ void operator()(void) { body(); };
+};
+extern struct btif_storage_load_le_devices btif_storage_load_le_devices;
+
+// Name: btif_storage_remove_ble_bonding_keys
+// Params: const RawAddress* remote_bd_addr
+// Return: bt_status_t
+struct btif_storage_remove_ble_bonding_keys {
+ static bt_status_t return_value;
+ std::function<bt_status_t(const RawAddress* remote_bd_addr)> body{
+ [](const RawAddress* /* remote_bd_addr */) { return return_value; }};
+ bt_status_t operator()(const RawAddress* remote_bd_addr) {
+ return body(remote_bd_addr);
+ };
+};
+extern struct btif_storage_remove_ble_bonding_keys
+ btif_storage_remove_ble_bonding_keys;
+
+// Name: btif_storage_remove_ble_local_keys
+// Params: void
+// Return: bt_status_t
+struct btif_storage_remove_ble_local_keys {
+ static bt_status_t return_value;
+ std::function<bt_status_t(void)> body{[](void) { return return_value; }};
+ bt_status_t operator()(void) { return body(); };
+};
+extern struct btif_storage_remove_ble_local_keys
+ btif_storage_remove_ble_local_keys;
+
+// Name: btif_storage_remove_bonded_device
+// Params: const RawAddress* remote_bd_addr
+// Return: bt_status_t
+struct btif_storage_remove_bonded_device {
+ static bt_status_t return_value;
+ std::function<bt_status_t(const RawAddress* remote_bd_addr)> body{
+ [](const RawAddress* /* remote_bd_addr */) { return return_value; }};
+ bt_status_t operator()(const RawAddress* remote_bd_addr) {
+ return body(remote_bd_addr);
+ };
+};
+extern struct btif_storage_remove_bonded_device
+ btif_storage_remove_bonded_device;
+
+// Name: btif_storage_remove_gatt_cl_db_hash
+// Params: const RawAddress& bd_addr
+// Return: void
+struct btif_storage_remove_gatt_cl_db_hash {
+ std::function<void(const RawAddress& bd_addr)> body{
+ [](const RawAddress& /* bd_addr */) {}};
+ void operator()(const RawAddress& bd_addr) { body(bd_addr); };
+};
+extern struct btif_storage_remove_gatt_cl_db_hash
+ btif_storage_remove_gatt_cl_db_hash;
+
+// Name: btif_storage_remove_gatt_cl_supp_feat
+// Params: const RawAddress& bd_addr
+// Return: void
+struct btif_storage_remove_gatt_cl_supp_feat {
+ std::function<void(const RawAddress& bd_addr)> body{
+ [](const RawAddress& /* bd_addr */) {}};
+ void operator()(const RawAddress& bd_addr) { body(bd_addr); };
+};
+extern struct btif_storage_remove_gatt_cl_supp_feat
+ btif_storage_remove_gatt_cl_supp_feat;
+
+// Name: btif_storage_set_adapter_property
+// Params: bt_property_t* property
+// Return: bt_status_t
+struct btif_storage_set_adapter_property {
+ static bt_status_t return_value;
+ std::function<bt_status_t(bt_property_t* property)> body{
+ [](bt_property_t* /* property */) { return return_value; }};
+ bt_status_t operator()(bt_property_t* property) { return body(property); };
+};
+extern struct btif_storage_set_adapter_property
+ btif_storage_set_adapter_property;
+
+// Name: btif_storage_set_gatt_cl_db_hash
+// Params: const RawAddress& bd_addr, Octet16 hash
+// Return: void
+struct btif_storage_set_gatt_cl_db_hash {
+ std::function<void(const RawAddress& bd_addr, Octet16 hash)> body{
+ [](const RawAddress& /* bd_addr */, Octet16 /* hash */) {}};
+ void operator()(const RawAddress& bd_addr, Octet16 hash) {
+ body(bd_addr, hash);
+ };
+};
+extern struct btif_storage_set_gatt_cl_db_hash btif_storage_set_gatt_cl_db_hash;
+
+// Name: btif_storage_set_gatt_cl_supp_feat
+// Params: const RawAddress& bd_addr, uint8_t feat
+// Return: void
+struct btif_storage_set_gatt_cl_supp_feat {
+ std::function<void(const RawAddress& bd_addr, uint8_t feat)> body{
+ [](const RawAddress& /* bd_addr */, uint8_t /* feat */) {}};
+ void operator()(const RawAddress& bd_addr, uint8_t feat) {
+ body(bd_addr, feat);
+ };
+};
+extern struct btif_storage_set_gatt_cl_supp_feat
+ btif_storage_set_gatt_cl_supp_feat;
+
+// Name: btif_storage_set_gatt_sr_supp_feat
+// Params: const RawAddress& addr, uint8_t feat
+// Return: void
+struct btif_storage_set_gatt_sr_supp_feat {
+ std::function<void(const RawAddress& addr, uint8_t feat)> body{
+ [](const RawAddress& /* addr */, uint8_t /* feat */) {}};
+ void operator()(const RawAddress& addr, uint8_t feat) { body(addr, feat); };
+};
+extern struct btif_storage_set_gatt_sr_supp_feat
+ btif_storage_set_gatt_sr_supp_feat;
+
+// Name: btif_storage_set_remote_addr_type
+// Params: const RawAddress& remote_bd_addr, const tBLE_ADDR_TYPE& addr_type
+// Return: void
+struct btif_storage_set_remote_addr_type {
+ std::function<bt_status_t(const RawAddress* remote_bd_addr,
+ const tBLE_ADDR_TYPE addr_type)>
+ body{[](const RawAddress* /* remote_bd_addr */,
+ const tBLE_ADDR_TYPE /* addr_type */) {
+ return BT_STATUS_SUCCESS;
+ }};
+ bt_status_t operator()(const RawAddress* remote_bd_addr,
+ const tBLE_ADDR_TYPE addr_type) {
+ return body(remote_bd_addr, addr_type);
+ };
+};
+extern struct btif_storage_set_remote_addr_type
+ btif_storage_set_remote_addr_type;
+
+// Name: btif_storage_set_remote_addr_type
+// Params: const RawAddress& remote_bd_addr, const tBLE_ADDR_TYPE& addr_type
+// Return: void
+struct btif_storage_set_remote_addr_type2 {
+ std::function<void(const RawAddress& remote_bd_addr,
+ const tBLE_ADDR_TYPE& addr_type)>
+ body{[](const RawAddress& /* remote_bd_addr */,
+ const tBLE_ADDR_TYPE& /* addr_type */) {}};
+ void operator()(const RawAddress& remote_bd_addr,
+ const tBLE_ADDR_TYPE& addr_type) {
+ body(remote_bd_addr, addr_type);
+ };
+};
+extern struct btif_storage_set_remote_addr_type2
+ btif_storage_set_remote_addr_type2;
+
+// Name: btif_storage_set_remote_device_property
+// Params: const RawAddress* remote_bd_addr, bt_property_t* property
+// Return: bt_status_t
+struct btif_storage_set_remote_device_property {
+ static bt_status_t return_value;
+ std::function<bt_status_t(const RawAddress* remote_bd_addr,
+ bt_property_t* property)>
+ body{[](const RawAddress* /* remote_bd_addr */,
+ bt_property_t* /* property */) { return return_value; }};
+ bt_status_t operator()(const RawAddress* remote_bd_addr,
+ bt_property_t* property) {
+ return body(remote_bd_addr, property);
+ };
+};
+extern struct btif_storage_set_remote_device_property
+ btif_storage_set_remote_device_property;
+
+// Name: btif_storage_set_remote_device_type
+// Params: const RawAddress& remote_bd_addr, const tBT_DEVICE_TYPE& device_type
+// Return: void
+struct btif_storage_set_remote_device_type {
+ std::function<void(const RawAddress& remote_bd_addr,
+ const tBT_DEVICE_TYPE& device_type)>
+ body{[](const RawAddress& /* remote_bd_addr */,
+ const tBT_DEVICE_TYPE& /* device_type */) {}};
+ void operator()(const RawAddress& remote_bd_addr,
+ const tBT_DEVICE_TYPE& device_type) {
+ body(remote_bd_addr, device_type);
+ };
+};
+extern struct btif_storage_set_remote_device_type
+ btif_storage_set_remote_device_type;
+
+} // namespace btif_storage
+} // namespace mock
+} // namespace test
+
+// END mockcify generation
diff --git a/system/test/mock/mock_btif_util.h b/system/test/mock/mock_btif_util.h
index 2753712..dd7dec3 100644
--- a/system/test/mock/mock_btif_util.h
+++ b/system/test/mock/mock_btif_util.h
@@ -46,7 +46,7 @@
struct ascii_2_hex {
static int return_value;
std::function<int(const char* p_ascii, int len, uint8_t* p_hex)> body{
- [](const char* p_ascii, int len, uint8_t* p_hex) {
+ [](const char* /* p_ascii */, int /* len */, uint8_t* /* p_hex */) {
return return_value;
}};
int operator()(const char* p_ascii, int len, uint8_t* p_hex) {
@@ -61,7 +61,7 @@
struct devclass2uint {
static uint32_t return_value;
std::function<uint32_t(DEV_CLASS dev_class)> body{
- [](DEV_CLASS dev_class) { return return_value; }};
+ [](DEV_CLASS /* dev_class */) { return return_value; }};
uint32_t operator()(DEV_CLASS dev_class) { return body(dev_class); };
};
extern struct devclass2uint devclass2uint;
@@ -72,7 +72,7 @@
struct dump_adapter_scan_mode {
static const char* return_value;
std::function<const char*(bt_scan_mode_t mode)> body{
- [](bt_scan_mode_t mode) { return return_value; }};
+ [](bt_scan_mode_t /* mode */) { return return_value; }};
const char* operator()(bt_scan_mode_t mode) { return body(mode); };
};
extern struct dump_adapter_scan_mode dump_adapter_scan_mode;
@@ -83,7 +83,7 @@
struct dump_av_audio_state {
static const char* return_value;
std::function<const char*(uint16_t event)> body{
- [](uint16_t event) { return return_value; }};
+ [](uint16_t /* event */) { return return_value; }};
const char* operator()(uint16_t event) { return body(event); };
};
extern struct dump_av_audio_state dump_av_audio_state;
@@ -94,7 +94,7 @@
struct dump_av_conn_state {
static const char* return_value;
std::function<const char*(uint16_t event)> body{
- [](uint16_t event) { return return_value; }};
+ [](uint16_t /* event */) { return return_value; }};
const char* operator()(uint16_t event) { return body(event); };
};
extern struct dump_av_conn_state dump_av_conn_state;
@@ -105,7 +105,7 @@
struct dump_bt_status {
static const char* return_value;
std::function<const char*(bt_status_t status)> body{
- [](bt_status_t status) { return return_value; }};
+ [](bt_status_t /* status */) { return return_value; }};
const char* operator()(bt_status_t status) { return body(status); };
};
extern struct dump_bt_status dump_bt_status;
@@ -116,7 +116,7 @@
struct dump_dm_event {
static const char* return_value;
std::function<const char*(uint16_t event)> body{
- [](uint16_t event) { return return_value; }};
+ [](uint16_t /* event */) { return return_value; }};
const char* operator()(uint16_t event) { return body(event); };
};
extern struct dump_dm_event dump_dm_event;
@@ -127,7 +127,7 @@
struct dump_dm_search_event {
static const char* return_value;
std::function<const char*(uint16_t event)> body{
- [](uint16_t event) { return return_value; }};
+ [](uint16_t /* event */) { return return_value; }};
const char* operator()(uint16_t event) { return body(event); };
};
extern struct dump_dm_search_event dump_dm_search_event;
@@ -138,7 +138,7 @@
struct dump_hd_event {
static const char* return_value;
std::function<const char*(uint16_t event)> body{
- [](uint16_t event) { return return_value; }};
+ [](uint16_t /* event */) { return return_value; }};
const char* operator()(uint16_t event) { return body(event); };
};
extern struct dump_hd_event dump_hd_event;
@@ -149,7 +149,7 @@
struct dump_hf_client_event {
static const char* return_value;
std::function<const char*(uint16_t event)> body{
- [](uint16_t event) { return return_value; }};
+ [](uint16_t /* event */) { return return_value; }};
const char* operator()(uint16_t event) { return body(event); };
};
extern struct dump_hf_client_event dump_hf_client_event;
@@ -160,7 +160,7 @@
struct dump_hf_event {
static const char* return_value;
std::function<const char*(uint16_t event)> body{
- [](uint16_t event) { return return_value; }};
+ [](uint16_t /* event */) { return return_value; }};
const char* operator()(uint16_t event) { return body(event); };
};
extern struct dump_hf_event dump_hf_event;
@@ -171,7 +171,7 @@
struct dump_hh_event {
static const char* return_value;
std::function<const char*(uint16_t event)> body{
- [](uint16_t event) { return return_value; }};
+ [](uint16_t /* event */) { return return_value; }};
const char* operator()(uint16_t event) { return body(event); };
};
extern struct dump_hh_event dump_hh_event;
@@ -182,7 +182,7 @@
struct dump_property_type {
static const char* return_value;
std::function<const char*(bt_property_type_t type)> body{
- [](bt_property_type_t type) { return return_value; }};
+ [](bt_property_type_t /* type */) { return return_value; }};
const char* operator()(bt_property_type_t type) { return body(type); };
};
extern struct dump_property_type dump_property_type;
@@ -193,7 +193,7 @@
struct dump_rc_event {
static const char* return_value;
std::function<const char*(uint8_t event)> body{
- [](uint8_t event) { return return_value; }};
+ [](uint8_t /* event */) { return return_value; }};
const char* operator()(uint8_t event) { return body(event); };
};
extern struct dump_rc_event dump_rc_event;
@@ -204,7 +204,7 @@
struct dump_rc_notification_event_id {
static const char* return_value;
std::function<const char*(uint8_t event_id)> body{
- [](uint8_t event_id) { return return_value; }};
+ [](uint8_t /* event_id */) { return return_value; }};
const char* operator()(uint8_t event_id) { return body(event_id); };
};
extern struct dump_rc_notification_event_id dump_rc_notification_event_id;
@@ -215,7 +215,7 @@
struct dump_rc_pdu {
static const char* return_value;
std::function<const char*(uint8_t pdu)> body{
- [](uint8_t pdu) { return return_value; }};
+ [](uint8_t /* pdu */) { return return_value; }};
const char* operator()(uint8_t pdu) { return body(pdu); };
};
extern struct dump_rc_pdu dump_rc_pdu;
@@ -226,7 +226,7 @@
struct dump_thread_evt {
static const char* return_value;
std::function<const char*(bt_cb_thread_evt evt)> body{
- [](bt_cb_thread_evt evt) { return return_value; }};
+ [](bt_cb_thread_evt /* evt */) { return return_value; }};
const char* operator()(bt_cb_thread_evt evt) { return body(evt); };
};
extern struct dump_thread_evt dump_thread_evt;
@@ -237,7 +237,7 @@
struct uint2devclass {
static constexpr DEV_CLASS return_value{};
std::function<DEV_CLASS(uint32_t cod)> body{
- [](uint32_t cod) { return return_value; }};
+ [](uint32_t /* cod */) { return return_value; }};
DEV_CLASS operator()(uint32_t cod) { return body(cod); };
};
extern struct uint2devclass uint2devclass;
diff --git a/system/test/mock/mock_jni_thread.cc b/system/test/mock/mock_jni_thread.cc
new file mode 100644
index 0000000..bcc0471
--- /dev/null
+++ b/system/test/mock/mock_jni_thread.cc
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
+ * Generated mock file from original source file
+ * Functions generated:27
+ */
+
+#include <base/functional/bind.h>
+
+#include <cstdint>
+
+#include "btif/include/btif_common.h"
+#include "include/hardware/bluetooth.h"
+#include "test/common/jni_thread.h"
+#include "test/common/mock_functions.h"
+
+bool is_on_jni_thread() {
+ inc_func_call_count(__func__);
+ return false;
+}
+bt_status_t btif_transfer_context(tBTIF_CBACK* /* p_cback */,
+ uint16_t /* event */, char* /* p_params */,
+ int /* param_len */,
+ tBTIF_COPY_CBACK* /* p_copy_cback */) {
+ inc_func_call_count(__func__);
+ return BT_STATUS_SUCCESS;
+}
+bt_status_t do_in_jni_thread(base::OnceClosure task) {
+ inc_func_call_count(__func__);
+ do_in_jni_thread_task_queue.push(std::move(task));
+ return BT_STATUS_SUCCESS;
+}
+bt_status_t do_in_jni_thread(const base::Location& /* from_here */,
+ base::OnceClosure task) {
+ inc_func_call_count(__func__);
+ do_in_jni_thread_task_queue.push(std::move(task));
+ return BT_STATUS_SUCCESS;
+}
diff --git a/system/test/mock/mock_legacy_hci_interface.h b/system/test/mock/mock_legacy_hci_interface.h
index 2260d41..3ae95fa 100644
--- a/system/test/mock/mock_legacy_hci_interface.h
+++ b/system/test/mock/mock_legacy_hci_interface.h
@@ -23,7 +23,6 @@
namespace bluetooth::legacy::hci::testing {
class MockInterface : public Interface {
public:
- MOCK_METHOD(void, InquiryCancel, (), (const));
MOCK_METHOD(void, Disconnect, (uint16_t handle, uint8_t reason), (const));
MOCK_METHOD(void, ChangeConnectionPacketType,
(uint16_t handle, uint16_t packet_types), (const));
diff --git a/system/test/mock/mock_main_shim_acl.cc b/system/test/mock/mock_main_shim_acl.cc
index 4244b94..0b14802 100644
--- a/system/test/mock/mock_main_shim_acl.cc
+++ b/system/test/mock/mock_main_shim_acl.cc
@@ -14,12 +14,238 @@
* limitations under the License.
*/
-/*
- * Generated mock file from original source file
- * Functions generated:7
- */
+#include <base/location.h>
+#include <base/strings/stringprintf.h>
-#include "main/shim/acl_api.h"
+#include <cstdint>
+#include <future>
+#include <memory>
+#include <optional>
+#include <string>
+
+#include "common/sync_map_count.h"
+#include "device/include/controller.h"
+#include "hci/acl_manager.h"
+#include "hci/acl_manager/classic_acl_connection.h"
+#include "hci/acl_manager/le_acl_connection.h"
+#include "hci/address.h"
+#include "hci/address_with_type.h"
+#include "hci/class_of_device.h"
+#include "main/shim/acl.h"
+#include "main/shim/entry.h"
+#include "os/handler.h"
+#include "stack/acl/acl.h"
#include "test/common/mock_functions.h"
+#include "types/raw_address.h"
-void bluetooth::shim::ACL_Shutdown() { inc_func_call_count(__func__); }
+using namespace bluetooth;
+
+void DumpsysL2cap(int /* fd */) { inc_func_call_count(__func__); }
+
+void DumpsysAcl(int /* fd */) { inc_func_call_count(__func__); }
+
+void DumpsysBtm(int /* fd */) { inc_func_call_count(__func__); }
+
+void DumpsysRecord(int /* fd */) { inc_func_call_count(__func__); }
+
+void DumpsysNeighbor(int /* fd */) { inc_func_call_count(__func__); }
+
+void shim::legacy::Acl::Dump(int /* fd */) const {
+ inc_func_call_count(__func__);
+}
+
+shim::legacy::Acl::Acl(os::Handler* /* handler */,
+ const acl_interface_t& acl_interface,
+ uint8_t /* max_acceptlist_size */,
+ uint8_t /* max_address_resolution_size */)
+ : acl_interface_(acl_interface) {
+ inc_func_call_count(__func__);
+}
+shim::legacy::Acl::~Acl() { inc_func_call_count(__func__); }
+
+bool shim::legacy::Acl::CheckForOrphanedAclConnections() const {
+ inc_func_call_count(__func__);
+ return false;
+}
+
+void shim::legacy::Acl::on_incoming_acl_credits(uint16_t /* handle */,
+ uint16_t /* credits */) {
+ inc_func_call_count(__func__);
+}
+
+using HciHandle = uint16_t;
+
+struct shim::legacy::Acl::impl {};
+
+void shim::legacy::Acl::CreateClassicConnection(
+ const hci::Address& /* address */) {
+ inc_func_call_count(__func__);
+}
+
+void shim::legacy::Acl::CancelClassicConnection(
+ const hci::Address& /* address */) {
+ inc_func_call_count(__func__);
+}
+
+void shim::legacy::Acl::AcceptLeConnectionFrom(
+ const hci::AddressWithType& /* address_with_type */, bool /* is_direct */,
+ std::promise<bool> /* promise */) {
+ inc_func_call_count(__func__);
+}
+
+void shim::legacy::Acl::IgnoreLeConnectionFrom(
+ const hci::AddressWithType& /* address_with_type */) {
+ inc_func_call_count(__func__);
+}
+
+void bluetooth::shim::legacy::Acl::OnClassicLinkDisconnected(
+ HciHandle /* handle */, hci::ErrorCode /* reason */) {
+ inc_func_call_count(__func__);
+}
+
+bluetooth::hci::AddressWithType shim::legacy::Acl::GetConnectionLocalAddress(
+ uint16_t /* handle */, bool /* ota_address */) {
+ inc_func_call_count(__func__);
+ return hci::AddressWithType();
+}
+bluetooth::hci::AddressWithType shim::legacy::Acl::GetConnectionPeerAddress(
+ uint16_t /* handle */, bool /* ota_address */) {
+ inc_func_call_count(__func__);
+ return hci::AddressWithType();
+}
+
+std::optional<uint8_t> shim::legacy::Acl::GetAdvertisingSetConnectedTo(
+ const RawAddress& /* remote_bda */) {
+ inc_func_call_count(__func__);
+ return std::nullopt;
+ ;
+}
+
+void shim::legacy::Acl::OnLeLinkDisconnected(HciHandle /* handle */,
+ hci::ErrorCode /* reason */) {
+ inc_func_call_count(__func__);
+}
+
+void shim::legacy::Acl::OnConnectSuccess(
+ std::unique_ptr<hci::acl_manager::ClassicAclConnection> /* connection */) {
+ inc_func_call_count(__func__);
+}
+
+void shim::legacy::Acl::OnConnectRequest(hci::Address /* address */,
+ hci::ClassOfDevice /* cod */) {
+ inc_func_call_count(__func__);
+}
+void shim::legacy::Acl::OnConnectFail(hci::Address /* address */,
+ hci::ErrorCode /* reason */,
+ bool /* locally_initiated */) {
+ inc_func_call_count(__func__);
+}
+
+void shim::legacy::Acl::OnLeConnectSuccess(
+ hci::AddressWithType /* address_with_type */,
+ std::unique_ptr<hci::acl_manager::LeAclConnection> /* connection */) {
+ inc_func_call_count(__func__);
+}
+
+void shim::legacy::Acl::OnLeConnectFail(
+ hci::AddressWithType /* address_with_type */, hci::ErrorCode /* reason */) {
+ inc_func_call_count(__func__);
+}
+
+void shim::legacy::Acl::DisconnectClassic(uint16_t /* handle */,
+ tHCI_STATUS /* reason */,
+ std::string /* comment */) {
+ inc_func_call_count(__func__);
+}
+
+void shim::legacy::Acl::DisconnectLe(uint16_t /* handle */,
+ tHCI_STATUS /* reason */,
+ std::string /* comment */) {
+ inc_func_call_count(__func__);
+}
+
+bool shim::legacy::Acl::HoldMode(uint16_t /* hci_handle */,
+ uint16_t /* max_interval */,
+ uint16_t /* min_interval */) {
+ inc_func_call_count(__func__);
+ return false;
+}
+
+bool shim::legacy::Acl::SniffMode(uint16_t /* hci_handle */,
+ uint16_t /* max_interval */,
+ uint16_t /* min_interval */,
+ uint16_t /* attempt */,
+ uint16_t /* timeout */) {
+ inc_func_call_count(__func__);
+ return false;
+}
+
+bool shim::legacy::Acl::ExitSniffMode(uint16_t /* hci_handle */) {
+ inc_func_call_count(__func__);
+ return false;
+}
+
+bool shim::legacy::Acl::SniffSubrating(uint16_t /* hci_handle */,
+ uint16_t /* maximum_latency */,
+ uint16_t /* minimum_remote_timeout */,
+ uint16_t /* minimum_local_timeout */) {
+ inc_func_call_count(__func__);
+ return false;
+}
+
+void shim::legacy::Acl::LeSetDefaultSubrate(uint16_t /* subrate_min */,
+ uint16_t /* subrate_max */,
+ uint16_t /* max_latency */,
+ uint16_t /* cont_num */,
+ uint16_t /* sup_tout */) {
+ inc_func_call_count(__func__);
+}
+
+void shim::legacy::Acl::LeSubrateRequest(uint16_t /* hci_handle */,
+ uint16_t /* subrate_min */,
+ uint16_t /* subrate_max */,
+ uint16_t /* max_latency */,
+ uint16_t /* cont_num */,
+ uint16_t /* sup_tout */) {
+ inc_func_call_count(__func__);
+}
+
+void shim::legacy::Acl::DumpConnectionHistory(int /* fd */) const {
+ inc_func_call_count(__func__);
+}
+
+void shim::legacy::Acl::DisconnectAllForSuspend() {
+ inc_func_call_count(__func__);
+}
+
+void shim::legacy::Acl::Shutdown() { inc_func_call_count(__func__); }
+
+void shim::legacy::Acl::FinalShutdown() { inc_func_call_count(__func__); }
+
+void shim::legacy::Acl::ClearFilterAcceptList() {
+ inc_func_call_count(__func__);
+}
+
+void shim::legacy::Acl::LeRand(LeRandCallback /* cb */) {
+ inc_func_call_count(__func__);
+}
+
+void shim::legacy::Acl::AddToAddressResolution(
+ const hci::AddressWithType& /* address_with_type */,
+ const std::array<uint8_t, 16>& /* peer_irk */,
+ const std::array<uint8_t, 16>& /* local_irk */) {
+ inc_func_call_count(__func__);
+}
+
+void shim::legacy::Acl::RemoveFromAddressResolution(
+ const hci::AddressWithType& /* address_with_type */) {
+ inc_func_call_count(__func__);
+}
+
+void shim::legacy::Acl::ClearAddressResolution() {
+ inc_func_call_count(__func__);
+}
+
+void shim::legacy::Acl::SetSystemSuspendState(bool /* suspended */) {
+ inc_func_call_count(__func__);
+}
diff --git a/system/test/mock/mock_main_shim_acl_api.cc b/system/test/mock/mock_main_shim_acl_api.cc
index ab21692..e679183 100644
--- a/system/test/mock/mock_main_shim_acl_api.cc
+++ b/system/test/mock/mock_main_shim_acl_api.cc
@@ -105,3 +105,5 @@
uint16_t /* sup_tout */) {
inc_func_call_count(__func__);
}
+
+void bluetooth::shim::ACL_Shutdown() { inc_func_call_count(__func__); }
diff --git a/system/test/mock/mock_main_shim_acl_legacy_interface.cc b/system/test/mock/mock_main_shim_acl_legacy_interface.cc
new file mode 100644
index 0000000..a7edba5
--- /dev/null
+++ b/system/test/mock/mock_main_shim_acl_legacy_interface.cc
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "main/shim/acl_legacy_interface.h"
+
+namespace bluetooth {
+namespace shim {
+namespace legacy {
+
+acl_interface_t acl_interface_ = {
+ .on_send_data_upwards = nullptr,
+ .on_packets_completed = nullptr,
+
+ .connection.classic.on_connected = nullptr,
+ .connection.classic.on_connect_request = nullptr,
+ .connection.classic.on_failed = nullptr,
+ .connection.classic.on_disconnected = nullptr,
+
+ .connection.le.on_connected = nullptr,
+ .connection.le.on_failed = nullptr,
+ .connection.le.on_disconnected = nullptr,
+
+ .link.classic.on_authentication_complete = nullptr,
+ .link.classic.on_central_link_key_complete = nullptr,
+ .link.classic.on_change_connection_link_key_complete = nullptr,
+ .link.classic.on_encryption_change = nullptr,
+ .link.classic.on_flow_specification_complete = nullptr,
+ .link.classic.on_flush_occurred = nullptr,
+ .link.classic.on_mode_change = nullptr,
+ .link.classic.on_packet_type_changed = nullptr,
+ .link.classic.on_qos_setup_complete = nullptr,
+ .link.classic.on_read_afh_channel_map_complete = nullptr,
+ .link.classic.on_read_automatic_flush_timeout_complete = nullptr,
+ .link.classic.on_sniff_subrating = nullptr,
+ .link.classic.on_read_clock_complete = nullptr,
+ .link.classic.on_read_clock_offset_complete = nullptr,
+ .link.classic.on_read_failed_contact_counter_complete = nullptr,
+ .link.classic.on_read_link_policy_settings_complete = nullptr,
+ .link.classic.on_read_link_quality_complete = nullptr,
+ .link.classic.on_read_link_supervision_timeout_complete = nullptr,
+ .link.classic.on_read_remote_version_information_complete = nullptr,
+ .link.classic.on_read_remote_supported_features_complete = nullptr,
+ .link.classic.on_read_remote_extended_features_complete = nullptr,
+ .link.classic.on_read_rssi_complete = nullptr,
+ .link.classic.on_read_transmit_power_level_complete = nullptr,
+ .link.classic.on_role_change = nullptr,
+ .link.classic.on_role_discovery_complete = nullptr,
+
+ .link.le.on_connection_update = nullptr,
+ .link.le.on_data_length_change = nullptr,
+ .link.le.on_read_remote_version_information_complete = nullptr,
+ .link.le.on_phy_update = nullptr,
+ .link.le.on_le_subrate_change = nullptr,
+};
+
+const acl_interface_t& GetAclInterface() { return acl_interface_; }
+
+} // namespace legacy
+} // namespace shim
+} // namespace bluetooth
diff --git a/system/test/mock/mock_main_shim_btm_api.cc b/system/test/mock/mock_main_shim_btm_api.cc
index 3c93c9e..35300b1 100644
--- a/system/test/mock/mock_main_shim_btm_api.cc
+++ b/system/test/mock/mock_main_shim_btm_api.cc
@@ -240,3 +240,7 @@
inc_func_call_count(__func__);
return BTM_SUCCESS;
}
+size_t bluetooth::shim::BTM_BleGetNumberOfAdvertisingInstancesInUse() {
+ inc_func_call_count(__func__);
+ return 0;
+}
diff --git a/system/test/mock/mock_main_shim_hci_layer.cc b/system/test/mock/mock_main_shim_hci_layer.cc
index 5651dfc..ff7f1e6 100644
--- a/system/test/mock/mock_main_shim_hci_layer.cc
+++ b/system/test/mock/mock_main_shim_hci_layer.cc
@@ -16,13 +16,18 @@
/*
* Generated mock file from original source file
- * Functions generated:3
+ * Functions generated:5
*
- * mockcify.pl ver 0.3.0
+ * mockcify.pl ver 0.7.0
*/
// Mock include file to share data between tests and mock
+#include "test/mock/mock_main_shim_hci_layer.h"
+
#include "main/shim/hci_layer.h"
+#include "test/common/mock_functions.h"
+
+// Original usings
// Mocked internal structures, if any
@@ -33,5 +38,58 @@
test_interface = interface;
}
} // namespace testing
-const hci_t* hci_layer_get_interface() { return testing::test_interface; }
} // namespace bluetooth::shim
+
+const hci_t* bluetooth::shim::hci_layer_get_interface() {
+ return testing::test_interface;
+}
+
+namespace test {
+namespace mock {
+namespace main_shim_hci_layer {
+
+// Function state capture and return values, if needed
+struct OnTransmitPacketCommandComplete OnTransmitPacketCommandComplete;
+struct OnTransmitPacketStatus OnTransmitPacketStatus;
+struct hci_on_reset_complete hci_on_reset_complete;
+struct hci_on_shutting_down hci_on_shutting_down;
+
+} // namespace main_shim_hci_layer
+} // namespace mock
+} // namespace test
+
+// Mocked function return values, if any
+namespace test {
+namespace mock {
+namespace main_shim_hci_layer {} // namespace main_shim_hci_layer
+} // namespace mock
+} // namespace test
+
+// Mocked functions, if any
+namespace cpp {
+void OnTransmitPacketCommandComplete(command_complete_cb complete_callback,
+ void* context,
+ bluetooth::hci::CommandCompleteView view) {
+ inc_func_call_count(__func__);
+ test::mock::main_shim_hci_layer::OnTransmitPacketCommandComplete(
+ complete_callback, context, view);
+}
+void OnTransmitPacketStatus(command_status_cb status_callback, void* context,
+ std::unique_ptr<OsiObject> command,
+ bluetooth::hci::CommandStatusView view) {
+ inc_func_call_count(__func__);
+ test::mock::main_shim_hci_layer::OnTransmitPacketStatus(
+ status_callback, context, std::move(command), view);
+}
+} // namespace cpp
+
+void bluetooth::shim::hci_on_reset_complete() {
+ inc_func_call_count(__func__);
+ test::mock::main_shim_hci_layer::hci_on_reset_complete();
+}
+void bluetooth::shim::hci_on_shutting_down() {
+ inc_func_call_count(__func__);
+ test::mock::main_shim_hci_layer::hci_on_shutting_down();
+}
+// Mocked functions complete
+// END mockcify generation
diff --git a/system/test/mock/mock_main_shim_hci_layer.h b/system/test/mock/mock_main_shim_hci_layer.h
index bed162c..c54735d 100644
--- a/system/test/mock/mock_main_shim_hci_layer.h
+++ b/system/test/mock/mock_main_shim_hci_layer.h
@@ -18,16 +18,107 @@
/*
* Generated mock file from original source file
- * Functions generated:3
+ * Functions generated:5
*
- * mockcify.pl ver 0.3.0
+ * mockcify.pl ver 0.7.0
*/
-// Original included files, if any
+#include <functional>
+
#include "hci/include/hci_layer.h"
+// Original included files, if any
+// NOTE: Since this is a mock file with mock definitions some number of
+// include files may not be required. The include-what-you-use
+// still applies, but crafting proper inclusion is out of scope
+// for this effort. This compilation unit may compile as-is, or
+// may need attention to prune from (or add to ) the inclusion set.
+#include <base/functional/bind.h>
+
+#include "hci/hci_packets.h"
+#include "osi/include/allocator.h"
+
+// Original usings
+using CommandCallbackData = struct {
+ void* context;
+};
+// Mocked compile conditionals, if any
+
namespace bluetooth::shim {
namespace testing {
-void hci_layer_set_interface(const hci_t* interface);
-}
+extern void hci_layer_set_interface(const hci_t* interface);
+} // namespace testing
} // namespace bluetooth::shim
+
+namespace test {
+namespace mock {
+namespace main_shim_hci_layer {
+
+// Shared state between mocked functions and tests
+// Name: OnTransmitPacketCommandComplete
+// Params: command_complete_cb complete_callback, void* context,
+// bluetooth::hci::CommandCompleteView view Return: void
+struct OnTransmitPacketCommandComplete {
+ std::function<void(command_complete_cb complete_callback, void* context,
+ bluetooth::hci::CommandCompleteView view)>
+ body{[](command_complete_cb /* complete_callback */, void* /* context */,
+ bluetooth::hci::CommandCompleteView /* view */) {}};
+ void operator()(command_complete_cb complete_callback, void* context,
+ bluetooth::hci::CommandCompleteView view) {
+ body(complete_callback, context, view);
+ };
+};
+extern struct OnTransmitPacketCommandComplete OnTransmitPacketCommandComplete;
+
+// Name: OnTransmitPacketStatus
+// Params: command_status_cb status_callback, void* context,
+// std::unique_ptr<OsiObject> command, bluetooth::hci::CommandStatusView view
+// Return: void
+struct OnTransmitPacketStatus {
+ std::function<void(command_status_cb status_callback, void* context,
+ std::unique_ptr<OsiObject> command,
+ bluetooth::hci::CommandStatusView view)>
+ body{[](command_status_cb /* status_callback */, void* /* context */,
+ std::unique_ptr<OsiObject> /* command */,
+ bluetooth::hci::CommandStatusView /* view */) {}};
+ void operator()(command_status_cb status_callback, void* context,
+ std::unique_ptr<OsiObject> command,
+ bluetooth::hci::CommandStatusView view) {
+ body(status_callback, context, std::move(command), view);
+ };
+};
+extern struct OnTransmitPacketStatus OnTransmitPacketStatus;
+
+// Name: hci_layer_get_interface
+// Params:
+// Return: const hci_t*
+struct hci_layer_get_interface {
+ static const hci_t* return_value;
+ std::function<const hci_t*()> body{[]() { return return_value; }};
+ const hci_t* operator()() { return body(); };
+};
+extern struct hci_layer_get_interface hci_layer_get_interface;
+
+// Name: hci_on_reset_complete
+// Params:
+// Return: void
+struct hci_on_reset_complete {
+ std::function<void()> body{[]() {}};
+ void operator()() { body(); };
+};
+extern struct hci_on_reset_complete hci_on_reset_complete;
+
+// Name: hci_on_shutting_down
+// Params:
+// Return: void
+struct hci_on_shutting_down {
+ std::function<void()> body{[]() {}};
+ void operator()() { body(); };
+};
+extern struct hci_on_shutting_down hci_on_shutting_down;
+
+} // namespace main_shim_hci_layer
+} // namespace mock
+} // namespace test
+
+// END mockcify generation
diff --git a/system/test/mock/mock_osi_allocator.cc b/system/test/mock/mock_osi_allocator.cc
index 224d51e..5702c41 100644
--- a/system/test/mock/mock_osi_allocator.cc
+++ b/system/test/mock/mock_osi_allocator.cc
@@ -23,10 +23,26 @@
// Mock include file to share data between tests and mock
#include "test/mock/mock_osi_allocator.h"
+#include "osi/include/allocator.h"
#include "test/common/mock_functions.h"
// Mocked internal structures, if any
+OsiObject::OsiObject(void* ptr) : ptr_(ptr) {}
+
+OsiObject::OsiObject(const void* ptr) : ptr_(const_cast<void*>(ptr)) {}
+
+OsiObject::~OsiObject() {
+ if (ptr_ != nullptr) {
+ osi_free(ptr_);
+ }
+}
+
+void* OsiObject::Release() {
+ void* ptr = ptr_;
+ ptr_ = nullptr;
+ return ptr;
+}
namespace test {
namespace mock {
namespace osi_allocator {
diff --git a/system/test/mock/mock_stack_acl_btm_pm.cc b/system/test/mock/mock_stack_acl_btm_pm.cc
index 99f8344..abbc88e 100644
--- a/system/test/mock/mock_stack_acl_btm_pm.cc
+++ b/system/test/mock/mock_stack_acl_btm_pm.cc
@@ -41,6 +41,22 @@
inc_func_call_count(__func__);
return BTM_CONTRL_UNKNOWN;
}
+uint8_t BTM_PM_ReadSniffLinkCount(void) {
+ inc_func_call_count(__func__);
+ return 0;
+}
+uint8_t BTM_PM_ReadBleLinkCount(void) {
+ inc_func_call_count(__func__);
+ return 0;
+}
+bool BTM_PM_DeviceInScanState(void) {
+ inc_func_call_count(__func__);
+ return false;
+}
+uint32_t BTM_PM_ReadBleScanDutyCycle(void) {
+ inc_func_call_count(__func__);
+ return 0;
+}
tBTM_STATUS BTM_PmRegister(uint8_t /* mask */, uint8_t* /* p_pm_id */,
tBTM_PM_STATUS_CBACK* /* p_cb */) {
inc_func_call_count(__func__);
diff --git a/system/test/mock/mock_stack_btm_ble_gap.cc b/system/test/mock/mock_stack_btm_ble_gap.cc
index eb854f5..ed466dd 100644
--- a/system/test/mock/mock_stack_btm_ble_gap.cc
+++ b/system/test/mock/mock_stack_btm_ble_gap.cc
@@ -146,10 +146,6 @@
tBLE_ADDR_TYPE* /* addr_type */) {
inc_func_call_count(__func__);
}
-void btm_ble_process_adv_pkt(uint8_t /* data_len */,
- const uint8_t* /* data */) {
- inc_func_call_count(__func__);
-}
void btm_ble_process_adv_pkt_cont(
uint16_t /* evt_type */, tBLE_ADDR_TYPE /* addr_type */,
const RawAddress& /* bda */, uint8_t /* primary_phy */,
@@ -167,13 +163,6 @@
std::vector<uint8_t> /* advertising_data */) {
inc_func_call_count(__func__);
}
-void btm_ble_process_ext_adv_pkt(uint8_t /* data_len */,
- const uint8_t* /* data */) {
- inc_func_call_count(__func__);
-}
-void btm_ble_process_phy_update_pkt(uint8_t /* len */, uint8_t* /* data */) {
- inc_func_call_count(__func__);
-}
void btm_ble_read_remote_features_complete(uint8_t* /* p */,
uint8_t /* length */) {
inc_func_call_count(__func__);
diff --git a/system/test/mock/mock_stack_btm_inq.cc b/system/test/mock/mock_stack_btm_inq.cc
index 8ff677f..9fc34e8 100644
--- a/system/test/mock/mock_stack_btm_inq.cc
+++ b/system/test/mock/mock_stack_btm_inq.cc
@@ -69,7 +69,6 @@
struct btm_inq_remote_name_timer_timeout btm_inq_remote_name_timer_timeout;
struct btm_inq_rmt_name_failed_cancelled btm_inq_rmt_name_failed_cancelled;
struct btm_inq_stop_on_ssp btm_inq_stop_on_ssp;
-struct btm_process_cancel_complete btm_process_cancel_complete;
struct btm_process_inq_complete btm_process_inq_complete;
struct btm_process_inq_results btm_process_inq_results;
struct btm_process_remote_name btm_process_remote_name;
@@ -256,10 +255,6 @@
inc_func_call_count(__func__);
test::mock::stack_btm_inq::btm_inq_stop_on_ssp();
}
-void btm_process_cancel_complete(tHCI_STATUS status, uint8_t mode) {
- inc_func_call_count(__func__);
- test::mock::stack_btm_inq::btm_process_cancel_complete(status, mode);
-}
void btm_process_inq_complete(tHCI_STATUS status, uint8_t mode) {
inc_func_call_count(__func__);
test::mock::stack_btm_inq::btm_process_inq_complete(status, mode);
diff --git a/system/test/mock/mock_stack_btm_inq.h b/system/test/mock/mock_stack_btm_inq.h
index 7ac6d12..ab805ab 100644
--- a/system/test/mock/mock_stack_btm_inq.h
+++ b/system/test/mock/mock_stack_btm_inq.h
@@ -429,16 +429,6 @@
};
extern struct btm_inq_stop_on_ssp btm_inq_stop_on_ssp;
-// Name: btm_process_cancel_complete
-// Params: tHCI_STATUS status, uint8_t mode
-// Return: void
-struct btm_process_cancel_complete {
- std::function<void(tHCI_STATUS status, uint8_t mode)> body{
- [](tHCI_STATUS /* status */, uint8_t /* mode */) {}};
- void operator()(tHCI_STATUS status, uint8_t mode) { body(status, mode); };
-};
-extern struct btm_process_cancel_complete btm_process_cancel_complete;
-
// Name: btm_process_inq_complete
// Params: tHCI_STATUS status, uint8_t mode
// Return: void
diff --git a/system/test/mock/mock_stack_btu_hcif.cc b/system/test/mock/mock_stack_btu_hcif.cc
index ba99679..e525c92 100644
--- a/system/test/mock/mock_stack_btu_hcif.cc
+++ b/system/test/mock/mock_stack_btu_hcif.cc
@@ -38,20 +38,20 @@
base::Location posted_from;
};
-void btu_hcif_process_event(uint8_t controller_id, BT_HDR* p_msg) {
+void btu_hcif_process_event(uint8_t /* controller_id */, BT_HDR* /* p_msg */) {
inc_func_call_count(__func__);
}
-void btu_hcif_send_cmd(uint8_t controller_id, const BT_HDR* p_buf) {
+void btu_hcif_send_cmd(uint8_t /* controller_id */, const BT_HDR* /* p_buf */) {
inc_func_call_count(__func__);
}
-void btu_hcif_send_cmd_with_cb(const base::Location& posted_from,
- uint16_t opcode, uint8_t* params,
- uint8_t params_len, hci_cmd_cb cb) {
+void btu_hcif_send_cmd_with_cb(const base::Location& /* posted_from */,
+ uint16_t /* opcode */, uint8_t* /* params */,
+ uint8_t /* params_len */, hci_cmd_cb /* cb */) {
inc_func_call_count(__func__);
}
-void cmd_with_cb_data_cleanup(cmd_with_cb_data* cb_wrapper) {
+void cmd_with_cb_data_cleanup(cmd_with_cb_data* /* cb_wrapper */) {
inc_func_call_count(__func__);
}
-void cmd_with_cb_data_init(cmd_with_cb_data* cb_wrapper) {
+void cmd_with_cb_data_init(cmd_with_cb_data* /* cb_wrapper */) {
inc_func_call_count(__func__);
}
diff --git a/system/test/mock/mock_stack_hcic_hciblecmds.h b/system/test/mock/mock_stack_hcic_hciblecmds.h
index 5d9b576..ef68736 100644
--- a/system/test/mock/mock_stack_hcic_hciblecmds.h
+++ b/system/test/mock/mock_stack_hcic_hciblecmds.h
@@ -45,9 +45,9 @@
struct btsnd_hci_ble_add_device_to_periodic_advertiser_list {
std::function<void(uint8_t, const RawAddress&, uint8_t,
base::OnceCallback<void(uint8_t*, uint16_t)>)>
- body{[](uint8_t adv_addr_type, const RawAddress& adv_addr,
- uint8_t adv_sid,
- base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}};
+ body{[](uint8_t /* adv_addr_type */, const RawAddress& /* adv_addr */,
+ uint8_t /* adv_sid */,
+ base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}};
void operator()(uint8_t adv_addr_type, const RawAddress& adv_addr,
uint8_t adv_sid,
base::OnceCallback<void(uint8_t*, uint16_t)> cb) {
@@ -76,9 +76,9 @@
struct btsnd_hci_ble_remove_device_from_periodic_advertiser_list {
std::function<void(uint8_t, const RawAddress&, uint8_t,
base::OnceCallback<void(uint8_t*, uint16_t)>)>
- body{[](uint8_t adv_addr_type, const RawAddress& adv_addr,
- uint8_t adv_sid,
- base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}};
+ body{[](uint8_t /* adv_addr_type */, const RawAddress& /* adv_addr */,
+ uint8_t /* adv_sid */,
+ base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}};
void operator()(uint8_t adv_addr_type, const RawAddress& adv_addr,
uint8_t adv_sid,
base::OnceCallback<void(uint8_t*, uint16_t)> cb) {
@@ -92,7 +92,8 @@
// Params: uint16_t conn_handle
// Return: void
struct btsnd_hcic_accept_cis_req {
- std::function<void(uint16_t conn_handle)> body{[](uint16_t conn_handle) {}};
+ std::function<void(uint16_t conn_handle)> body{
+ [](uint16_t /* conn_handle */) {}};
void operator()(uint16_t conn_handle) { body(conn_handle); };
};
extern struct btsnd_hcic_accept_cis_req btsnd_hcic_accept_cis_req;
@@ -103,8 +104,9 @@
struct btsnd_hcic_ble_add_device_resolving_list {
std::function<void(uint8_t addr_type_peer, const RawAddress& bda_peer,
const Octet16& irk_peer, const Octet16& irk_local)>
- body{[](uint8_t addr_type_peer, const RawAddress& bda_peer,
- const Octet16& irk_peer, const Octet16& irk_local) {}};
+ body{[](uint8_t /* addr_type_peer */, const RawAddress& /* bda_peer */,
+ const Octet16& /* irk_peer */,
+ const Octet16& /* irk_local */) {}};
void operator()(uint8_t addr_type_peer, const RawAddress& bda_peer,
const Octet16& irk_peer, const Octet16& irk_local) {
body(addr_type_peer, bda_peer, irk_peer, irk_local);
@@ -128,7 +130,7 @@
// Return: void
struct btsnd_hcic_ble_enh_rx_test {
std::function<void(uint8_t rx_chan, uint8_t phy, uint8_t mod_index)> body{
- [](uint8_t rx_chan, uint8_t phy, uint8_t mod_index) {}};
+ [](uint8_t /* rx_chan */, uint8_t /* phy */, uint8_t /* mod_index */) {}};
void operator()(uint8_t rx_chan, uint8_t phy, uint8_t mod_index) {
body(rx_chan, phy, mod_index);
};
@@ -141,8 +143,8 @@
struct btsnd_hcic_ble_enh_tx_test {
std::function<void(uint8_t tx_chan, uint8_t data_len, uint8_t payload,
uint8_t phy)>
- body{[](uint8_t tx_chan, uint8_t data_len, uint8_t payload, uint8_t phy) {
- }};
+ body{[](uint8_t /* tx_chan */, uint8_t /* data_len */,
+ uint8_t /* payload */, uint8_t /* phy */) {}};
void operator()(uint8_t tx_chan, uint8_t data_len, uint8_t payload,
uint8_t phy) {
body(tx_chan, data_len, payload, phy);
@@ -154,7 +156,7 @@
// Params: uint16_t handle
// Return: void
struct btsnd_hcic_ble_ltk_req_neg_reply {
- std::function<void(uint16_t handle)> body{[](uint16_t handle) {}};
+ std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) {}};
void operator()(uint16_t handle) { body(handle); };
};
extern struct btsnd_hcic_ble_ltk_req_neg_reply btsnd_hcic_ble_ltk_req_neg_reply;
@@ -164,7 +166,7 @@
// Return: void
struct btsnd_hcic_ble_ltk_req_reply {
std::function<void(uint16_t handle, const Octet16& ltk)> body{
- [](uint16_t handle, const Octet16& ltk) {}};
+ [](uint16_t /* handle */, const Octet16& /* ltk */) {}};
void operator()(uint16_t handle, const Octet16& ltk) { body(handle, ltk); };
};
extern struct btsnd_hcic_ble_ltk_req_reply btsnd_hcic_ble_ltk_req_reply;
@@ -177,9 +179,10 @@
std::function<void(uint8_t options, uint8_t adv_sid, uint8_t adv_addr_type,
const RawAddress& adv_addr, uint16_t skip_num,
uint16_t sync_timeout, uint8_t sync_cte_type)>
- body{[](uint8_t options, uint8_t adv_sid, uint8_t adv_addr_type,
- const RawAddress& adv_addr, uint16_t skip_num,
- uint16_t sync_timeout, uint8_t sync_cte_type) {}};
+ body{[](uint8_t /* options */, uint8_t /* adv_sid */,
+ uint8_t /* adv_addr_type */, const RawAddress& /* adv_addr */,
+ uint16_t /* skip_num */, uint16_t /* sync_timeout */,
+ uint8_t /* sync_cte_type */) {}};
void operator()(uint8_t options, uint8_t adv_sid, uint8_t adv_addr_type,
const RawAddress& adv_addr, uint16_t skip_num,
uint16_t sync_timeout, uint8_t sync_cte_type) {
@@ -195,7 +198,7 @@
// Return: void
struct btsnd_hcic_ble_periodic_advertising_create_sync_cancel {
std::function<void(base::OnceCallback<void(uint8_t*, uint16_t)>)> body{
- [](base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}};
+ [](base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}};
void operator()(base::OnceCallback<void(uint8_t*, uint16_t)> cb) {
body(std::move(cb));
};
@@ -209,8 +212,9 @@
struct btsnd_hcic_ble_periodic_advertising_set_info_transfer {
std::function<void(uint16_t, uint16_t, uint8_t,
base::OnceCallback<void(uint8_t*, uint16_t)>)>
- body{[](uint16_t conn_handle, uint16_t service_data, uint8_t adv_handle,
- base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}};
+ body{[](uint16_t /* conn_handle */, uint16_t /* service_data */,
+ uint8_t /* adv_handle */,
+ base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}};
void operator()(uint16_t conn_handle, uint16_t service_data,
uint8_t adv_handle,
base::OnceCallback<void(uint8_t*, uint16_t)> cb) {
@@ -226,8 +230,9 @@
struct btsnd_hcic_ble_periodic_advertising_sync_transfer {
std::function<void(uint16_t, uint16_t, uint16_t,
base::OnceCallback<void(uint8_t*, uint16_t)>)>
- body{[](uint16_t conn_handle, uint16_t service_data, uint16_t sync_handle,
- base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}};
+ body{[](uint16_t /* conn_handle */, uint16_t /* service_data */,
+ uint16_t /* sync_handle */,
+ base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}};
void operator()(uint16_t conn_handle, uint16_t service_data,
uint16_t sync_handle,
base::OnceCallback<void(uint8_t*, uint16_t)> cb) {
@@ -242,8 +247,8 @@
// Return: void
struct btsnd_hcic_ble_periodic_advertising_terminate_sync {
std::function<void(uint16_t, base::OnceCallback<void(uint8_t*, uint16_t)>)>
- body{[](uint16_t sync_handle,
- base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}};
+ body{[](uint16_t /* sync_handle */,
+ base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}};
void operator()(uint16_t sync_handle,
base::OnceCallback<void(uint8_t*, uint16_t)> cb) {
body(sync_handle, std::move(cb));
@@ -257,7 +262,7 @@
// Return: void
struct btsnd_hcic_ble_rand {
std::function<void(base::Callback<void(BT_OCTET8)>)> body{
- [](base::Callback<void(BT_OCTET8)> cb) {}};
+ [](base::Callback<void(BT_OCTET8)> /* cb */) {}};
void operator()(base::Callback<void(BT_OCTET8)> cb) { body(std::move(cb)); };
};
extern struct btsnd_hcic_ble_rand btsnd_hcic_ble_rand;
@@ -267,7 +272,7 @@
// Return: void
struct btsnd_hcic_ble_rc_param_req_neg_reply {
std::function<void(uint16_t handle, uint8_t reason)> body{
- [](uint16_t handle, uint8_t reason) {}};
+ [](uint16_t /* handle */, uint8_t /* reason */) {}};
void operator()(uint16_t handle, uint8_t reason) { body(handle, reason); };
};
extern struct btsnd_hcic_ble_rc_param_req_neg_reply
@@ -282,9 +287,10 @@
uint16_t conn_int_max, uint16_t conn_latency,
uint16_t conn_timeout, uint16_t min_ce_len,
uint16_t max_ce_len)>
- body{[](uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max,
- uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len,
- uint16_t max_ce_len) {}};
+ body{[](uint16_t /* handle */, uint16_t /* conn_int_min */,
+ uint16_t /* conn_int_max */, uint16_t /* conn_latency */,
+ uint16_t /* conn_timeout */, uint16_t /* min_ce_len */,
+ uint16_t /* max_ce_len */) {}};
void operator()(uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max,
uint16_t conn_latency, uint16_t conn_timeout,
uint16_t min_ce_len, uint16_t max_ce_len) {
@@ -309,7 +315,7 @@
// Params: uint16_t handle
// Return: void
struct btsnd_hcic_ble_read_remote_feat {
- std::function<void(uint16_t handle)> body{[](uint16_t handle) {}};
+ std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) {}};
void operator()(uint16_t handle) { body(handle); };
};
extern struct btsnd_hcic_ble_read_remote_feat btsnd_hcic_ble_read_remote_feat;
@@ -319,7 +325,7 @@
// Return: void
struct btsnd_hcic_ble_read_resolvable_addr_peer {
std::function<void(uint8_t addr_type_peer, const RawAddress& bda_peer)> body{
- [](uint8_t addr_type_peer, const RawAddress& bda_peer) {}};
+ [](uint8_t /* addr_type_peer */, const RawAddress& /* bda_peer */) {}};
void operator()(uint8_t addr_type_peer, const RawAddress& bda_peer) {
body(addr_type_peer, bda_peer);
};
@@ -331,7 +337,7 @@
// Params: uint8_t rx_freq
// Return: void
struct btsnd_hcic_ble_receiver_test {
- std::function<void(uint8_t rx_freq)> body{[](uint8_t rx_freq) {}};
+ std::function<void(uint8_t rx_freq)> body{[](uint8_t /* rx_freq */) {}};
void operator()(uint8_t rx_freq) { body(rx_freq); };
};
extern struct btsnd_hcic_ble_receiver_test btsnd_hcic_ble_receiver_test;
@@ -341,7 +347,7 @@
// Return: void
struct btsnd_hcic_ble_rm_device_resolving_list {
std::function<void(uint8_t addr_type_peer, const RawAddress& bda_peer)> body{
- [](uint8_t addr_type_peer, const RawAddress& bda_peer) {}};
+ [](uint8_t /* addr_type_peer */, const RawAddress& /* bda_peer */) {}};
void operator()(uint8_t addr_type_peer, const RawAddress& bda_peer) {
body(addr_type_peer, bda_peer);
};
@@ -354,7 +360,7 @@
// Return: void
struct btsnd_hcic_ble_set_adv_data {
std::function<void(uint8_t data_len, uint8_t* p_data)> body{
- [](uint8_t data_len, uint8_t* p_data) {}};
+ [](uint8_t /* data_len */, uint8_t* /* p_data */) {}};
void operator()(uint8_t data_len, uint8_t* p_data) {
body(data_len, p_data);
};
@@ -365,7 +371,7 @@
// Params: uint8_t adv_enable
// Return: void
struct btsnd_hcic_ble_set_adv_enable {
- std::function<void(uint8_t adv_enable)> body{[](uint8_t adv_enable) {}};
+ std::function<void(uint8_t adv_enable)> body{[](uint8_t /* adv_enable */) {}};
void operator()(uint8_t adv_enable) { body(adv_enable); };
};
extern struct btsnd_hcic_ble_set_adv_enable btsnd_hcic_ble_set_adv_enable;
@@ -376,7 +382,8 @@
struct btsnd_hcic_ble_set_data_length {
std::function<void(uint16_t conn_handle, uint16_t tx_octets,
uint16_t tx_time)>
- body{[](uint16_t conn_handle, uint16_t tx_octets, uint16_t tx_time) {}};
+ body{[](uint16_t /* conn_handle */, uint16_t /* tx_octets */,
+ uint16_t /* tx_time */) {}};
void operator()(uint16_t conn_handle, uint16_t tx_octets, uint16_t tx_time) {
body(conn_handle, tx_octets, tx_time);
};
@@ -390,9 +397,10 @@
struct btsnd_hcic_ble_set_default_periodic_advertising_sync_transfer_params {
std::function<void(uint16_t, uint8_t, uint16_t, uint16_t, uint8_t,
base::OnceCallback<void(uint8_t*, uint16_t)>)>
- body{[](uint16_t conn_handle, uint8_t mode, uint16_t skip,
- uint16_t sync_timeout, uint8_t cte_type,
- base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}};
+ body{[](uint16_t /* conn_handle */, uint8_t /* mode */,
+ uint16_t /* skip */, uint16_t /* sync_timeout */,
+ uint8_t /* cte_type */,
+ base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}};
void operator()(uint16_t conn_handle, uint8_t mode, uint16_t skip,
uint16_t sync_timeout, uint8_t cte_type,
base::OnceCallback<void(uint8_t*, uint16_t)> cb) {
@@ -409,8 +417,8 @@
struct btsnd_hcic_ble_set_extended_scan_enable {
std::function<void(uint8_t enable, uint8_t filter_duplicates,
uint16_t duration, uint16_t period)>
- body{[](uint8_t enable, uint8_t filter_duplicates, uint16_t duration,
- uint16_t period) {}};
+ body{[](uint8_t /* enable */, uint8_t /* filter_duplicates */,
+ uint16_t /* duration */, uint16_t /* period */) {}};
void operator()(uint8_t enable, uint8_t filter_duplicates, uint16_t duration,
uint16_t period) {
body(enable, filter_duplicates, duration, period);
@@ -425,8 +433,9 @@
struct btsnd_hcic_ble_set_extended_scan_params {
std::function<void(uint8_t own_address_type, uint8_t scanning_filter_policy,
uint8_t scanning_phys, scanning_phy_cfg* phy_cfg)>
- body{[](uint8_t own_address_type, uint8_t scanning_filter_policy,
- uint8_t scanning_phys, scanning_phy_cfg* phy_cfg) {}};
+ body{[](uint8_t /* own_address_type */,
+ uint8_t /* scanning_filter_policy */, uint8_t /* scanning_phys */,
+ scanning_phy_cfg* /* phy_cfg */) {}};
void operator()(uint8_t own_address_type, uint8_t scanning_filter_policy,
uint8_t scanning_phys, scanning_phy_cfg* phy_cfg) {
body(own_address_type, scanning_filter_policy, scanning_phys, phy_cfg);
@@ -441,8 +450,8 @@
struct btsnd_hcic_ble_set_periodic_advertising_receive_enable {
std::function<void(uint16_t, bool,
base::OnceCallback<void(uint8_t*, uint16_t)>)>
- body{[](uint16_t sync_handle, bool enable,
- base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}};
+ body{[](uint16_t /* sync_handle */, bool /* enable */,
+ base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}};
void operator()(uint16_t sync_handle, bool enable,
base::OnceCallback<void(uint8_t*, uint16_t)> cb) {
body(sync_handle, enable, std::move(cb));
@@ -458,9 +467,10 @@
struct btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params {
std::function<void(uint16_t, uint8_t, uint16_t, uint16_t, uint8_t,
base::OnceCallback<void(uint8_t*, uint16_t)>)>
- body{[](uint16_t conn_handle, uint8_t mode, uint16_t skip,
- uint16_t sync_timeout, uint8_t cte_type,
- base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}};
+ body{[](uint16_t /* conn_handle */, uint8_t /* mode */,
+ uint16_t /* skip */, uint16_t /* sync_timeout */,
+ uint8_t /* cte_type */,
+ base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}};
void operator()(uint16_t conn_handle, uint8_t mode, uint16_t skip,
uint16_t sync_timeout, uint8_t cte_type,
base::OnceCallback<void(uint8_t*, uint16_t)> cb) {
@@ -476,8 +486,8 @@
struct btsnd_hcic_ble_set_privacy_mode {
std::function<void(uint8_t addr_type_peer, const RawAddress& bda_peer,
uint8_t privacy_type)>
- body{[](uint8_t addr_type_peer, const RawAddress& bda_peer,
- uint8_t privacy_type) {}};
+ body{[](uint8_t /* addr_type_peer */, const RawAddress& /* bda_peer */,
+ uint8_t /* privacy_type */) {}};
void operator()(uint8_t addr_type_peer, const RawAddress& bda_peer,
uint8_t privacy_type) {
body(addr_type_peer, bda_peer, privacy_type);
@@ -489,7 +499,8 @@
// Params: uint16_t rpa_timout
// Return: void
struct btsnd_hcic_ble_set_rand_priv_addr_timeout {
- std::function<void(uint16_t rpa_timout)> body{[](uint16_t rpa_timout) {}};
+ std::function<void(uint16_t rpa_timout)> body{
+ [](uint16_t /* rpa_timout */) {}};
void operator()(uint16_t rpa_timout) { body(rpa_timout); };
};
extern struct btsnd_hcic_ble_set_rand_priv_addr_timeout
@@ -500,7 +511,7 @@
// Return: void
struct btsnd_hcic_ble_set_scan_enable {
std::function<void(uint8_t scan_enable, uint8_t duplicate)> body{
- [](uint8_t scan_enable, uint8_t duplicate) {}};
+ [](uint8_t /* scan_enable */, uint8_t /* duplicate */) {}};
void operator()(uint8_t scan_enable, uint8_t duplicate) {
body(scan_enable, duplicate);
};
@@ -513,8 +524,9 @@
struct btsnd_hcic_ble_set_scan_params {
std::function<void(uint8_t scan_type, uint16_t scan_int, uint16_t scan_win,
uint8_t addr_type_own, uint8_t scan_filter_policy)>
- body{[](uint8_t scan_type, uint16_t scan_int, uint16_t scan_win,
- uint8_t addr_type_own, uint8_t scan_filter_policy) {}};
+ body{[](uint8_t /* scan_type */, uint16_t /* scan_int */,
+ uint16_t /* scan_win */, uint8_t /* addr_type_own */,
+ uint8_t /* scan_filter_policy */) {}};
void operator()(uint8_t scan_type, uint16_t scan_int, uint16_t scan_win,
uint8_t addr_type_own, uint8_t scan_filter_policy) {
body(scan_type, scan_int, scan_win, addr_type_own, scan_filter_policy);
@@ -528,8 +540,8 @@
struct btsnd_hcic_ble_start_enc {
std::function<void(uint16_t handle, uint8_t rand[HCIC_BLE_RAND_DI_SIZE],
uint16_t ediv, const Octet16& ltk)>
- body{[](uint16_t handle, uint8_t rand[HCIC_BLE_RAND_DI_SIZE],
- uint16_t ediv, const Octet16& ltk) {}};
+ body{[](uint16_t /* handle */, uint8_t[HCIC_BLE_RAND_DI_SIZE] /* rand */,
+ uint16_t /* ediv */, const Octet16& /* ltk */) {}};
void operator()(uint16_t handle, uint8_t rand[HCIC_BLE_RAND_DI_SIZE],
uint16_t ediv, const Octet16& ltk) {
body(handle, rand, ediv, ltk);
@@ -551,7 +563,8 @@
// Return: void
struct btsnd_hcic_ble_transmitter_test {
std::function<void(uint8_t tx_freq, uint8_t test_data_len, uint8_t payload)>
- body{[](uint8_t tx_freq, uint8_t test_data_len, uint8_t payload) {}};
+ body{[](uint8_t /* tx_freq */, uint8_t /* test_data_len */,
+ uint8_t /* payload */) {}};
void operator()(uint8_t tx_freq, uint8_t test_data_len, uint8_t payload) {
body(tx_freq, test_data_len, payload);
};
@@ -567,9 +580,10 @@
uint16_t conn_int_max, uint16_t conn_latency,
uint16_t conn_timeout, uint16_t min_ce_len,
uint16_t max_ce_len)>
- body{[](uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max,
- uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len,
- uint16_t max_ce_len) {}};
+ body{[](uint16_t /* handle */, uint16_t /* conn_int_min */,
+ uint16_t /* conn_int_max */, uint16_t /* conn_latency */,
+ uint16_t /* conn_timeout */, uint16_t /* min_ce_len */,
+ uint16_t /* max_ce_len */) {}};
void operator()(uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max,
uint16_t conn_latency, uint16_t conn_timeout,
uint16_t min_ce_len, uint16_t max_ce_len) {
@@ -589,10 +603,11 @@
uint8_t adv_type, tBLE_ADDR_TYPE addr_type_own,
tBLE_ADDR_TYPE addr_type_dir, const RawAddress& direct_bda,
uint8_t channel_map, uint8_t adv_filter_policy)>
- body{[](uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
- tBLE_ADDR_TYPE addr_type_own, tBLE_ADDR_TYPE addr_type_dir,
- const RawAddress& direct_bda, uint8_t channel_map,
- uint8_t adv_filter_policy) {}};
+ body{[](uint16_t /* adv_int_min */, uint16_t /* adv_int_max */,
+ uint8_t /* adv_type */, tBLE_ADDR_TYPE /* addr_type_own */,
+ tBLE_ADDR_TYPE /* addr_type_dir */,
+ const RawAddress& /* direct_bda */, uint8_t /* channel_map */,
+ uint8_t /* adv_filter_policy */) {}};
void operator()(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
tBLE_ADDR_TYPE addr_type_own, tBLE_ADDR_TYPE addr_type_dir,
const RawAddress& direct_bda, uint8_t channel_map,
@@ -614,11 +629,12 @@
uint16_t transport_latency, uint8_t rtn, uint8_t phy,
uint8_t packing, uint8_t framing, uint8_t enc,
std::array<uint8_t, 16> bcst_code)>
- body{[](uint8_t big_handle, uint8_t adv_handle, uint8_t num_bis,
- uint32_t sdu_itv, uint16_t max_sdu_size,
- uint16_t transport_latency, uint8_t rtn, uint8_t phy,
- uint8_t packing, uint8_t framing, uint8_t enc,
- std::array<uint8_t, 16> bcst_code) {}};
+ body{[](uint8_t /* big_handle */, uint8_t /* adv_handle */,
+ uint8_t /* num_bis */, uint32_t /* sdu_itv */,
+ uint16_t /* max_sdu_size */, uint16_t /* transport_latency */,
+ uint8_t /* rtn */, uint8_t /* phy */, uint8_t /* packing */,
+ uint8_t /* framing */, uint8_t /* enc */,
+ std::array<uint8_t, 16> /* bcst_code */) {}};
void operator()(uint8_t big_handle, uint8_t adv_handle, uint8_t num_bis,
uint32_t sdu_itv, uint16_t max_sdu_size,
uint16_t transport_latency, uint8_t rtn, uint8_t phy,
@@ -636,8 +652,8 @@
struct btsnd_hcic_create_cis {
std::function<void(uint8_t, const EXT_CIS_CREATE_CFG*,
base::OnceCallback<void(uint8_t*, uint16_t)>)>
- body{[](uint8_t num_cis, const EXT_CIS_CREATE_CFG* cis_cfg,
- base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}};
+ body{[](uint8_t /* num_cis */, const EXT_CIS_CREATE_CFG* /* cis_cfg */,
+ base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}};
void operator()(uint8_t num_cis, const EXT_CIS_CREATE_CFG* cis_cfg,
base::OnceCallback<void(uint8_t*, uint16_t)> cb) {
body(num_cis, cis_cfg, std::move(cb));
@@ -650,7 +666,7 @@
// Return: void
struct btsnd_hcic_read_iso_link_quality {
std::function<void(uint16_t, base::OnceCallback<void(uint8_t*, uint16_t)>)>
- body{[](uint16_t iso_handle,
+ body{[](uint16_t /* iso_handle */,
base::OnceCallback<void(uint8_t*, uint16_t)>) {}};
void operator()(uint16_t iso_handle,
base::OnceCallback<void(uint8_t*, uint16_t)> cb) {
@@ -665,8 +681,8 @@
struct btsnd_hcic_rej_cis_req {
std::function<void(uint16_t, uint8_t,
base::OnceCallback<void(uint8_t*, uint16_t)>)>
- body{[](uint16_t conn_handle, uint8_t reason,
- base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}};
+ body{[](uint16_t /* conn_handle */, uint8_t /* reason */,
+ base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}};
void operator()(uint16_t conn_handle, uint8_t reason,
base::OnceCallback<void(uint8_t*, uint16_t)> cb) {
body(conn_handle, reason, std::move(cb));
@@ -679,8 +695,8 @@
// Return: void
struct btsnd_hcic_remove_cig {
std::function<void(uint8_t, base::OnceCallback<void(uint8_t*, uint16_t)>)>
- body{[](uint8_t cig_id, base::OnceCallback<void(uint8_t*, uint16_t)> cb) {
- }};
+ body{[](uint8_t /* cig_id */,
+ base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}};
void operator()(uint8_t cig_id,
base::OnceCallback<void(uint8_t*, uint16_t)> cb) {
body(cig_id, std::move(cb));
@@ -694,8 +710,8 @@
struct btsnd_hcic_remove_iso_data_path {
std::function<void(uint16_t, uint8_t,
base::OnceCallback<void(uint8_t*, uint16_t)>)>
- body{[](uint16_t iso_handle, uint8_t data_path_dir,
- base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}};
+ body{[](uint16_t /* iso_handle */, uint8_t /* data_path_dir */,
+ base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}};
void operator()(uint16_t iso_handle, uint8_t data_path_dir,
base::OnceCallback<void(uint8_t*, uint16_t)> cb) {
body(iso_handle, data_path_dir, std::move(cb));
@@ -707,7 +723,7 @@
// Params: uint16_t conn_handle
// Return: void
struct btsnd_hcic_req_peer_sca {
- std::function<void(uint16_t)> body{[](uint16_t conn_handle) {}};
+ std::function<void(uint16_t)> body{[](uint16_t /* conn_handle */) {}};
void operator()(uint16_t conn_handle) { body(conn_handle); };
};
extern struct btsnd_hcic_req_peer_sca btsnd_hcic_req_peer_sca;
@@ -721,11 +737,13 @@
std::function<void(uint8_t, uint32_t, uint32_t, uint8_t, uint8_t, uint8_t,
uint16_t, uint16_t, uint8_t, const EXT_CIS_CFG*,
base::OnceCallback<void(uint8_t*, uint16_t)>)>
- body{[](uint8_t cig_id, uint32_t sdu_itv_mtos, uint32_t sdu_itv_stom,
- uint8_t sca, uint8_t packing, uint8_t framing,
- uint16_t max_trans_lat_stom, uint16_t max_trans_lat_mtos,
- uint8_t cis_cnt, const EXT_CIS_CFG* cis_cfg,
- base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}};
+ body{[](uint8_t /* cig_id */, uint32_t /* sdu_itv_mtos */,
+ uint32_t /* sdu_itv_stom */, uint8_t /* sca */,
+ uint8_t /* packing */, uint8_t /* framing */,
+ uint16_t /* max_trans_lat_stom */,
+ uint16_t /* max_trans_lat_mtos */, uint8_t /* cis_cnt */,
+ const EXT_CIS_CFG* /* cis_cfg */,
+ base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}};
void operator()(uint8_t cig_id, uint32_t sdu_itv_mtos, uint32_t sdu_itv_stom,
uint8_t sca, uint8_t packing, uint8_t framing,
uint16_t max_trans_lat_stom, uint16_t max_trans_lat_mtos,
@@ -747,11 +765,12 @@
std::function<void(uint16_t, uint8_t, uint8_t, uint8_t, uint16_t, uint16_t,
uint32_t, std::vector<uint8_t>,
base::OnceCallback<void(uint8_t*, uint16_t)>)>
- body{[](uint16_t iso_handle, uint8_t data_path_dir, uint8_t data_path_id,
- uint8_t codec_id_format, uint16_t codec_id_company,
- uint16_t codec_id_vendor, uint32_t controller_delay,
- std::vector<uint8_t> codec_conf,
- base::OnceCallback<void(uint8_t*, uint16_t)> cb) {}};
+ body{[](uint16_t /* iso_handle */, uint8_t /* data_path_dir */,
+ uint8_t /* data_path_id */, uint8_t /* codec_id_format */,
+ uint16_t /* codec_id_company */, uint16_t /* codec_id_vendor */,
+ uint32_t /* controller_delay */,
+ std::vector<uint8_t> /* codec_conf */,
+ base::OnceCallback<void(uint8_t*, uint16_t)> /* cb */) {}};
void operator()(uint16_t iso_handle, uint8_t data_path_dir,
uint8_t data_path_id, uint8_t codec_id_format,
uint16_t codec_id_company, uint16_t codec_id_vendor,
@@ -769,7 +788,7 @@
// Return: void
struct btsnd_hcic_term_big {
std::function<void(uint8_t, uint8_t)> body{
- [](uint8_t big_handle, uint8_t reason) {}};
+ [](uint8_t /* big_handle */, uint8_t /* reason */) {}};
void operator()(uint8_t big_handle, uint8_t reason) {
body(big_handle, reason);
};
diff --git a/system/test/mock/mock_stack_hcic_hcicmds.h b/system/test/mock/mock_stack_hcic_hcicmds.h
index b0d5d3e..232a60f 100644
--- a/system/test/mock/mock_stack_hcic_hcicmds.h
+++ b/system/test/mock/mock_stack_hcic_hcicmds.h
@@ -44,7 +44,7 @@
// Return: void
struct btsnd_hcic_accept_conn {
std::function<void(const RawAddress& dest, uint8_t role)> body{
- [](const RawAddress& dest, uint8_t role) {}};
+ [](const RawAddress& /* dest */, uint8_t /* role */) {}};
void operator()(const RawAddress& dest, uint8_t role) { body(dest, role); };
};
extern struct btsnd_hcic_accept_conn btsnd_hcic_accept_conn;
@@ -58,10 +58,11 @@
uint32_t receive_bandwidth, uint16_t max_latency,
uint16_t content_fmt, uint8_t retrans_effort,
uint16_t packet_types)>
- body{[](const RawAddress& bd_addr, uint32_t transmit_bandwidth,
- uint32_t receive_bandwidth, uint16_t max_latency,
- uint16_t content_fmt, uint8_t retrans_effort,
- uint16_t packet_types) {}};
+ body{[](const RawAddress& /* bd_addr */,
+ uint32_t /* transmit_bandwidth */,
+ uint32_t /* receive_bandwidth */, uint16_t /* max_latency */,
+ uint16_t /* content_fmt */, uint8_t /* retrans_effort */,
+ uint16_t /* packet_types */) {}};
void operator()(const RawAddress& bd_addr, uint32_t transmit_bandwidth,
uint32_t receive_bandwidth, uint16_t max_latency,
uint16_t content_fmt, uint8_t retrans_effort,
@@ -77,7 +78,7 @@
// Return: void
struct btsnd_hcic_add_SCO_conn {
std::function<void(uint16_t handle, uint16_t packet_types)> body{
- [](uint16_t handle, uint16_t packet_types) {}};
+ [](uint16_t /* handle */, uint16_t /* packet_types */) {}};
void operator()(uint16_t handle, uint16_t packet_types) {
body(handle, packet_types);
};
@@ -88,7 +89,7 @@
// Params: uint16_t handle
// Return: void
struct btsnd_hcic_auth_request {
- std::function<void(uint16_t handle)> body{[](uint16_t handle) {}};
+ std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) {}};
void operator()(uint16_t handle) { body(handle); };
};
extern struct btsnd_hcic_auth_request btsnd_hcic_auth_request;
@@ -97,7 +98,7 @@
// Params: BD_NAME name
// Return: void
struct btsnd_hcic_change_name {
- std::function<void(BD_NAME name)> body{[](BD_NAME name) {}};
+ std::function<void(BD_NAME name)> body{[](BD_NAME /* name */) {}};
void operator()(BD_NAME name) { body(name); };
};
extern struct btsnd_hcic_change_name btsnd_hcic_change_name;
@@ -107,7 +108,7 @@
// Return: void
struct btsnd_hcic_create_conn_cancel {
std::function<void(const RawAddress& dest)> body{
- [](const RawAddress& dest) {}};
+ [](const RawAddress& /* dest */) {}};
void operator()(const RawAddress& dest) { body(dest); };
};
extern struct btsnd_hcic_create_conn_cancel btsnd_hcic_create_conn_cancel;
@@ -117,7 +118,7 @@
// Return: void
struct btsnd_hcic_delete_stored_key {
std::function<void(const RawAddress& bd_addr, bool delete_all_flag)> body{
- [](const RawAddress& bd_addr, bool delete_all_flag) {}};
+ [](const RawAddress& /* bd_addr */, bool /* delete_all_flag */) {}};
void operator()(const RawAddress& bd_addr, bool delete_all_flag) {
body(bd_addr, delete_all_flag);
};
@@ -138,7 +139,8 @@
// Return: void
struct btsnd_hcic_enhanced_accept_synchronous_connection {
std::function<void(const RawAddress& bd_addr, enh_esco_params_t* p_params)>
- body{[](const RawAddress& bd_addr, enh_esco_params_t* p_params) {}};
+ body{[](const RawAddress& /* bd_addr */,
+ enh_esco_params_t* /* p_params */) {}};
void operator()(const RawAddress& bd_addr, enh_esco_params_t* p_params) {
body(bd_addr, p_params);
};
@@ -151,7 +153,7 @@
// Return: void
struct btsnd_hcic_enhanced_flush {
std::function<void(uint16_t handle, uint8_t packet_type)> body{
- [](uint16_t handle, uint8_t packet_type) {}};
+ [](uint16_t /* handle */, uint8_t /* packet_type */) {}};
void operator()(uint16_t handle, uint8_t packet_type) {
body(handle, packet_type);
};
@@ -163,7 +165,7 @@
// Return: void
struct btsnd_hcic_enhanced_set_up_synchronous_connection {
std::function<void(uint16_t conn_handle, enh_esco_params_t* p_params)> body{
- [](uint16_t conn_handle, enh_esco_params_t* p_params) {}};
+ [](uint16_t /* conn_handle */, enh_esco_params_t* /* p_params */) {}};
void operator()(uint16_t conn_handle, enh_esco_params_t* p_params) {
body(conn_handle, p_params);
};
@@ -175,7 +177,7 @@
// Params: uint16_t handle
// Return: void
struct btsnd_hcic_exit_park_mode {
- std::function<void(uint16_t handle)> body{[](uint16_t handle) {}};
+ std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) {}};
void operator()(uint16_t handle) { body(handle); };
};
extern struct btsnd_hcic_exit_park_mode btsnd_hcic_exit_park_mode;
@@ -184,7 +186,7 @@
// Params: uint16_t handle
// Return: void
struct btsnd_hcic_exit_sniff_mode {
- std::function<void(uint16_t handle)> body{[](uint16_t handle) {}};
+ std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) {}};
void operator()(uint16_t handle) { body(handle); };
};
extern struct btsnd_hcic_exit_sniff_mode btsnd_hcic_exit_sniff_mode;
@@ -195,8 +197,8 @@
struct btsnd_hcic_hold_mode {
std::function<void(uint16_t handle, uint16_t max_hold_period,
uint16_t min_hold_period)>
- body{[](uint16_t handle, uint16_t max_hold_period,
- uint16_t min_hold_period) {}};
+ body{[](uint16_t /* handle */, uint16_t /* max_hold_period */,
+ uint16_t /* min_hold_period */) {}};
void operator()(uint16_t handle, uint16_t max_hold_period,
uint16_t min_hold_period) {
body(handle, max_hold_period, min_hold_period);
@@ -209,7 +211,7 @@
// Return: void
struct btsnd_hcic_io_cap_req_neg_reply {
std::function<void(const RawAddress& bd_addr, uint8_t err_code)> body{
- [](const RawAddress& bd_addr, uint8_t err_code) {}};
+ [](const RawAddress& /* bd_addr */, uint8_t /* err_code */) {}};
void operator()(const RawAddress& bd_addr, uint8_t err_code) {
body(bd_addr, err_code);
};
@@ -222,8 +224,8 @@
struct btsnd_hcic_io_cap_req_reply {
std::function<void(const RawAddress& bd_addr, uint8_t capability,
uint8_t oob_present, uint8_t auth_req)>
- body{[](const RawAddress& bd_addr, uint8_t capability,
- uint8_t oob_present, uint8_t auth_req) {}};
+ body{[](const RawAddress& /* bd_addr */, uint8_t /* capability */,
+ uint8_t /* oob_present */, uint8_t /* auth_req */) {}};
void operator()(const RawAddress& bd_addr, uint8_t capability,
uint8_t oob_present, uint8_t auth_req) {
body(bd_addr, capability, oob_present, auth_req);
@@ -236,7 +238,7 @@
// Return: void
struct btsnd_hcic_link_key_neg_reply {
std::function<void(const RawAddress& bd_addr)> body{
- [](const RawAddress& bd_addr) {}};
+ [](const RawAddress& /* bd_addr */) {}};
void operator()(const RawAddress& bd_addr) { body(bd_addr); };
};
extern struct btsnd_hcic_link_key_neg_reply btsnd_hcic_link_key_neg_reply;
@@ -246,7 +248,7 @@
// Return: void
struct btsnd_hcic_link_key_req_reply {
std::function<void(const RawAddress& bd_addr, const LinkKey& link_key)> body{
- [](const RawAddress& bd_addr, const LinkKey& link_key) {}};
+ [](const RawAddress& /* bd_addr */, const LinkKey& /* link_key */) {}};
void operator()(const RawAddress& bd_addr, const LinkKey& link_key) {
body(bd_addr, link_key);
};
@@ -259,8 +261,8 @@
struct btsnd_hcic_park_mode {
std::function<void(uint16_t handle, uint16_t beacon_max_interval,
uint16_t beacon_min_interval)>
- body{[](uint16_t handle, uint16_t beacon_max_interval,
- uint16_t beacon_min_interval) {}};
+ body{[](uint16_t /* handle */, uint16_t /* beacon_max_interval */,
+ uint16_t /* beacon_min_interval */) {}};
void operator()(uint16_t handle, uint16_t beacon_max_interval,
uint16_t beacon_min_interval) {
body(handle, beacon_max_interval, beacon_min_interval);
@@ -273,7 +275,7 @@
// Return: void
struct btsnd_hcic_pin_code_neg_reply {
std::function<void(const RawAddress& bd_addr)> body{
- [](const RawAddress& bd_addr) {}};
+ [](const RawAddress& /* bd_addr */) {}};
void operator()(const RawAddress& bd_addr) { body(bd_addr); };
};
extern struct btsnd_hcic_pin_code_neg_reply btsnd_hcic_pin_code_neg_reply;
@@ -284,8 +286,8 @@
struct btsnd_hcic_pin_code_req_reply {
std::function<void(const RawAddress& bd_addr, uint8_t pin_code_len,
PIN_CODE pin_code)>
- body{[](const RawAddress& bd_addr, uint8_t pin_code_len,
- PIN_CODE pin_code) {}};
+ body{[](const RawAddress& /* bd_addr */, uint8_t /* pin_code_len */,
+ PIN_CODE /* pin_code */) {}};
void operator()(const RawAddress& bd_addr, uint8_t pin_code_len,
PIN_CODE pin_code) {
body(bd_addr, pin_code_len, pin_code);
@@ -298,7 +300,7 @@
// Return: void
struct btsnd_hcic_read_encryption_key_size {
std::function<void(uint16_t handle, ReadEncKeySizeCb cb)> body{
- [](uint16_t handle, ReadEncKeySizeCb cb) {}};
+ [](uint16_t /* handle */, ReadEncKeySizeCb /* cb */) {}};
void operator()(uint16_t handle, ReadEncKeySizeCb cb) {
body(handle, std::move(cb));
};
@@ -310,7 +312,7 @@
// Params: uint16_t handle
// Return: void
struct btsnd_hcic_read_failed_contact_counter {
- std::function<void(uint16_t handle)> body{[](uint16_t handle) {}};
+ std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) {}};
void operator()(uint16_t handle) { body(handle); };
};
extern struct btsnd_hcic_read_failed_contact_counter
@@ -338,7 +340,7 @@
// Params: uint16_t handle
// Return: void
struct btsnd_hcic_read_rmt_clk_offset {
- std::function<void(uint16_t handle)> body{[](uint16_t handle) {}};
+ std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) {}};
void operator()(uint16_t handle) { body(handle); };
};
extern struct btsnd_hcic_read_rmt_clk_offset btsnd_hcic_read_rmt_clk_offset;
@@ -347,7 +349,7 @@
// Params: uint16_t handle
// Return: void
struct btsnd_hcic_read_rssi {
- std::function<void(uint16_t handle)> body{[](uint16_t handle) {}};
+ std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) {}};
void operator()(uint16_t handle) { body(handle); };
};
extern struct btsnd_hcic_read_rssi btsnd_hcic_read_rssi;
@@ -357,7 +359,7 @@
// Return: void
struct btsnd_hcic_read_tx_power {
std::function<void(uint16_t handle, uint8_t type)> body{
- [](uint16_t handle, uint8_t type) {}};
+ [](uint16_t /* handle */, uint8_t /* type */) {}};
void operator()(uint16_t handle, uint8_t type) { body(handle, type); };
};
extern struct btsnd_hcic_read_tx_power btsnd_hcic_read_tx_power;
@@ -367,7 +369,7 @@
// Return: void
struct btsnd_hcic_reject_conn {
std::function<void(const RawAddress& dest, uint8_t reason)> body{
- [](const RawAddress& dest, uint8_t reason) {}};
+ [](const RawAddress& /* dest */, uint8_t /* reason */) {}};
void operator()(const RawAddress& dest, uint8_t reason) {
body(dest, reason);
};
@@ -379,7 +381,7 @@
// Return: void
struct btsnd_hcic_reject_esco_conn {
std::function<void(const RawAddress& bd_addr, uint8_t reason)> body{
- [](const RawAddress& bd_addr, uint8_t reason) {}};
+ [](const RawAddress& /* bd_addr */, uint8_t /* reason */) {}};
void operator()(const RawAddress& bd_addr, uint8_t reason) {
body(bd_addr, reason);
};
@@ -391,7 +393,7 @@
// Return: void
struct btsnd_hcic_rem_oob_neg_reply {
std::function<void(const RawAddress& bd_addr)> body{
- [](const RawAddress& bd_addr) {}};
+ [](const RawAddress& /* bd_addr */) {}};
void operator()(const RawAddress& bd_addr) { body(bd_addr); };
};
extern struct btsnd_hcic_rem_oob_neg_reply btsnd_hcic_rem_oob_neg_reply;
@@ -402,8 +404,8 @@
struct btsnd_hcic_rem_oob_reply {
std::function<void(const RawAddress& bd_addr, const Octet16& c,
const Octet16& r)>
- body{
- [](const RawAddress& bd_addr, const Octet16& c, const Octet16& r) {}};
+ body{[](const RawAddress& /* bd_addr */, const Octet16& /* c */,
+ const Octet16& /* r */) {}};
void operator()(const RawAddress& bd_addr, const Octet16& c,
const Octet16& r) {
body(bd_addr, c, r);
@@ -416,7 +418,7 @@
// Return: void
struct btsnd_hcic_rmt_ext_features {
std::function<void(uint16_t handle, uint8_t page_num)> body{
- [](uint16_t handle, uint8_t page_num) {}};
+ [](uint16_t /* handle */, uint8_t /* page_num */) {}};
void operator()(uint16_t handle, uint8_t page_num) {
body(handle, page_num);
};
@@ -429,8 +431,8 @@
struct btsnd_hcic_rmt_name_req {
std::function<void(const RawAddress& bd_addr, uint8_t page_scan_rep_mode,
uint8_t page_scan_mode, uint16_t clock_offset)>
- body{[](const RawAddress& bd_addr, uint8_t page_scan_rep_mode,
- uint8_t page_scan_mode, uint16_t clock_offset) {}};
+ body{[](const RawAddress& /* bd_addr */, uint8_t /* page_scan_rep_mode */,
+ uint8_t /* page_scan_mode */, uint16_t /* clock_offset */) {}};
void operator()(const RawAddress& bd_addr, uint8_t page_scan_rep_mode,
uint8_t page_scan_mode, uint16_t clock_offset) {
body(bd_addr, page_scan_rep_mode, page_scan_mode, clock_offset);
@@ -443,7 +445,7 @@
// Return: void
struct btsnd_hcic_rmt_name_req_cancel {
std::function<void(const RawAddress& bd_addr)> body{
- [](const RawAddress& bd_addr) {}};
+ [](const RawAddress& /* bd_addr */) {}};
void operator()(const RawAddress& bd_addr) { body(bd_addr); };
};
extern struct btsnd_hcic_rmt_name_req_cancel btsnd_hcic_rmt_name_req_cancel;
@@ -452,7 +454,7 @@
// Params: uint16_t handle
// Return: void
struct btsnd_hcic_rmt_ver_req {
- std::function<void(uint16_t handle)> body{[](uint16_t handle) {}};
+ std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) {}};
void operator()(uint16_t handle) { body(handle); };
};
extern struct btsnd_hcic_rmt_ver_req btsnd_hcic_rmt_ver_req;
@@ -462,7 +464,7 @@
// Return: void
struct btsnd_hcic_set_conn_encrypt {
std::function<void(uint16_t handle, bool enable)> body{
- [](uint16_t handle, bool enable) {}};
+ [](uint16_t /* handle */, bool /* enable */) {}};
void operator()(uint16_t handle, bool enable) { body(handle, enable); };
};
extern struct btsnd_hcic_set_conn_encrypt btsnd_hcic_set_conn_encrypt;
@@ -473,8 +475,8 @@
struct btsnd_hcic_set_event_filter {
std::function<void(uint8_t filt_type, uint8_t filt_cond_type,
uint8_t* filt_cond, uint8_t filt_cond_len)>
- body{[](uint8_t filt_type, uint8_t filt_cond_type, uint8_t* filt_cond,
- uint8_t filt_cond_len) {}};
+ body{[](uint8_t /* filt_type */, uint8_t /* filt_cond_type */,
+ uint8_t* /* filt_cond */, uint8_t /* filt_cond_len */) {}};
void operator()(uint8_t filt_type, uint8_t filt_cond_type, uint8_t* filt_cond,
uint8_t filt_cond_len) {
body(filt_type, filt_cond_type, filt_cond, filt_cond_len);
@@ -491,9 +493,10 @@
uint32_t receive_bandwidth, uint16_t max_latency,
uint16_t voice, uint8_t retrans_effort,
uint16_t packet_types)>
- body{[](uint16_t handle, uint32_t transmit_bandwidth,
- uint32_t receive_bandwidth, uint16_t max_latency, uint16_t voice,
- uint8_t retrans_effort, uint16_t packet_types) {}};
+ body{[](uint16_t /* handle */, uint32_t /* transmit_bandwidth */,
+ uint32_t /* receive_bandwidth */, uint16_t /* max_latency */,
+ uint16_t /* voice */, uint8_t /* retrans_effort */,
+ uint16_t /* packet_types */) {}};
void operator()(uint16_t handle, uint32_t transmit_bandwidth,
uint32_t receive_bandwidth, uint16_t max_latency,
uint16_t voice, uint8_t retrans_effort,
@@ -511,9 +514,9 @@
std::function<void(uint16_t handle, uint16_t max_sniff_period,
uint16_t min_sniff_period, uint16_t sniff_attempt,
uint16_t sniff_timeout)>
- body{[](uint16_t handle, uint16_t max_sniff_period,
- uint16_t min_sniff_period, uint16_t sniff_attempt,
- uint16_t sniff_timeout) {}};
+ body{[](uint16_t /* handle */, uint16_t /* max_sniff_period */,
+ uint16_t /* min_sniff_period */, uint16_t /* sniff_attempt */,
+ uint16_t /* sniff_timeout */) {}};
void operator()(uint16_t handle, uint16_t max_sniff_period,
uint16_t min_sniff_period, uint16_t sniff_attempt,
uint16_t sniff_timeout) {
@@ -529,8 +532,8 @@
struct btsnd_hcic_sniff_sub_rate {
std::function<void(uint16_t handle, uint16_t max_lat, uint16_t min_remote_lat,
uint16_t min_local_lat)>
- body{[](uint16_t handle, uint16_t max_lat, uint16_t min_remote_lat,
- uint16_t min_local_lat) {}};
+ body{[](uint16_t /* handle */, uint16_t /* max_lat */,
+ uint16_t /* min_remote_lat */, uint16_t /* min_local_lat */) {}};
void operator()(uint16_t handle, uint16_t max_lat, uint16_t min_remote_lat,
uint16_t min_local_lat) {
body(handle, max_lat, min_remote_lat, min_local_lat);
@@ -543,7 +546,7 @@
// Return: void
struct btsnd_hcic_user_conf_reply {
std::function<void(const RawAddress& bd_addr, bool is_yes)> body{
- [](const RawAddress& bd_addr, bool is_yes) {}};
+ [](const RawAddress& /* bd_addr */, bool /* is_yes */) {}};
void operator()(const RawAddress& bd_addr, bool is_yes) {
body(bd_addr, is_yes);
};
@@ -555,7 +558,7 @@
// Return: void
struct btsnd_hcic_user_passkey_neg_reply {
std::function<void(const RawAddress& bd_addr)> body{
- [](const RawAddress& bd_addr) {}};
+ [](const RawAddress& /* bd_addr */) {}};
void operator()(const RawAddress& bd_addr) { body(bd_addr); };
};
extern struct btsnd_hcic_user_passkey_neg_reply
@@ -566,7 +569,7 @@
// Return: void
struct btsnd_hcic_user_passkey_reply {
std::function<void(const RawAddress& bd_addr, uint32_t value)> body{
- [](const RawAddress& bd_addr, uint32_t value) {}};
+ [](const RawAddress& /* bd_addr */, uint32_t /* value */) {}};
void operator()(const RawAddress& bd_addr, uint32_t value) {
body(bd_addr, value);
};
@@ -579,8 +582,8 @@
struct btsnd_hcic_vendor_spec_cmd {
std::function<void(uint16_t opcode, uint8_t len, uint8_t* p_data,
tBTM_VSC_CMPL_CB* p_cmd_cplt_cback)>
- body{[](uint16_t opcode, uint8_t len, uint8_t* p_data,
- tBTM_VSC_CMPL_CB* p_cmd_cplt_cback) {}};
+ body{[](uint16_t /* opcode */, uint8_t /* len */, uint8_t* /* p_data */,
+ tBTM_VSC_CMPL_CB* /* p_cmd_cplt_cback */) {}};
void operator()(uint16_t opcode, uint8_t len, uint8_t* p_data,
tBTM_VSC_CMPL_CB* p_cmd_cplt_cback) {
body(opcode, len, p_data, p_cmd_cplt_cback);
@@ -592,7 +595,7 @@
// Params: uint8_t flag
// Return: void
struct btsnd_hcic_write_auth_enable {
- std::function<void(uint8_t flag)> body{[](uint8_t flag) {}};
+ std::function<void(uint8_t flag)> body{[](uint8_t /* flag */) {}};
void operator()(uint8_t flag) { body(flag); };
};
extern struct btsnd_hcic_write_auth_enable btsnd_hcic_write_auth_enable;
@@ -602,7 +605,7 @@
// Return: void
struct btsnd_hcic_write_auto_flush_tout {
std::function<void(uint16_t handle, uint16_t tout)> body{
- [](uint16_t handle, uint16_t tout) {}};
+ [](uint16_t /* handle */, uint16_t /* tout */) {}};
void operator()(uint16_t handle, uint16_t tout) { body(handle, tout); };
};
extern struct btsnd_hcic_write_auto_flush_tout btsnd_hcic_write_auto_flush_tout;
@@ -612,7 +615,7 @@
// Return: void
struct btsnd_hcic_write_cur_iac_lap {
std::function<void(uint8_t num_cur_iac, LAP* const iac_lap)> body{
- [](uint8_t num_cur_iac, LAP* const iac_lap) {}};
+ [](uint8_t /* num_cur_iac */, LAP* const /* iac_lap */) {}};
void operator()(uint8_t num_cur_iac, LAP* const iac_lap) {
body(num_cur_iac, iac_lap);
};
@@ -623,7 +626,7 @@
// Params: uint16_t settings
// Return: void
struct btsnd_hcic_write_def_policy_set {
- std::function<void(uint16_t settings)> body{[](uint16_t settings) {}};
+ std::function<void(uint16_t settings)> body{[](uint16_t /* settings */) {}};
void operator()(uint16_t settings) { body(settings); };
};
extern struct btsnd_hcic_write_def_policy_set btsnd_hcic_write_def_policy_set;
@@ -632,7 +635,8 @@
// Params: DEV_CLASS dev_class
// Return: void
struct btsnd_hcic_write_dev_class {
- std::function<void(DEV_CLASS dev_class)> body{[](DEV_CLASS dev_class) {}};
+ std::function<void(DEV_CLASS dev_class)> body{
+ [](DEV_CLASS /* dev_class */) {}};
void operator()(DEV_CLASS dev_class) { body(dev_class); };
};
extern struct btsnd_hcic_write_dev_class btsnd_hcic_write_dev_class;
@@ -642,7 +646,7 @@
// Return: void
struct btsnd_hcic_write_ext_inquiry_response {
std::function<void(void* buffer, uint8_t fec_req)> body{
- [](void* buffer, uint8_t fec_req) {}};
+ [](void* /* buffer */, uint8_t /* fec_req */) {}};
void operator()(void* buffer, uint8_t fec_req) { body(buffer, fec_req); };
};
extern struct btsnd_hcic_write_ext_inquiry_response
@@ -653,7 +657,7 @@
// Return: void
struct btsnd_hcic_write_inqscan_cfg {
std::function<void(uint16_t interval, uint16_t window)> body{
- [](uint16_t interval, uint16_t window) {}};
+ [](uint16_t /* interval */, uint16_t /* window */) {}};
void operator()(uint16_t interval, uint16_t window) {
body(interval, window);
};
@@ -664,7 +668,7 @@
// Params: uint8_t type
// Return: void
struct btsnd_hcic_write_inqscan_type {
- std::function<void(uint8_t type)> body{[](uint8_t type) {}};
+ std::function<void(uint8_t type)> body{[](uint8_t /* type */) {}};
void operator()(uint8_t type) { body(type); };
};
extern struct btsnd_hcic_write_inqscan_type btsnd_hcic_write_inqscan_type;
@@ -673,7 +677,7 @@
// Params: uint8_t mode
// Return: void
struct btsnd_hcic_write_inquiry_mode {
- std::function<void(uint8_t mode)> body{[](uint8_t mode) {}};
+ std::function<void(uint8_t mode)> body{[](uint8_t /* mode */) {}};
void operator()(uint8_t mode) { body(mode); };
};
extern struct btsnd_hcic_write_inquiry_mode btsnd_hcic_write_inquiry_mode;
@@ -683,7 +687,7 @@
// Return: void
struct btsnd_hcic_write_link_super_tout {
std::function<void(uint16_t handle, uint16_t timeout)> body{
- [](uint16_t handle, uint16_t timeout) {}};
+ [](uint16_t /* handle */, uint16_t /* timeout */) {}};
void operator()(uint16_t handle, uint16_t timeout) { body(handle, timeout); };
};
extern struct btsnd_hcic_write_link_super_tout btsnd_hcic_write_link_super_tout;
@@ -692,7 +696,7 @@
// Params: uint16_t timeout
// Return: void
struct btsnd_hcic_write_page_tout {
- std::function<void(uint16_t timeout)> body{[](uint16_t timeout) {}};
+ std::function<void(uint16_t timeout)> body{[](uint16_t /* timeout */) {}};
void operator()(uint16_t timeout) { body(timeout); };
};
extern struct btsnd_hcic_write_page_tout btsnd_hcic_write_page_tout;
@@ -702,7 +706,7 @@
// Return: void
struct btsnd_hcic_write_pagescan_cfg {
std::function<void(uint16_t interval, uint16_t window)> body{
- [](uint16_t interval, uint16_t window) {}};
+ [](uint16_t /* interval */, uint16_t /* window */) {}};
void operator()(uint16_t interval, uint16_t window) {
body(interval, window);
};
@@ -713,7 +717,7 @@
// Params: uint8_t type
// Return: void
struct btsnd_hcic_write_pagescan_type {
- std::function<void(uint8_t type)> body{[](uint8_t type) {}};
+ std::function<void(uint8_t type)> body{[](uint8_t /* type */) {}};
void operator()(uint8_t type) { body(type); };
};
extern struct btsnd_hcic_write_pagescan_type btsnd_hcic_write_pagescan_type;
@@ -722,7 +726,7 @@
// Params: uint8_t type
// Return: void
struct btsnd_hcic_write_pin_type {
- std::function<void(uint8_t type)> body{[](uint8_t type) {}};
+ std::function<void(uint8_t type)> body{[](uint8_t /* type */) {}};
void operator()(uint8_t type) { body(type); };
};
extern struct btsnd_hcic_write_pin_type btsnd_hcic_write_pin_type;
@@ -732,7 +736,7 @@
// Return: void
struct btsnd_hcic_write_policy_set {
std::function<void(uint16_t handle, uint16_t settings)> body{
- [](uint16_t handle, uint16_t settings) {}};
+ [](uint16_t /* handle */, uint16_t /* settings */) {}};
void operator()(uint16_t handle, uint16_t settings) {
body(handle, settings);
};
@@ -743,7 +747,7 @@
// Params: uint8_t flag
// Return: void
struct btsnd_hcic_write_scan_enable {
- std::function<void(uint8_t flag)> body{[](uint8_t flag) {}};
+ std::function<void(uint8_t flag)> body{[](uint8_t /* flag */) {}};
void operator()(uint8_t flag) { body(flag); };
};
extern struct btsnd_hcic_write_scan_enable btsnd_hcic_write_scan_enable;
@@ -752,7 +756,7 @@
// Params: uint16_t flags
// Return: void
struct btsnd_hcic_write_voice_settings {
- std::function<void(uint16_t flags)> body{[](uint16_t flags) {}};
+ std::function<void(uint16_t flags)> body{[](uint16_t /* flags */) {}};
void operator()(uint16_t flags) { body(flags); };
};
extern struct btsnd_hcic_write_voice_settings btsnd_hcic_write_voice_settings;
diff --git a/system/test/mock/mock_stack_metrics_logging.h b/system/test/mock/mock_stack_metrics_logging.h
index fd34980..ca938a6 100644
--- a/system/test/mock/mock_stack_metrics_logging.h
+++ b/system/test/mock/mock_stack_metrics_logging.h
@@ -44,9 +44,10 @@
std::function<void(const RawAddress& address, uint16_t handle,
uint32_t hci_cmd, uint16_t hci_event, uint16_t cmd_status,
uint16_t reason_code, int64_t event_value)>
- body{[](const RawAddress& address, uint16_t handle, uint32_t hci_cmd,
- uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code,
- int64_t event_value) {}};
+ body{[](const RawAddress& /* address */, uint16_t /* handle */,
+ uint32_t /* hci_cmd */, uint16_t /* hci_event */,
+ uint16_t /* cmd_status */, uint16_t /* reason_code */,
+ int64_t /* event_value */) {}};
void operator()(const RawAddress& address, uint16_t handle, uint32_t hci_cmd,
uint16_t hci_event, uint16_t cmd_status, uint16_t reason_code,
int64_t event_value) {
@@ -66,10 +67,11 @@
uint16_t link_type, uint32_t hci_cmd, uint16_t hci_event,
uint16_t hci_ble_event, uint16_t cmd_status,
uint16_t reason_code)>
- body{[](const RawAddress* address, uint32_t connection_handle,
- android::bluetooth::DirectionEnum direction, uint16_t link_type,
- uint32_t hci_cmd, uint16_t hci_event, uint16_t hci_ble_event,
- uint16_t cmd_status, uint16_t reason_code) {}};
+ body{[](const RawAddress* /* address */, uint32_t /* connection_handle */,
+ android::bluetooth::DirectionEnum /* direction */,
+ uint16_t /* link_type */, uint32_t /* hci_cmd */,
+ uint16_t /* hci_event */, uint16_t /* hci_ble_event */,
+ uint16_t /* cmd_status */, uint16_t /* reason_code */) {}};
void operator()(const RawAddress* address, uint32_t connection_handle,
android::bluetooth::DirectionEnum direction,
uint16_t link_type, uint32_t hci_cmd, uint16_t hci_event,
@@ -88,9 +90,9 @@
std::function<void(const RawAddress& address, uint16_t smp_cmd,
android::bluetooth::DirectionEnum direction,
uint16_t smp_fail_reason)>
- body{[](const RawAddress& address, uint16_t smp_cmd,
- android::bluetooth::DirectionEnum direction,
- uint16_t smp_fail_reason) {}};
+ body{[](const RawAddress& /* address */, uint16_t /* smp_cmd */,
+ android::bluetooth::DirectionEnum /* direction */,
+ uint16_t /* smp_fail_reason */) {}};
void operator()(const RawAddress& address, uint16_t smp_cmd,
android::bluetooth::DirectionEnum direction,
uint16_t smp_fail_reason) {
@@ -106,9 +108,9 @@
std::function<void(const RawAddress& address, uint16_t protocol_uuid,
uint16_t attribute_id, size_t attribute_size,
const char* attribute_value)>
- body{[](const RawAddress& address, uint16_t protocol_uuid,
- uint16_t attribute_id, size_t attribute_size,
- const char* attribute_value) {}};
+ body{[](const RawAddress& /* address */, uint16_t /* protocol_uuid */,
+ uint16_t /* attribute_id */, size_t /* attribute_size */,
+ const char* /* attribute_value */) {}};
void operator()(const RawAddress& address, uint16_t protocol_uuid,
uint16_t attribute_id, size_t attribute_size,
const char* attribute_value) {
@@ -129,12 +131,14 @@
const std::string& manufacturer, const std::string& model,
const std::string& hardware_version,
const std::string& software_version)>
- body2{[](const RawAddress& address,
- android::bluetooth::AddressTypeEnum address_type,
- android::bluetooth::DeviceInfoSrcEnum source_type,
- const std::string& source_name, const std::string& manufacturer,
- const std::string& model, const std::string& hardware_version,
- const std::string& software_version) {}};
+ body2{[](const RawAddress& /* address */,
+ android::bluetooth::AddressTypeEnum /* address_type */,
+ android::bluetooth::DeviceInfoSrcEnum /* source_type */,
+ const std::string& /* source_name */,
+ const std::string& /* manufacturer */,
+ const std::string& /* model */,
+ const std::string& /* hardware_version */,
+ const std::string& /* software_version */) {}};
void operator()(const RawAddress& address,
android::bluetooth::AddressTypeEnum address_type,
android::bluetooth::DeviceInfoSrcEnum source_type,
@@ -151,11 +155,13 @@
const std::string& manufacturer, const std::string& model,
const std::string& hardware_version,
const std::string& software_version)>
- body{[](const RawAddress& address,
- android::bluetooth::DeviceInfoSrcEnum source_type,
- const std::string& source_name, const std::string& manufacturer,
- const std::string& model, const std::string& hardware_version,
- const std::string& software_version) {}};
+ body{[](const RawAddress& /* address */,
+ android::bluetooth::DeviceInfoSrcEnum /* source_type */,
+ const std::string& /* source_name */,
+ const std::string& /* manufacturer */,
+ const std::string& /* model */,
+ const std::string& /* hardware_version */,
+ const std::string& /* software_version */) {}};
void operator()(const RawAddress& address,
android::bluetooth::DeviceInfoSrcEnum source_type,
const std::string& source_name,
@@ -172,8 +178,8 @@
struct log_counter_metrics {
std::function<void(android::bluetooth::CodePathCounterKeyEnum key,
int64_t value)>
- body{
- [](android::bluetooth::CodePathCounterKeyEnum key, int64_t value) {}};
+ body{[](android::bluetooth::CodePathCounterKeyEnum /* key */,
+ int64_t /* value */) {}};
void operator()(android::bluetooth::CodePathCounterKeyEnum key,
int64_t value) {
body(key, value);
@@ -185,8 +191,8 @@
struct log_hfp_audio_packet_loss_stats {
std::function<void(const RawAddress& address, int num_decoded_frames,
double packet_loss_ratio, uint16_t codec_type)>
- body{[](const RawAddress& address, int num_decoded_frames,
- double packet_loss_ratio, uint16_t codec_type) {}};
+ body{[](const RawAddress& /* address */, int /* num_decoded_frames */,
+ double /* packet_loss_ratio */, uint16_t /* codec_type */) {}};
void operator()(const RawAddress& address, int num_decoded_frames,
double packet_loss_ratio, uint16_t codec_type) {
body(address, num_decoded_frames, packet_loss_ratio, codec_type);
@@ -198,8 +204,8 @@
struct log_mmc_transcode_rtt_stats {
std::function<void(int maximum_rtt, double mean_rtt, int num_requests,
int codec_type)>
- body{[](int maximum_rtt, double mean_rtt, int num_requests,
- int codec_type) {}};
+ body{[](int /* maximum_rtt */, double /* mean_rtt */,
+ int /* num_requests */, int /* codec_type */) {}};
void operator()(int maximum_rtt, double mean_rtt, int num_requests,
int codec_type) {
body(maximum_rtt, mean_rtt, num_requests, codec_type);
diff --git a/system/test/stub/osi.cc b/system/test/stub/osi.cc
index 6643ad7..894c009 100644
--- a/system/test/stub/osi.cc
+++ b/system/test/stub/osi.cc
@@ -26,6 +26,7 @@
#include <map>
#include <string>
+#include "os/log.h"
#include "osi/include/alarm.h"
#include "osi/include/allocator.h"
#include "osi/include/config.h"
@@ -33,7 +34,6 @@
#include "osi/include/future.h"
#include "osi/include/hash_map_utils.h"
#include "osi/include/list.h"
-#include "osi/include/log.h"
#include "osi/include/reactor.h"
#include "osi/include/ringbuffer.h"
#include "osi/include/socket.h"
@@ -47,6 +47,22 @@
#define UNUSED_ATTR
#endif
+OsiObject::OsiObject(void* ptr) : ptr_(ptr) {}
+
+OsiObject::OsiObject(const void* ptr) : ptr_(const_cast<void*>(ptr)) {}
+
+OsiObject::~OsiObject() {
+ if (ptr_ != nullptr) {
+ osi_free(ptr_);
+ }
+}
+
+void* OsiObject::Release() {
+ void* ptr = ptr_;
+ ptr_ = nullptr;
+ return ptr;
+}
+
struct StringComparison {
bool operator()(char const* lhs, char const* rhs) const {
return strcmp(lhs, rhs) < 0;
diff --git a/system/test/tool/mockcify.pl b/system/test/tool/mockcify.pl
index dd974c0..724f26d 100755
--- a/system/test/tool/mockcify.pl
+++ b/system/test/tool/mockcify.pl
@@ -264,7 +264,7 @@
my $link="test/mock/$hdr";
unlink "$INCDIR/$link";
symlink "$OUTDIR/$hdr", "$INCDIR/$link";
- system("$CC -c -std=c++17 -o /dev/null -D" . join(" -D", @defs) . " -I" . join(" -I", @incs) . " $OUTDIR/$src");
+ system("$CC -c -std=c++20 -o /dev/null -D" . join(" -D", @defs) . " -I" . join(" -I", @incs) . " $OUTDIR/$src");
my $rc = $?;
($? == 0)
? printf(STDERR "SUCCESS Compiled unit \'$src\'\n")
diff --git a/system/types/Android.bp b/system/types/Android.bp
index 8ff1cd0..742d6d3 100644
--- a/system/types/Android.bp
+++ b/system/types/Android.bp
@@ -67,6 +67,7 @@
],
include_dirs: [
"packages/modules/Bluetooth/system",
+ "packages/modules/Bluetooth/system/include",
],
host_supported: true,
srcs: [
diff --git a/system/types/ble_address_with_type.h b/system/types/ble_address_with_type.h
index 90aefdd..5c0f531 100644
--- a/system/types/ble_address_with_type.h
+++ b/system/types/ble_address_with_type.h
@@ -18,6 +18,8 @@
#include <cstdint>
#include <string>
+
+#include "types/bt_transport.h"
#include "types/raw_address.h"
#define BLE_ADDR_PUBLIC 0x00
@@ -149,4 +151,40 @@
}
};
+struct tAclLinkSpec {
+ tBLE_BD_ADDR addrt;
+ tBT_TRANSPORT transport;
+
+ bool operator==(const tAclLinkSpec rhs) const {
+ if (rhs.addrt != addrt) return false;
+
+ if (rhs.transport == BT_TRANSPORT_AUTO || transport == BT_TRANSPORT_AUTO) {
+ return true;
+ }
+
+ return rhs.transport == transport;
+ }
+
+ bool operator!=(const tAclLinkSpec rhs) const { return !(*this == rhs); }
+
+ bool StrictlyEquals(const tAclLinkSpec rhs) const {
+ return rhs.addrt == addrt && rhs.transport == transport;
+ }
+
+ std::string ToString() const {
+ return std::string(addrt.ToString() + "[" + bt_transport_text(transport) +
+ "]");
+ }
+
+ std::string ToStringForLogging() const {
+ return addrt.ToStringForLogging() + "[" + bt_transport_text(transport) +
+ "]";
+ }
+
+ std::string ToRedactedStringForLogging() const {
+ return addrt.ToRedactedStringForLogging() + "[" +
+ bt_transport_text(transport) + "]";
+ }
+};
+
#endif
diff --git a/system/types/bluetooth/uuid.h b/system/types/bluetooth/uuid.h
index f3e6ec2..0bdab40 100644
--- a/system/types/bluetooth/uuid.h
+++ b/system/types/bluetooth/uuid.h
@@ -19,6 +19,7 @@
#pragma once
#include <stdint.h>
+
#include <array>
#include <string>
@@ -145,3 +146,16 @@
};
} // namespace std
+
+// This file is used outside bluetooth in components
+// that do not have access to bluetooth/log.h
+#if __has_include(<bluetooth/log.h>)
+
+#include <bluetooth/log.h>
+
+namespace fmt {
+template <>
+struct formatter<bluetooth::Uuid> : ostream_formatter {};
+} // namespace fmt
+
+#endif // __has_include(<bluetooth/log.h>)
diff --git a/system/types/hci_role.h b/system/types/hci_role.h
index eb582b8..bdd0940 100644
--- a/system/types/hci_role.h
+++ b/system/types/hci_role.h
@@ -47,3 +47,14 @@
typedef tHCI_ROLE hci_role_t; // LEGACY
const auto RoleText = hci_role_text; // LEGACY
+
+#if __has_include(<bluetooth/log.h>)
+
+#include <bluetooth/log.h>
+
+namespace fmt {
+template <>
+struct formatter<tHCI_ROLE> : enum_formatter<tHCI_ROLE> {};
+} // namespace fmt
+
+#endif // __has_include(<bluetooth/log.h>)
diff --git a/system/types/test/ble_address_with_type_unittest.cc b/system/types/test/ble_address_with_type_unittest.cc
index 5332d99..60eaffb 100644
--- a/system/types/test/ble_address_with_type_unittest.cc
+++ b/system/types/test/ble_address_with_type_unittest.cc
@@ -17,6 +17,8 @@
#include "types/ble_address_with_type.h"
#include <gtest/gtest.h>
+static constexpr uint8_t RAW_ADDRESS_TEST1[6] = {0x01, 0x02, 0x03,
+ 0x04, 0x05, 0x06};
TEST(BleAddressWithTypeTest, to_ble_addr_type) {
for (unsigned i = 0; i < 0xff + 1; i++) {
@@ -97,6 +99,23 @@
}
}
+TEST(BleAddressWithTypeTest, TYPED_ADDRESS_TRANSPORT) {
+ tAclLinkSpec linkSpecA = {{BLE_ADDR_PUBLIC, RAW_ADDRESS_TEST1},
+ BT_TRANSPORT_AUTO};
+ tAclLinkSpec linkSpecB = {{BLE_ADDR_PUBLIC, RAW_ADDRESS_TEST1},
+ BT_TRANSPORT_BR_EDR};
+ tAclLinkSpec linkSpecC = {{BLE_ADDR_PUBLIC, RAW_ADDRESS_TEST1},
+ BT_TRANSPORT_LE};
+
+ ASSERT_EQ(linkSpecA, linkSpecB);
+ ASSERT_EQ(linkSpecA, linkSpecC);
+ ASSERT_NE(linkSpecB, linkSpecC);
+
+ ASSERT_FALSE(linkSpecA.StrictlyEquals(linkSpecB));
+ ASSERT_FALSE(linkSpecA.StrictlyEquals(linkSpecC));
+ ASSERT_FALSE(linkSpecB.StrictlyEquals(linkSpecC));
+}
+
TEST(BleAddressWithTypeTest, BLE_ADDR_TYPE_TO_STREAM) {
uint8_t buf[256] = {0};
uint8_t* p = buf;
diff --git a/system/udrv/BUILD.gn b/system/udrv/BUILD.gn
index 05561b8..2c872d6 100644
--- a/system/udrv/BUILD.gn
+++ b/system/udrv/BUILD.gn
@@ -28,6 +28,7 @@
configs += [
"//bt/system:target_defaults",
+ "//bt/system/log:log_defaults",
]
deps = [
diff --git a/tools/rootcanal/Android.bp b/tools/rootcanal/Android.bp
index 386de78..910ca1b 100644
--- a/tools/rootcanal/Android.bp
+++ b/tools/rootcanal/Android.bp
@@ -38,7 +38,7 @@
misc_undefined: ["bounds"],
},
c_std: "c99",
- cpp_std: "c++17",
+ cpp_std: "c++20",
cflags: [
"-DGOOGLE_PROTOBUF_NO_RTTI",
"-Wall",